text stringlengths 8 4.13M |
|---|
use super::*;
use tcp_typed::Notifier;
#[derive(Debug)]
pub enum Inner {
Connecting(InnerConnecting),
ConnectingLocalClosed(InnerConnectingLocalClosed),
Connected(InnerConnected),
RemoteClosed(InnerRemoteClosed),
LocalClosed(InnerLocalClosed),
Closing(InnerClosing),
Closed,
Killed,
}
impl Inner {
pub fn connect(
local: net::SocketAddr, remote: net::SocketAddr, incoming: Option<Connection>,
notifier: &impl Notifier,
) -> Self {
InnerConnecting::new(local, remote, incoming, notifier).into()
}
pub fn poll(&mut self, notifier: &impl Notifier) {
*self = match mem::replace(self, Inner::Killed) {
Inner::Connecting(connecting) => connecting.poll(notifier).into(),
Inner::ConnectingLocalClosed(connecting_local_closed) => {
connecting_local_closed.poll(notifier).into()
}
Inner::Connected(connecting) => connecting.poll(notifier).into(),
Inner::RemoteClosed(remote_closed) => remote_closed.poll(notifier).into(),
Inner::LocalClosed(local_closed) => local_closed.poll(notifier).into(),
Inner::Closing(closing) => closing.poll(notifier).into(),
Inner::Closed => Inner::Closed,
Inner::Killed => Inner::Killed,
};
if let &mut Inner::RemoteClosed(_) = self {
self.close(notifier);
}
}
pub fn add_incoming<'a>(
&'a mut self, notifier: &'a impl Notifier,
) -> Option<impl FnOnce(Connection) + 'a> {
match self {
Inner::Connecting(_) | Inner::ConnectingLocalClosed(_) => {
Some(move |connection| match self {
Inner::Connecting(connecting) => connecting.add_incoming(connection, notifier),
Inner::ConnectingLocalClosed(connecting_local_closed) => {
connecting_local_closed.add_incoming(connection, notifier)
}
_ => unreachable!(),
})
}
_ => None,
}
}
pub fn connecting(&self) -> bool {
match self {
&Inner::Connecting(_) | &Inner::ConnectingLocalClosed(_) => true,
_ => false,
}
}
pub fn recvable(&self) -> bool {
match self {
&Inner::Connected(_) | &Inner::LocalClosed(_) => true,
_ => false,
}
}
pub fn recv_avail<T: serde::de::DeserializeOwned + 'static, E: Notifier>(
&mut self, notifier: &E,
) -> Option<bool> {
if self.recvable() {
Some(match self {
&mut Inner::Connected(ref mut connected) => connected.recv_avail::<T, E>(notifier),
&mut Inner::LocalClosed(ref mut local_closed) => {
local_closed.recv_avail::<T, E>(notifier)
}
_ => unreachable!(),
})
} else {
None
}
}
pub fn recv<T: serde::de::DeserializeOwned + 'static>(
&mut self, notifier: &impl Notifier,
) -> T {
match self {
&mut Inner::Connected(ref mut connected) => connected.recv(notifier),
&mut Inner::LocalClosed(ref mut local_closed) => local_closed.recv(notifier),
_ => panic!(),
}
}
pub fn sendable(&self) -> bool {
match self {
&Inner::Connected(_) | &Inner::RemoteClosed(_) => true,
_ => false,
}
}
pub fn send_avail(&self) -> Option<bool> {
if self.sendable() {
Some(match self {
&Inner::Connected(ref connected) => connected.send_avail(),
&Inner::RemoteClosed(ref remote_closed) => remote_closed.send_avail(),
_ => unreachable!(),
})
} else {
None
}
}
pub fn send<T: serde::ser::Serialize + 'static>(&mut self, x: T, notifier: &impl Notifier) {
match self {
&mut Inner::Connected(ref mut connected) => connected.send(x, notifier),
&mut Inner::RemoteClosed(ref mut remote_closed) => remote_closed.send(x, notifier),
_ => panic!(),
}
}
pub fn closable(&self) -> bool {
match self {
&Inner::Connecting(_) | &Inner::Connected(_) | &Inner::RemoteClosed(_) => true,
_ => false,
}
}
pub fn closed(&self) -> bool {
match self {
&Inner::Closed => true,
_ => false,
}
}
pub fn valid(&self) -> bool {
match self {
&Inner::Connecting(_)
| &Inner::ConnectingLocalClosed(_)
| &Inner::Connected(_)
| &Inner::RemoteClosed(_)
| &Inner::LocalClosed(_)
| &Inner::Closing(_)
| &Inner::Closed => true,
&Inner::Killed => false,
}
}
pub fn close(&mut self, notifier: &impl Notifier) {
*self = match mem::replace(self, Inner::Killed) {
Inner::Connecting(connecting) => connecting.close(notifier).into(),
Inner::Connected(connected) => connected.close(notifier).into(),
Inner::RemoteClosed(remote_closed) => remote_closed.close(notifier).into(),
Inner::ConnectingLocalClosed(_)
| Inner::LocalClosed(_)
| Inner::Closing(_)
| Inner::Closed
| Inner::Killed => panic!(),
};
}
// pub fn drop(self, notifier: &impl Notifier) {
}
impl From<InnerConnecting> for Inner {
#[inline(always)]
fn from(connecter: InnerConnecting) -> Self {
Inner::Connecting(connecter)
}
}
impl From<InnerConnectingPoll> for Inner {
#[inline(always)]
fn from(connecting_poll: InnerConnectingPoll) -> Self {
match connecting_poll {
InnerConnectingPoll::Connecting(connecting) => Inner::Connecting(connecting),
InnerConnectingPoll::Connected(connected) => Inner::Connected(connected),
InnerConnectingPoll::RemoteClosed(remote_closed) => Inner::RemoteClosed(remote_closed),
InnerConnectingPoll::Killed => Inner::Killed,
}
}
}
impl From<InnerConnectingLocalClosed> for Inner {
#[inline(always)]
fn from(connecting_local_closed: InnerConnectingLocalClosed) -> Self {
Inner::ConnectingLocalClosed(connecting_local_closed)
}
}
impl From<InnerConnectingLocalClosedPoll> for Inner {
#[inline(always)]
fn from(connecter_local_closed_poll: InnerConnectingLocalClosedPoll) -> Self {
match connecter_local_closed_poll {
InnerConnectingLocalClosedPoll::ConnectingLocalClosed(connecting_local_closed) => {
Inner::ConnectingLocalClosed(connecting_local_closed)
}
InnerConnectingLocalClosedPoll::LocalClosed(local_closed) => {
Inner::LocalClosed(local_closed)
}
InnerConnectingLocalClosedPoll::Closing(closing) => Inner::Closing(closing),
InnerConnectingLocalClosedPoll::Closed => Inner::Closed,
InnerConnectingLocalClosedPoll::Killed => Inner::Killed,
}
}
}
impl From<InnerConnected> for Inner {
#[inline(always)]
fn from(connected: InnerConnected) -> Self {
Inner::Connected(connected)
}
}
impl From<InnerConnectedPoll> for Inner {
#[inline(always)]
fn from(connected_poll: InnerConnectedPoll) -> Self {
match connected_poll {
InnerConnectedPoll::Connected(connected) => Inner::Connected(connected),
InnerConnectedPoll::RemoteClosed(remote_closed) => Inner::RemoteClosed(remote_closed),
InnerConnectedPoll::Killed => Inner::Killed,
}
}
}
impl From<InnerRemoteClosed> for Inner {
#[inline(always)]
fn from(remote_closed: InnerRemoteClosed) -> Self {
Inner::RemoteClosed(remote_closed)
}
}
impl From<InnerRemoteClosedPoll> for Inner {
#[inline(always)]
fn from(remote_closed_poll: InnerRemoteClosedPoll) -> Self {
match remote_closed_poll {
InnerRemoteClosedPoll::RemoteClosed(remote_closed) => {
Inner::RemoteClosed(remote_closed)
}
InnerRemoteClosedPoll::Killed => Inner::Killed,
}
}
}
impl From<InnerLocalClosed> for Inner {
#[inline(always)]
fn from(local_closed: InnerLocalClosed) -> Self {
Inner::LocalClosed(local_closed)
}
}
impl From<InnerLocalClosedPoll> for Inner {
#[inline(always)]
fn from(local_closed_poll: InnerLocalClosedPoll) -> Self {
match local_closed_poll {
InnerLocalClosedPoll::LocalClosed(local_closed) => Inner::LocalClosed(local_closed),
InnerLocalClosedPoll::Closing(closing) => Inner::Closing(closing),
InnerLocalClosedPoll::Closed => Inner::Closed,
InnerLocalClosedPoll::Killed => Inner::Killed,
}
}
}
impl From<InnerClosing> for Inner {
#[inline(always)]
fn from(closing: InnerClosing) -> Self {
Inner::Closing(closing)
}
}
impl From<InnerClosingPoll> for Inner {
#[inline(always)]
fn from(closing_poll: InnerClosingPoll) -> Self {
match closing_poll {
InnerClosingPoll::Closing(closing) => Inner::Closing(closing),
InnerClosingPoll::Closed => Inner::Closed,
InnerClosingPoll::Killed => Inner::Killed,
}
}
}
|
use proconio::input;
fn main() {
input! {
l: u64
}
let ans = binom_knuth(l-1, std::cmp::min(l-12, 11));
println!("{}", ans)
}
pub fn binom_knuth(n: u64, k: u64) -> u64 {
(0..n + 1)
.rev()
.zip(1..k + 1)
.fold(1, |mut r, (n, d)| { r *= n; r /= d; r })
} |
use legion::*;
use crate::{
app_state::AppState,
hierarchy::Children,
};
#[derive(Clone, Debug)]
pub struct Transform2D {
pub translation: glam::Vec3,
pub rotation: f32,
}
impl Transform2D {
pub fn new(translation: &glam::Vec3, rotation: f32) -> Self {
Self {
translation: translation.clone(),
rotation,
}
}
pub fn build_matrix(&self) -> glam::Mat4 {
glam::Mat4::from_rotation_translation(
glam::Quat::from_rotation_z(self.rotation.to_radians()),
self.translation
)
}
pub fn multiply(&self, transform: &Transform2D) -> Self {
let mut rotation = ((self.rotation + transform.rotation) + 180.0) % 360.0;
if rotation < 0.0 {
rotation += 360.0;
}
rotation -= 180.0;
let x = transform.translation.x * rotation.to_radians().cos() - transform.translation.y * rotation.to_radians().sin();
let y = transform.translation.x * rotation.to_radians().sin() + transform.translation.y * rotation.to_radians().cos();
let translation = self.translation + glam::Vec3::new(x, y, 0.0);
Self { translation, rotation }
}
}
pub struct LocalTransform(pub Transform2D);
pub struct GlobalTransform(pub Transform2D);
pub fn propagate_transforms(world: &mut World, resources: &mut Resources) {
let app_state = resources.get::<AppState>().unwrap();
/*let mut query =
<(&mut GlobalTransform, &LocalTransform, &Children)>::query()
.filter(maybe_changed::<LocalTransform>());
for (global_transform, local_transform, children) in query.iter_mut(world) {
global_transform.0 = local_transform.0.clone();
for child in &children.0 {
propagate_recursive(*child, &global_transform.0, world);
}
}*/
let root_entities = app_state.root_entities.clone();
for entity in &root_entities {
let mut entry = world.entry(*entity).unwrap();
let local_transform = entry.get_component::<LocalTransform>().unwrap().0.clone();
let global_transform = entry.get_component_mut::<GlobalTransform>().unwrap();
global_transform.0 = local_transform.clone();
if let Ok(children) = entry.get_component::<Children>() {
let children = children.0.clone();
for child in children {
propagate_recursive(child, local_transform.clone(), world);
}
}
}
}
fn propagate_recursive(entity: Entity, parent_transform: Transform2D, world: &mut World) {
let mut entry = world.entry(entity).unwrap();
let transform = parent_transform.multiply(&entry.get_component::<LocalTransform>().unwrap().0);
let global_transform = entry.get_component_mut::<GlobalTransform>().unwrap();
global_transform.0 = transform.clone();
if let Ok(children) = entry.get_component::<Children>() {
let children = children.0.clone();
for child in children {
propagate_recursive(child, transform.clone(), world);
}
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::ROMSWMAP {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW0EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW0ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW0EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW0EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW0ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW0ENR::FLASH_ROMSWMAP_SW0EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW0ENR::FLASH_ROMSWMAP_SW0EN_CORE => 1,
FLASH_ROMSWMAP_SW0ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW0ENR {
match value {
0 => FLASH_ROMSWMAP_SW0ENR::FLASH_ROMSWMAP_SW0EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW0ENR::FLASH_ROMSWMAP_SW0EN_CORE,
i => FLASH_ROMSWMAP_SW0ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW0EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw0en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW0ENR::FLASH_ROMSWMAP_SW0EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW0EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw0en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW0ENR::FLASH_ROMSWMAP_SW0EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW0EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW0ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW0EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW0EN_CORE,
}
impl FLASH_ROMSWMAP_SW0ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW0ENW::FLASH_ROMSWMAP_SW0EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW0ENW::FLASH_ROMSWMAP_SW0EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW0ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW0ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW0ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw0en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW0ENW::FLASH_ROMSWMAP_SW0EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw0en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW0ENW::FLASH_ROMSWMAP_SW0EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 0);
self.w.bits |= ((value as u32) & 3) << 0;
self.w
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW1EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW1ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW1EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW1EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW1ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW1ENR::FLASH_ROMSWMAP_SW1EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW1ENR::FLASH_ROMSWMAP_SW1EN_CORE => 1,
FLASH_ROMSWMAP_SW1ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW1ENR {
match value {
0 => FLASH_ROMSWMAP_SW1ENR::FLASH_ROMSWMAP_SW1EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW1ENR::FLASH_ROMSWMAP_SW1EN_CORE,
i => FLASH_ROMSWMAP_SW1ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW1EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw1en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW1ENR::FLASH_ROMSWMAP_SW1EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW1EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw1en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW1ENR::FLASH_ROMSWMAP_SW1EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW1EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW1ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW1EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW1EN_CORE,
}
impl FLASH_ROMSWMAP_SW1ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW1ENW::FLASH_ROMSWMAP_SW1EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW1ENW::FLASH_ROMSWMAP_SW1EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW1ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW1ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW1ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw1en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW1ENW::FLASH_ROMSWMAP_SW1EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw1en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW1ENW::FLASH_ROMSWMAP_SW1EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 2);
self.w.bits |= ((value as u32) & 3) << 2;
self.w
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW2EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW2ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW2EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW2EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW2ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW2ENR::FLASH_ROMSWMAP_SW2EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW2ENR::FLASH_ROMSWMAP_SW2EN_CORE => 1,
FLASH_ROMSWMAP_SW2ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW2ENR {
match value {
0 => FLASH_ROMSWMAP_SW2ENR::FLASH_ROMSWMAP_SW2EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW2ENR::FLASH_ROMSWMAP_SW2EN_CORE,
i => FLASH_ROMSWMAP_SW2ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW2EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw2en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW2ENR::FLASH_ROMSWMAP_SW2EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW2EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw2en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW2ENR::FLASH_ROMSWMAP_SW2EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW2EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW2ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW2EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW2EN_CORE,
}
impl FLASH_ROMSWMAP_SW2ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW2ENW::FLASH_ROMSWMAP_SW2EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW2ENW::FLASH_ROMSWMAP_SW2EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW2ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW2ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW2ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw2en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW2ENW::FLASH_ROMSWMAP_SW2EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw2en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW2ENW::FLASH_ROMSWMAP_SW2EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 4);
self.w.bits |= ((value as u32) & 3) << 4;
self.w
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW3EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW3ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW3EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW3EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW3ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW3ENR::FLASH_ROMSWMAP_SW3EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW3ENR::FLASH_ROMSWMAP_SW3EN_CORE => 1,
FLASH_ROMSWMAP_SW3ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW3ENR {
match value {
0 => FLASH_ROMSWMAP_SW3ENR::FLASH_ROMSWMAP_SW3EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW3ENR::FLASH_ROMSWMAP_SW3EN_CORE,
i => FLASH_ROMSWMAP_SW3ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW3EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw3en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW3ENR::FLASH_ROMSWMAP_SW3EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW3EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw3en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW3ENR::FLASH_ROMSWMAP_SW3EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW3EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW3ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW3EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW3EN_CORE,
}
impl FLASH_ROMSWMAP_SW3ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW3ENW::FLASH_ROMSWMAP_SW3EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW3ENW::FLASH_ROMSWMAP_SW3EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW3ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW3ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW3ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw3en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW3ENW::FLASH_ROMSWMAP_SW3EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw3en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW3ENW::FLASH_ROMSWMAP_SW3EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 6);
self.w.bits |= ((value as u32) & 3) << 6;
self.w
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW4EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW4ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW4EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW4EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW4ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW4ENR::FLASH_ROMSWMAP_SW4EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW4ENR::FLASH_ROMSWMAP_SW4EN_CORE => 1,
FLASH_ROMSWMAP_SW4ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW4ENR {
match value {
0 => FLASH_ROMSWMAP_SW4ENR::FLASH_ROMSWMAP_SW4EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW4ENR::FLASH_ROMSWMAP_SW4EN_CORE,
i => FLASH_ROMSWMAP_SW4ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW4EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw4en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW4ENR::FLASH_ROMSWMAP_SW4EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW4EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw4en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW4ENR::FLASH_ROMSWMAP_SW4EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW4EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW4ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW4EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW4EN_CORE,
}
impl FLASH_ROMSWMAP_SW4ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW4ENW::FLASH_ROMSWMAP_SW4EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW4ENW::FLASH_ROMSWMAP_SW4EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW4ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW4ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW4ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw4en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW4ENW::FLASH_ROMSWMAP_SW4EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw4en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW4ENW::FLASH_ROMSWMAP_SW4EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 8);
self.w.bits |= ((value as u32) & 3) << 8;
self.w
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW5EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW5ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW5EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW5EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW5ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW5ENR::FLASH_ROMSWMAP_SW5EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW5ENR::FLASH_ROMSWMAP_SW5EN_CORE => 1,
FLASH_ROMSWMAP_SW5ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW5ENR {
match value {
0 => FLASH_ROMSWMAP_SW5ENR::FLASH_ROMSWMAP_SW5EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW5ENR::FLASH_ROMSWMAP_SW5EN_CORE,
i => FLASH_ROMSWMAP_SW5ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW5EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw5en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW5ENR::FLASH_ROMSWMAP_SW5EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW5EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw5en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW5ENR::FLASH_ROMSWMAP_SW5EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW5EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW5ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW5EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW5EN_CORE,
}
impl FLASH_ROMSWMAP_SW5ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW5ENW::FLASH_ROMSWMAP_SW5EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW5ENW::FLASH_ROMSWMAP_SW5EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW5ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW5ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW5ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw5en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW5ENW::FLASH_ROMSWMAP_SW5EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw5en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW5ENW::FLASH_ROMSWMAP_SW5EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 10);
self.w.bits |= ((value as u32) & 3) << 10;
self.w
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW6EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW6ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW6EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW6EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW6ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW6ENR::FLASH_ROMSWMAP_SW6EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW6ENR::FLASH_ROMSWMAP_SW6EN_CORE => 1,
FLASH_ROMSWMAP_SW6ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW6ENR {
match value {
0 => FLASH_ROMSWMAP_SW6ENR::FLASH_ROMSWMAP_SW6EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW6ENR::FLASH_ROMSWMAP_SW6EN_CORE,
i => FLASH_ROMSWMAP_SW6ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW6EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw6en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW6ENR::FLASH_ROMSWMAP_SW6EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW6EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw6en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW6ENR::FLASH_ROMSWMAP_SW6EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW6EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW6ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW6EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW6EN_CORE,
}
impl FLASH_ROMSWMAP_SW6ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW6ENW::FLASH_ROMSWMAP_SW6EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW6ENW::FLASH_ROMSWMAP_SW6EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW6ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW6ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW6ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw6en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW6ENW::FLASH_ROMSWMAP_SW6EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw6en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW6ENW::FLASH_ROMSWMAP_SW6EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 12);
self.w.bits |= ((value as u32) & 3) << 12;
self.w
}
}
#[doc = "Possible values of the field `FLASH_ROMSWMAP_SW7EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW7ENR {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW7EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW7EN_CORE,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl FLASH_ROMSWMAP_SW7ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW7ENR::FLASH_ROMSWMAP_SW7EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW7ENR::FLASH_ROMSWMAP_SW7EN_CORE => 1,
FLASH_ROMSWMAP_SW7ENR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> FLASH_ROMSWMAP_SW7ENR {
match value {
0 => FLASH_ROMSWMAP_SW7ENR::FLASH_ROMSWMAP_SW7EN_NOTVIS,
1 => FLASH_ROMSWMAP_SW7ENR::FLASH_ROMSWMAP_SW7EN_CORE,
i => FLASH_ROMSWMAP_SW7ENR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW7EN_NOTVIS`"]
#[inline(always)]
pub fn is_flash_romswmap_sw7en_notvis(&self) -> bool {
*self == FLASH_ROMSWMAP_SW7ENR::FLASH_ROMSWMAP_SW7EN_NOTVIS
}
#[doc = "Checks if the value of the field is `FLASH_ROMSWMAP_SW7EN_CORE`"]
#[inline(always)]
pub fn is_flash_romswmap_sw7en_core(&self) -> bool {
*self == FLASH_ROMSWMAP_SW7ENR::FLASH_ROMSWMAP_SW7EN_CORE
}
}
#[doc = "Values that can be written to the field `FLASH_ROMSWMAP_SW7EN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FLASH_ROMSWMAP_SW7ENW {
#[doc = "Software region not available to the core"]
FLASH_ROMSWMAP_SW7EN_NOTVIS,
#[doc = "Region available to core"]
FLASH_ROMSWMAP_SW7EN_CORE,
}
impl FLASH_ROMSWMAP_SW7ENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
FLASH_ROMSWMAP_SW7ENW::FLASH_ROMSWMAP_SW7EN_NOTVIS => 0,
FLASH_ROMSWMAP_SW7ENW::FLASH_ROMSWMAP_SW7EN_CORE => 1,
}
}
}
#[doc = r"Proxy"]
pub struct _FLASH_ROMSWMAP_SW7ENW<'a> {
w: &'a mut W,
}
impl<'a> _FLASH_ROMSWMAP_SW7ENW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FLASH_ROMSWMAP_SW7ENW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Software region not available to the core"]
#[inline(always)]
pub fn flash_romswmap_sw7en_notvis(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW7ENW::FLASH_ROMSWMAP_SW7EN_NOTVIS)
}
#[doc = "Region available to core"]
#[inline(always)]
pub fn flash_romswmap_sw7en_core(self) -> &'a mut W {
self.variant(FLASH_ROMSWMAP_SW7ENW::FLASH_ROMSWMAP_SW7EN_CORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 14);
self.w.bits |= ((value as u32) & 3) << 14;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - ROM SW Region 0 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw0en(&self) -> FLASH_ROMSWMAP_SW0ENR {
FLASH_ROMSWMAP_SW0ENR::_from(((self.bits >> 0) & 3) as u8)
}
#[doc = "Bits 2:3 - ROM SW Region 1 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw1en(&self) -> FLASH_ROMSWMAP_SW1ENR {
FLASH_ROMSWMAP_SW1ENR::_from(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:5 - ROM SW Region 2 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw2en(&self) -> FLASH_ROMSWMAP_SW2ENR {
FLASH_ROMSWMAP_SW2ENR::_from(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - ROM SW Region 3 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw3en(&self) -> FLASH_ROMSWMAP_SW3ENR {
FLASH_ROMSWMAP_SW3ENR::_from(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bits 8:9 - ROM SW Region 4 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw4en(&self) -> FLASH_ROMSWMAP_SW4ENR {
FLASH_ROMSWMAP_SW4ENR::_from(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 10:11 - ROM SW Region 5 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw5en(&self) -> FLASH_ROMSWMAP_SW5ENR {
FLASH_ROMSWMAP_SW5ENR::_from(((self.bits >> 10) & 3) as u8)
}
#[doc = "Bits 12:13 - ROM SW Region 6 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw6en(&self) -> FLASH_ROMSWMAP_SW6ENR {
FLASH_ROMSWMAP_SW6ENR::_from(((self.bits >> 12) & 3) as u8)
}
#[doc = "Bits 14:15 - ROM SW Region 7 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw7en(&self) -> FLASH_ROMSWMAP_SW7ENR {
FLASH_ROMSWMAP_SW7ENR::_from(((self.bits >> 14) & 3) as u8)
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - ROM SW Region 0 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw0en(&mut self) -> _FLASH_ROMSWMAP_SW0ENW {
_FLASH_ROMSWMAP_SW0ENW { w: self }
}
#[doc = "Bits 2:3 - ROM SW Region 1 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw1en(&mut self) -> _FLASH_ROMSWMAP_SW1ENW {
_FLASH_ROMSWMAP_SW1ENW { w: self }
}
#[doc = "Bits 4:5 - ROM SW Region 2 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw2en(&mut self) -> _FLASH_ROMSWMAP_SW2ENW {
_FLASH_ROMSWMAP_SW2ENW { w: self }
}
#[doc = "Bits 6:7 - ROM SW Region 3 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw3en(&mut self) -> _FLASH_ROMSWMAP_SW3ENW {
_FLASH_ROMSWMAP_SW3ENW { w: self }
}
#[doc = "Bits 8:9 - ROM SW Region 4 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw4en(&mut self) -> _FLASH_ROMSWMAP_SW4ENW {
_FLASH_ROMSWMAP_SW4ENW { w: self }
}
#[doc = "Bits 10:11 - ROM SW Region 5 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw5en(&mut self) -> _FLASH_ROMSWMAP_SW5ENW {
_FLASH_ROMSWMAP_SW5ENW { w: self }
}
#[doc = "Bits 12:13 - ROM SW Region 6 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw6en(&mut self) -> _FLASH_ROMSWMAP_SW6ENW {
_FLASH_ROMSWMAP_SW6ENW { w: self }
}
#[doc = "Bits 14:15 - ROM SW Region 7 Availability"]
#[inline(always)]
pub fn flash_romswmap_sw7en(&mut self) -> _FLASH_ROMSWMAP_SW7ENW {
_FLASH_ROMSWMAP_SW7ENW { w: self }
}
}
|
use crate::{app_env::get_env, datastore::prelude::*};
use googapis::google::datastore::v1;
use v1::{
run_query_request::QueryType, Entity, EntityResult, GqlQuery, QueryResultBatch,
RunQueryRequest, Value,
};
use super::utils::{value_to_gql_param, PathToRef};
pub async fn run_query_id<'a>(
client: &Client,
kind: &'a str,
entity_path: &PathToRef<'a>,
) -> Response<Entity> {
let query_batch = run_query(
client,
format!("SELECT * FROM {} WHERE __key__ = @1", kind),
Default::default(),
&[insert::to_db_key(entity_path)],
)
.await
.or(Err(ResponseError::NotFound(kind.into())))?;
let first_entity = extract_first_entity(&query_batch.entity_results);
match first_entity {
Some(v) => Ok(v),
None => Err(ResponseError::NotFound(format!("{}", kind))),
}
}
pub async fn run_query<'a>(
client: &Client,
query_string: String,
named_bindings: DbProperties,
positional_bindings: &[Value],
) -> Response<QueryResultBatch> {
let mut client = client.clone();
let query = RunQueryRequest {
project_id: get_env::project_id(),
query_type: Some(QueryType::GqlQuery(GqlQuery {
named_bindings: named_bindings
.iter()
.map(|(k, v)| (k.to_string(), value_to_gql_param(v)))
.collect(),
positional_bindings: positional_bindings.iter().map(value_to_gql_param).collect(),
query_string,
allow_literals: true,
})),
..Default::default()
};
let query_batch = client
.run_query(query)
.await
.map_err(|err| {
println!("{:#?}", err.to_string());
ResponseError::UnexpectedError(err.to_string())
})?
.get_ref()
.batch
.clone();
match query_batch {
Some(batch) => Ok(batch),
None => Err(ResponseError::UnexpectedError(
"Batch is not present".into(),
)),
}
}
pub fn extract_first_entity(entities: &Vec<EntityResult>) -> Option<Entity> {
match entities.last() {
Some(entity) if entity.entity.is_some() => entity.entity.to_owned(),
_ => None,
}
}
|
// This pub module only tests that the code inside compiles
#![allow(clippy::derive_partial_eq_without_eq)]
#![allow(dead_code)]
use std::{
cmp::{Eq, Ord, PartialEq, PartialOrd},
error::Error as ErrorTrait,
fmt::{self, Debug, Display, Write as FmtWriteTrait},
io::{
self, BufRead as IoBufReadTrait, Read as IoReadTrait, Seek as IoSeekTrait,
Write as IoWriteTrait,
},
};
use crate::{
sabi_trait,
std_types::RBox,
test_utils::{GetImpls, GetImplsHelper},
type_level::downcasting::{TD_CanDowncast, TD_Opaque},
};
pub mod no_supertraits {
use super::*;
#[sabi_trait]
pub trait Trait {
fn method(&self) {}
}
pub struct Struct;
impl Trait for Struct {}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_ERROR);
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
}
}
pub mod static_supertrait {
use super::*;
#[sabi_trait]
pub trait Trait: 'static {
fn method(&self) {}
}
pub struct Struct<'a>(&'a str);
impl Trait for Struct<'static> {}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_ERROR);
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct(""), TD_CanDowncast);
object.method();
}
// Testing that Trait has 'static as a supertrait,
trait Dummy {
fn dummy<T>()
where
T: Trait;
}
impl Dummy for () {
fn dummy<T>()
where
T: Trait + 'static,
{
}
}
}
pub mod nonstatic_supertrait {
use super::*;
#[sabi_trait]
pub trait Trait<'a>: 'a {
fn method(&self) {}
}
pub struct Struct<'a>(&'a str);
impl<'a, 'b: 'a> Trait<'a> for Struct<'b> {}
impl<'a, T: 'a> Trait<'a> for Option<T> {}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, 'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_ERROR);
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct(""), TD_CanDowncast);
object.method();
}
// Testing that Trait has 'a as a supertrait,
trait Dummy {
fn dummy<'a, T>()
where
T: Trait<'a>;
}
impl Dummy for () {
fn dummy<'a, T>()
where
T: Trait<'a> + 'a,
{
}
}
struct MakeBorrowedCTO<'a, 'b, T>(&'b (), &'a (), T);
impl<'a, 'b, T> MakeBorrowedCTO<'a, 'b, T>
where
T: 'a,
'a: 'b,
{
pub const NONE: Option<&'a T> = None;
pub const CONST: Trait_CTO<'a, 'a, 'b> = Trait_CTO::from_const(&Self::NONE, TD_Opaque);
pub fn get_const(_: &'a T) -> Trait_CTO<'a, 'a, 'b> {
Self::CONST
}
}
// Testing that Trait does not have 'a as a supertrait.
fn assert_trait_inner<'a, T>(_: T)
where
T: Trait<'a>,
{
}
fn assert_trait() {
let mut a = String::new();
a.push('w');
assert_trait_inner(Struct(&a));
{
let a = 0usize;
MakeBorrowedCTO::get_const(&a).method();
}
{
let a = String::new();
MakeBorrowedCTO::get_const(&a).method();
}
}
}
pub mod only_clone {
use super::*;
#[sabi_trait]
pub trait Trait: Clone {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_ERROR);
}
#[derive(Clone)]
pub struct Struct;
impl Trait for Struct {}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
let _ = object.clone();
}
}
pub mod only_display {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: Display {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl Display for Struct {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("What!?", f)
}
}
impl Trait for Struct {}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
format!("{}", object);
}
}
pub mod only_debug {
use super::*;
#[sabi_trait]
pub trait Trait: Debug {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_ERROR);
}
#[derive(Debug)]
pub struct Struct;
impl Trait for Struct {}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
format!("{:?}", object);
}
}
// pub mod only_serialize{
// use super::*;
// #[sabi_trait]
// #[sabi(use_dyntrait)]
// pub trait Trait:Serialize{
// fn method(&self){}
// }
// #[derive(::serde::Serialize)]
// pub struct Struct;
// impl Trait for Struct{}
// impl SerializeType for Struct {
// fn serialize_impl<'a>(&'a self) -> Result<RCow<'a, str>, RBoxError>{
// Ok(RCow::from("Struct"))
// }
// }
// fn assert_bound<T>(_:&T)
// where
// T:serde::Serialize
// {}
// fn test_constructible(){
// let object=Trait_TO::from_value(Struct,TD_CanDowncast);
// object.method();
// assert_bound(&object);
// }
// }
// pub mod only_deserialize_a{
// use super::*;
// use serde::Deserialize;
// #[sabi_trait]
// #[sabi(use_dyntrait)]
// //#[sabi(debug_print_trait)]
// pub trait Trait: for<'a> Deserialize<'a> {
// fn method(&self){}
// }
// impl<'a> DeserializeOwnedInterface<'a> for Trait_Interface{
// type Deserialized=Trait_Backend<'a,RBox<()>>;
// fn deserialize_impl(s: RStr<'_>) -> Result<Self::Deserialized, RBoxError>{
// Ok(DynTrait::from_value(Struct,Trait_Interface::NEW))
// }
// }
// #[derive(Deserialize)]
// pub struct Struct;
// impl Trait for Struct{}
// fn assert_bound<T>(_:&T)
// where
// T:for<'a>Deserialize<'a>
// {}
// fn test_constructible(){
// let object=Trait_TO::from_value(Struct,TD_CanDowncast);
// object.method();
// assert_bound(&object);
// }
// }
pub mod only_partial_eq {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
// #[sabi(debug_print_trait)]
pub trait Trait: PartialEq {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
#[derive(PartialEq)]
pub struct Struct;
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + PartialEq,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_eq {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: Eq {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(GI::IMPLS_EQ);
assert!(GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
#[derive(Eq, PartialEq)]
pub struct Struct;
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + Eq,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_partial_ord {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: PartialOrd {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
#[derive(PartialEq, PartialOrd)]
pub struct Struct;
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + PartialOrd,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_ord {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: Ord {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(GI::IMPLS_EQ);
assert!(GI::IMPLS_PARTIAL_EQ);
assert!(GI::IMPLS_ORD);
assert!(GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
#[derive(PartialEq, PartialOrd, Eq, Ord)]
pub struct Struct;
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + Ord,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_hash {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: Hash {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
#[derive(Hash)]
pub struct Struct;
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + std::hash::Hash,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_iterator_a {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait<'a, T: 'a>: Iterator<Item = &'a T> {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, 'static, RBox<()>, ()>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct<'a, T>(&'a T);
impl<'a, T> Trait<'a, T> for Struct<'a, T> {}
impl<'a, T> Iterator for Struct<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
None
}
}
fn assert_bound<'a, T: 'a>(_: &T)
where
T: Trait<'a, i32> + Iterator<Item = &'a i32>,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct(&0), TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_iterator_b {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait<T: 'static>: Iterator<Item = &'static T> {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>, ()>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl Trait<i32> for Struct {}
impl Iterator for Struct {
type Item = &'static i32;
fn next(&mut self) -> Option<&'static i32> {
None
}
}
fn assert_bound<T>(_: &T)
where
T: Trait<i32> + Iterator<Item = &'static i32>,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_de_iterator {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait<T: 'static>: DoubleEndedIterator<Item = &'static T> {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>, ()>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(GI::IMPLS_ITERATOR);
assert!(GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl Trait<i32> for Struct {}
impl Iterator for Struct {
type Item = &'static i32;
fn next(&mut self) -> Option<&'static i32> {
None
}
}
impl DoubleEndedIterator for Struct {
fn next_back(&mut self) -> Option<&'static i32> {
None
}
}
fn assert_bound<T>(_: &T)
where
T: Trait<i32> + DoubleEndedIterator<Item = &'static i32>,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_error {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: Error {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(GI::IMPLS_DISPLAY);
assert!(GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(GI::IMPLS_ERROR);
}
#[derive(Debug)]
pub struct Struct;
impl Display for Struct {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Ok(())
}
}
impl ErrorTrait for Struct {}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + ErrorTrait,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_fmt_write {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: FmtWrite {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl FmtWriteTrait for Struct {
fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> {
Ok(())
}
}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + FmtWriteTrait,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_io_write {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: IoWrite {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl IoWriteTrait for Struct {
fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + IoWriteTrait,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_io_read {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: IoRead {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl IoReadTrait for Struct {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + IoReadTrait,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_io_bufread {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: IoBufRead {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(!GI::IMPLS_IO_SEEK);
assert!(GI::IMPLS_IO_READ);
assert!(GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl IoReadTrait for Struct {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl IoBufReadTrait for Struct {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
Ok(&[])
}
fn consume(&mut self, _amt: usize) {}
}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + IoBufReadTrait,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
pub mod only_io_seek {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait: IoSeek {
fn method(&self) {}
}
#[test]
fn test_impls() {
type GI = GetImpls<Trait_TO<'static, RBox<()>>>;
assert!(!GI::IMPLS_SEND);
assert!(!GI::IMPLS_SYNC);
assert!(!GI::IMPLS_UNPIN);
assert!(!GI::IMPLS_CLONE);
assert!(!GI::IMPLS_DISPLAY);
assert!(!GI::IMPLS_DEBUG);
assert!(!GI::IMPLS_SERIALIZE);
assert!(!GI::IMPLS_EQ);
assert!(!GI::IMPLS_PARTIAL_EQ);
assert!(!GI::IMPLS_ORD);
assert!(!GI::IMPLS_PARTIAL_ORD);
assert!(!GI::IMPLS_HASH);
assert!(!GI::IMPLS_DESERIALIZE);
assert!(!GI::IMPLS_ITERATOR);
assert!(!GI::IMPLS_DOUBLE_ENDED_ITERATOR);
assert!(!GI::IMPLS_FMT_WRITE);
assert!(!GI::IMPLS_IO_WRITE);
assert!(GI::IMPLS_IO_SEEK);
assert!(!GI::IMPLS_IO_READ);
assert!(!GI::IMPLS_IO_BUF_READ);
assert!(!GI::IMPLS_ERROR);
}
pub struct Struct;
impl IoSeekTrait for Struct {
fn seek(&mut self, _: io::SeekFrom) -> io::Result<u64> {
Ok(0)
}
}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait + IoSeekTrait,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
pub mod every_trait {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait:
Clone
+ Iterator
+ DoubleEndedIterator<Item = &'static ()>
+ Display
+ Debug
+ Error
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ Hash
+ FmtWrite
+ IoWrite
+ IoRead
+ IoBufRead
+ IoSeek
+ Send
+ Sync
+ Unpin
{
fn method(&self) {}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct Struct;
impl Display for Struct {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("What!?", f)
}
}
impl Iterator for Struct {
type Item = &'static ();
fn next(&mut self) -> Option<&'static ()> {
None
}
}
impl DoubleEndedIterator for Struct {
fn next_back(&mut self) -> Option<&'static ()> {
None
}
}
impl ErrorTrait for Struct {}
impl FmtWriteTrait for Struct {
fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> {
Ok(())
}
}
impl IoWriteTrait for Struct {
fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl IoReadTrait for Struct {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl IoBufReadTrait for Struct {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
Ok(&[])
}
fn consume(&mut self, _amt: usize) {}
}
impl IoSeekTrait for Struct {
fn seek(&mut self, _: io::SeekFrom) -> io::Result<u64> {
Ok(0)
}
}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait
+ Clone
+ Iterator
+ DoubleEndedIterator<Item = &'static ()>
+ Display
+ Debug
+ ErrorTrait
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ std::hash::Hash
+ FmtWriteTrait
+ IoWriteTrait
+ IoReadTrait
+ IoBufReadTrait
+ IoSeekTrait
+ Send
+ Sync
+ Unpin,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
pub mod every_trait_static {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait:
'static
+ Clone
+ Iterator
+ DoubleEndedIterator<Item = &'static ()>
+ Display
+ Debug
+ Error
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ Hash
+ FmtWrite
+ IoWrite
+ IoRead
+ IoBufRead
+ IoSeek
{
fn method(&self) {}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct Struct;
impl Display for Struct {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("What!?", f)
}
}
impl Iterator for Struct {
type Item = &'static ();
fn next(&mut self) -> Option<&'static ()> {
None
}
}
impl DoubleEndedIterator for Struct {
fn next_back(&mut self) -> Option<&'static ()> {
None
}
}
impl ErrorTrait for Struct {}
impl FmtWriteTrait for Struct {
fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> {
Ok(())
}
}
impl IoWriteTrait for Struct {
fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl IoReadTrait for Struct {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl IoBufReadTrait for Struct {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
Ok(&[])
}
fn consume(&mut self, _amt: usize) {}
}
impl IoSeekTrait for Struct {
fn seek(&mut self, _: io::SeekFrom) -> io::Result<u64> {
Ok(0)
}
}
impl Trait for Struct {}
fn assert_bound<T>(_: &T)
where
T: Trait
+ Clone
+ Iterator
+ DoubleEndedIterator<Item = &'static ()>
+ Display
+ Debug
+ ErrorTrait
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ std::hash::Hash
+ FmtWriteTrait
+ IoWriteTrait
+ IoReadTrait
+ IoBufReadTrait
+ IoSeekTrait,
{
}
fn test_constructible() {
let object = Trait_TO::from_value(Struct, TD_CanDowncast);
object.method();
assert_bound(&object);
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
pub mod every_trait_nonstatic {
use super::*;
#[sabi_trait]
#[sabi(use_dyntrait)]
pub trait Trait<'a>:
'a+
Clone+
Iterator+DoubleEndedIterator<Item=&'static ()>+
Display+Debug+Error+
//PartialEq+Eq+PartialOrd+Ord+
Hash+
FmtWrite+IoWrite+IoRead+IoBufRead+IoSeek
{
fn method(&self){}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct Struct<'a>(&'a str);
impl Display for Struct<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt("What!?", f)
}
}
impl Iterator for Struct<'_> {
type Item = &'static ();
fn next(&mut self) -> Option<&'static ()> {
None
}
}
impl DoubleEndedIterator for Struct<'_> {
fn next_back(&mut self) -> Option<&'static ()> {
None
}
}
impl ErrorTrait for Struct<'_> {}
impl FmtWriteTrait for Struct<'_> {
fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> {
Ok(())
}
}
impl IoWriteTrait for Struct<'_> {
fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
Ok(0)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl IoReadTrait for Struct<'_> {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Ok(0)
}
}
impl IoBufReadTrait for Struct<'_> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
Ok(&[])
}
fn consume(&mut self, _amt: usize) {}
}
impl IoSeekTrait for Struct<'_> {
fn seek(&mut self, _: io::SeekFrom) -> io::Result<u64> {
Ok(0)
}
}
impl<'a> Trait<'a> for Struct<'a> {}
fn assert_bound<'a, T>(_: &T)
where
T: Trait<'a>,
{
}
fn test_constructible() {
let string = String::new();
let value = Struct(&string);
let object = Trait_TO::from_ptr(RBox::new(value), TD_Opaque);
object.method();
assert_bound(&object);
{
let value = Struct(&string);
constructs_const_a(&value);
let value = Struct("");
constructs_const_a(&value);
}
}
const CONST_A: Trait_CTO<'static, 'static, 'static> =
Trait_CTO::from_const(&Struct(""), TD_Opaque);
fn constructs_const_a<'a, 'b, 'borr, T>(ref_: &'b T) -> Trait_CTO<'a, 'borr, 'b>
where
T: 'borr + 'a + Trait<'a>,
{
Trait_CTO::from_const(ref_, TD_Opaque)
}
}
|
use super::dyn_sized::{self, DynSized};
use std::marker::Unsize;
use std::mem;
use std::ops::{Deref, DerefMut};
/// The storage format for thin pointers. Stores the metadata and the value together.
#[derive(Debug)]
#[repr(C)]
pub struct ThinBackend<D, T> where
D: DynSized + ?Sized,
T: ?Sized
{
pub meta: D::Meta,
pub value: T
}
unsafe impl<D> DynSized for ThinBackend<D, D> where
D: DynSized + ?Sized
{
type Meta = D::Meta;
fn assemble(meta: D::Meta, data: *const ()) -> *const Self {
let d_ptr: *const D = D::assemble(meta, data);
unsafe {
mem::transmute(d_ptr)
}
}
fn disassemble(ptr: *const Self) -> (D::Meta, *const ()) {
let d_ptr: *const D = unsafe {
mem::transmute(ptr)
};
D::disassemble(d_ptr)
}
}
impl<D, S> ThinBackend<D, S> where
D: DynSized + ?Sized,
S: Unsize<D>
{
pub fn new(value: S) -> ThinBackend<D, S> {
ThinBackend {
meta: (&value as &D).meta(),
value: value
}
}
}
impl<D, S> ThinBackend<D, S> where
D: DynSized + ?Sized
{
pub fn into_value(self) -> S {
self.value
}
}
impl<D> ThinBackend<D, D> where
D: DynSized + ?Sized
{
pub unsafe fn fat_from_thin(data: *const ()) -> *const ThinBackend<D, D> {
let ptr = data as *const ThinBackend<D, ()>;
let meta = (*ptr).meta;
ThinBackend::assemble(meta, data)
}
pub unsafe fn fat_from_thin_mut(data: *mut ()) -> *mut ThinBackend<D, D> {
let ptr = data as *mut ThinBackend<D, ()>;
let meta = (*ptr).meta;
ThinBackend::assemble_mut(meta, data)
}
pub fn size_of_backend(src: &D) -> usize {
dyn_sized::size_of_val::<ThinBackend<D, D>>(src.meta())
}
pub fn align_of_backend(src: &D) -> usize {
dyn_sized::align_of_val::<ThinBackend<D,D>>(src.meta())
}
}
impl<D, T> Deref for ThinBackend<D, T> where
D: DynSized + ?Sized,
T: ?Sized
{
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<D, T> DerefMut for ThinBackend<D, T> where
D: DynSized + ?Sized,
T: ?Sized
{
fn deref_mut(&mut self) -> &mut T {
&mut self.value
}
}
|
use std::string::String;
pub struct Node {
// TODO: Use string is just for convenient. Replace it for saving the 24 byte as much as possible.
// Maybe just a position of Lineno to the main text,
// Since a size fixed "string" cannot be adjusted according to the input length.
pub text: String
}
|
// For macro spans
#![feature(proc_macro_span)]
extern crate proc_macro;
use proc_macro::{TokenStream, TokenTree};
#[proc_macro]
pub fn python(input: TokenStream) -> TokenStream {
print(input);
todo!()
}
fn print(input: TokenStream) {
for t in input {
if let TokenTree::Group(g) = t {
println!("{:?}: open {:?}", g.span_open().start(), g.delimiter());
print(g.stream());
println!("{:?}: close {:?}", g.span_close().start(), g.delimiter());
} else {
println!("{:?}: {}", t.span().start(), t.to_string());
}
}
}
|
//= {
//= "output": {
//= "1": [
//= "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"\\#\\$%\\&'\\(\\)\\*\\+,\\-\\./0123456789:;<=>\\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\\\\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\~\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff",
//= true
//= ],
//= "2": [
//= "",
//= true
//= ]
//= },
//= "children": [],
//= "exit": "Success"
//= }
#![deny(warnings, deprecated)]
extern crate constellation;
use constellation::*;
use std::io::{self, Write};
fn main() {
init(Resources {
mem: 20 * 1024 * 1024,
..Resources::default()
});
io::stdout()
.write_all(&(0u8..=255).collect::<Vec<_>>())
.unwrap()
}
|
#[macro_use]
extern crate diesel;
table! {
users {
id -> Integer,
}
}
#[derive(Insertable)]
#[table_name = "self::users"]
struct UserOk {
id: i32,
}
#[derive(Insertable)]
#[table_name(self::users)]
struct UserWarn {
id: i32,
}
#[derive(Insertable)]
#[table_name]
struct UserError1 {
id: i32,
}
#[derive(Insertable)]
#[table_name = true]
struct UserError2 {
id: i32,
}
#[derive(Insertable)]
#[table_name = ""]
struct UserError3 {
id: i32,
}
#[derive(Insertable)]
#[table_name = "not a path"]
struct UserError4 {
id: i32,
}
#[derive(Insertable)]
#[table_name = "does::not::exist"]
struct UserError5 {
id: i32,
}
fn main() {}
|
//! Method has type parameters.
use near_bindgen::near_bindgen;
use borsh::{BorshDeserialize, BorshSerialize};
#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
struct Incrementer {
value: u32,
}
#[near_bindgen]
impl Incrementer {
pub fn method<'a, T: 'a + std::fmt::Display>(&self) {
unimplemented!()
}
}
fn main() {}
|
use binary_search::BinarySearch;
use procon_reader::ProconReader;
use std::collections::HashMap;
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let points: Vec<(u32, u32)> = (0..n)
.map(|_| {
let x: u32 = rd.get();
let y: u32 = rd.get();
(x, y)
})
.collect();
let mut xs: Vec<u32> = points.iter().map(|&(x, _)| x).collect();
xs.sort();
xs.dedup();
let mut ys = vec![vec![]; n];
for &(x, y) in &points {
let i = xs.lower_bound(&x);
ys[i].push(y);
}
for x in 0..n {
ys[x].sort();
}
let mut ans = 0;
let mut freq: HashMap<(u32, u32), u64> = HashMap::new();
for x in 0..n {
let mut y_pairs = Vec::new();
for i in 0..ys[x].len() {
for j in (i + 1)..ys[x].len() {
y_pairs.push((ys[x][i], ys[x][j]));
}
}
for yy in &y_pairs {
if let Some(f) = freq.get(yy) {
ans += f;
}
}
for yy in y_pairs {
freq.entry(yy).and_modify(|f| *f += 1).or_insert(1);
}
}
println!("{}", ans);
}
|
#![allow(dead_code)]
use core::mem::transmute;
pub struct Message<'a> {
pub msg_type: MsgType,
pub operation: u8,
pub data: &'a [u8],
}
#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum MsgType {
Reserved = 0,
Error = 1,
System = 2,
Ack = 3,
Reboot = 4,
Macro = 5,
Ble = 6,
Keyboard = 7,
Keyup = 8,
Led = 9,
FwInfo = 10,
FwUp = 11,
CustomLed = 12,
CustomKey = 13,
}
impl From<u8> for MsgType {
#[inline]
fn from(b: u8) -> Self {
unsafe { transmute(b) }
}
}
#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum BleOp {
Reserved = 0,
On = 1,
Off = 2,
SaveHost = 3,
ConnectHost = 4,
DeleteHost = 5,
HostListQuery = 6,
Broadcast = 7,
Battery = 8,
AckOk = 9,
AckFail = 10,
CurrentHostQuery = 11,
LegacyMode = 12,
Pair = 13,
Disconnect = 14,
AckReserved = 128,
AckOn = 129,
AckOff = 130,
AckSaveHost = 131,
AckConnectHost = 132,
AckDeleteHost = 133,
AckHostListQuery = 134,
AckBroadcast = 135,
AckBattery = 136,
AckAckOk = 137,
AckAckFaiL = 138,
AckCurrentHostQuery = 139,
AckLegacyMode = 140,
AckWakeup = 170,
}
impl From<u8> for BleOp {
#[inline]
fn from(b: u8) -> Self {
unsafe { transmute(b) }
}
}
#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum KeyboardOp {
Reserved = 0,
KeyReport = 1,
DownloadUserLayout = 2,
SetLayoutId = 3,
GetLayoutId = 4,
UpUserLayout = 5,
AckReserved = 128,
AckKeyReport = 129,
AckDownloadUserLayout = 130,
AckSetLayoutId = 131,
AckGetLayoutId = 132,
AckUpUserLayout = 133,
}
impl From<u8> for KeyboardOp {
#[inline]
fn from(b: u8) -> Self {
unsafe { transmute(b) }
}
}
#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum LedOp {
Reserved = 0,
ThemeMode = 1,
ThemeSwitch = 2,
UserStaticTheme = 3,
BleConfig = 4,
ConfigCmd = 5,
Music = 6,
Key = 7,
GetUsedThemeId = 8,
GetUserStaticTheme = 9,
GetUserStaticCrcId = 10,
SetIndividualKeys = 11,
GetThemeId = 0xc,
AckReserved = 128,
AckThemeMode = 129,
AckThemeSwitch = 130,
AckUserStaticTheme = 131,
AckBleConfig = 132,
AckConfigCmd = 133,
AckMusic = 134,
AckKey = 135,
AckGetUsedThemeId = 136,
AckGetUserStaticTheme = 137,
AckGetUserStaticCrcId = 138,
AckSetIndividualKeys = 139,
}
impl From<u8> for LedOp {
#[inline]
fn from(b: u8) -> Self {
unsafe { transmute(b) }
}
}
#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum SystemOp {
Reserved = 0,
GetId = 1,
IsSyncCode = 8,
SetSyncCode = 9,
AckReserved = 128,
AckGetId = 129,
AckIsSyncCode = 136,
AckSetSyncCode = 137,
}
impl From<u8> for SystemOp {
#[inline]
fn from(b: u8) -> Self {
unsafe { transmute(b) }
}
}
#[repr(u8)]
#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum MacroOp {
Reserved = 0,
SyncMacro = 5,
AckReserved = 128,
AckSyncMacro = 133,
}
impl From<u8> for MacroOp {
#[inline]
fn from(b: u8) -> Self {
unsafe { transmute(b) }
}
}
|
fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {
(v1, v2, 42)
}
fn main() {
let v1 = vec![1, 2, 3];
let v2 = vec![1, 3, 3];
let (v1, v2, answer) = foo(v1, v2);
println!("{:?}, {:?}, {}", v1, v2, answer);
}
|
fn main() {
let d = Data { name: "data1".to_string(), value: 10 };
let mut d2 = Data { name: "data2".to_string(), value: 5};
println!("{:?}", d);
println!("{:?}", d2);
d2.name.push_str("-up");
d2.value += 3;
println!("{:?}", d2);
}
#[derive(Debug)]
struct Data {
name: String,
value: i32
}
|
//! All the traits exposed to be used in other custom pallets
use crate::*;
use codec::{Decode, Encode};
use frame_support::{dispatch, ensure};
use scale_info::TypeInfo;
/// Mixer trait definition to be used in other pallets
pub trait MixerInterface<T: Config<I>, I: 'static = ()> {
// Creates a new mixer
fn create(
creator: T::AccountId,
deposit_size: BalanceOf<T, I>,
depth: u8,
) -> Result<T::TreeId, dispatch::DispatchError>;
/// Deposit into the mixer
fn deposit(account: T::AccountId, id: T::TreeId, leaf: T::Element) -> Result<(), dispatch::DispatchError>;
/// Withdraw from the mixer
fn withdraw(
id: T::TreeId,
proof_bytes: &[u8],
root: T::Element,
nullifier_hash: T::Element,
recipient: T::AccountId,
relayer: T::AccountId,
fee: BalanceOf<T, I>,
refund: BalanceOf<T, I>,
) -> Result<(), dispatch::DispatchError>;
// Stores nullifier hash from a spend tx
fn add_nullifier_hash(id: T::TreeId, nullifier_hash: T::Element) -> Result<(), dispatch::DispatchError>;
}
/// Mixer trait for inspecting mixer state
pub trait MixerInspector<T: Config<I>, I: 'static = ()> {
/// Gets the merkle root for a tree or returns `TreeDoesntExist`
fn get_root(id: T::TreeId) -> Result<T::Element, dispatch::DispatchError>;
/// Checks if a merkle root is in a tree's cached history or returns
/// `TreeDoesntExist
fn is_known_root(id: T::TreeId, target: T::Element) -> Result<bool, dispatch::DispatchError>;
fn ensure_known_root(id: T::TreeId, target: T::Element) -> Result<(), dispatch::DispatchError> {
let is_known: bool = Self::is_known_root(id, target)?;
ensure!(is_known, Error::<T, I>::InvalidWithdrawRoot);
Ok(())
}
/// Check if a nullifier has been used in a tree or returns
/// `InvalidNullifier`
fn is_nullifier_used(id: T::TreeId, nullifier: T::Element) -> bool;
fn ensure_nullifier_unused(id: T::TreeId, nullifier: T::Element) -> Result<(), dispatch::DispatchError> {
ensure!(
Self::is_nullifier_used(id, nullifier),
Error::<T, I>::AlreadyRevealedNullifier
);
Ok(())
}
}
#[derive(Default, Clone, Encode, Decode, TypeInfo)]
pub struct MixerMetadata<AccountId, Balance> {
/// Creator account
pub creator: AccountId,
/// Balance size of deposit
pub deposit_size: Balance,
}
|
use arci::{Error, JointTrajectoryClient, TrajectoryPoint};
use async_trait::async_trait;
use k::nalgebra as na;
use k::Isometry3;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
type ArcJointTrajectoryClient = Arc<dyn JointTrajectoryClient>;
pub fn isometry(x: f64, y: f64, z: f64, roll: f64, pitch: f64, yaw: f64) -> k::Isometry3<f64> {
k::Isometry3::from_parts(
k::Translation3::new(x, y, z),
k::UnitQuaternion::from_euler_angles(roll, pitch, yaw),
)
}
pub struct IkSolverParameters {
pub allowable_position_error: f64, // unit: m
pub allowable_angle_error: f64, // unit: rad
pub jacobian_multiplier: f64,
pub num_max_try: usize,
}
pub fn create_jacobian_ik_solver(parameters: &IkSolverParameters) -> k::JacobianIKSolver<f64> {
k::JacobianIKSolver::new(
parameters.allowable_position_error,
parameters.allowable_angle_error,
parameters.jacobian_multiplier,
parameters.num_max_try,
)
}
pub fn create_random_jacobian_ik_solver(
parameters: &IkSolverParameters,
) -> openrr_planner::RandomInitializeIKSolver<f64, k::JacobianIKSolver<f64>> {
openrr_planner::RandomInitializeIKSolver::new(
create_jacobian_ik_solver(parameters),
parameters.num_max_try,
)
}
pub struct IkSolverWithChain {
ik_arm: k::SerialChain<f64>,
ik_solver: Arc<dyn k::InverseKinematicsSolver<f64> + Send + Sync>,
}
impl IkSolverWithChain {
pub fn end_transform(&self) -> k::Isometry3<f64> {
self.ik_arm.end_transform()
}
pub fn joint_positions(&self) -> Vec<f64> {
self.ik_arm.joint_positions()
}
pub fn solve_with_constraints(
&self,
target_pose: &k::Isometry3<f64>,
constraints: &k::Constraints,
) -> Result<(), Error> {
self.ik_solver
.solve_with_constraints(&self.ik_arm, &target_pose, constraints)
.map_err(|e| Error::Other(e.into()))
}
pub fn set_joint_positions_clamped(&self, positions: &[f64]) {
self.ik_arm.set_joint_positions_clamped(positions)
}
pub fn new(
arm: k::SerialChain<f64>,
ik_solver: Arc<dyn k::InverseKinematicsSolver<f64> + Send + Sync>,
) -> Self {
Self {
ik_arm: arm,
ik_solver,
}
}
}
pub struct IkClient<T>
where
T: JointTrajectoryClient,
{
pub client: T,
pub ik_solver_with_chain: IkSolverWithChain,
pub chain: k::Chain<f64>,
pub constraints: k::Constraints,
}
impl<T> IkClient<T>
where
T: JointTrajectoryClient + Send,
{
pub fn new(client: T, ik_solver_with_chain: IkSolverWithChain, chain: k::Chain<f64>) -> Self {
Self {
client,
ik_solver_with_chain,
chain,
constraints: k::Constraints::default(),
}
}
pub fn current_end_transform(&self) -> Result<k::Isometry3<f64>, Error> {
let current_joint_angles = self.client.current_joint_positions()?;
self.chain
.set_joint_positions_clamped(¤t_joint_angles);
Ok(self.ik_solver_with_chain.end_transform())
}
pub async fn move_ik_with_constraints(
&self,
target_pose: &k::Isometry3<f64>,
constraints: &k::Constraints,
duration_sec: f64,
) -> Result<(), Error> {
self.ik_solver_with_chain
.solve_with_constraints(&target_pose, constraints)?;
let positions = self.ik_solver_with_chain.joint_positions();
let duration = std::time::Duration::from_secs_f64(duration_sec);
self.client.send_joint_positions(positions, duration).await
}
pub async fn move_ik_with_interpolation_and_constraints(
&self,
target_pose: &k::Isometry3<f64>,
constraints: &k::Constraints,
duration_sec: f64,
) -> Result<(), Error> {
let mut traj = check_ik_with_interpolation_and_constraints(
&self.current_end_transform()?,
target_pose,
&self.ik_solver_with_chain,
constraints,
duration_sec,
0.05,
10,
)?;
let dof = self.client.joint_names().len();
traj.first_mut().unwrap().velocities = Some(vec![0.0; dof]);
traj.last_mut().unwrap().velocities = Some(vec![0.0; dof]);
self.client.send_joint_trajectory(traj).await
}
pub async fn move_ik(
&self,
target_pose: &k::Isometry3<f64>,
duration_sec: f64,
) -> Result<(), Error> {
self.move_ik_with_constraints(target_pose, &self.constraints, duration_sec)
.await
}
pub async fn move_ik_with_interpolation(
&self,
target_pose: &k::Isometry3<f64>,
duration_sec: f64,
) -> Result<(), Error> {
self.move_ik_with_interpolation_and_constraints(
target_pose,
&self.constraints,
duration_sec,
)
.await
}
/// Get relative pose from current pose of the IK target
pub fn transform(&self, relative_pose: &k::Isometry3<f64>) -> Result<k::Isometry3<f64>, Error> {
let current_joint_angles = self.client.current_joint_positions()?;
self.chain
.set_joint_positions_clamped(¤t_joint_angles);
let current_target_pose = self.ik_solver_with_chain.end_transform();
Ok(current_target_pose * relative_pose)
}
// Reset the kinematic model for IK calculation like Jacobian method
pub fn set_zero_pose_for_kinematics(&self) -> Result<(), Error> {
let zero_angles = vec![0.0; self.chain.dof()];
self.chain
.set_joint_positions(&zero_angles)
.map_err(|e| Error::Other(e.into()))?;
Ok(())
}
}
#[async_trait]
impl<T> JointTrajectoryClient for IkClient<T>
where
T: JointTrajectoryClient,
{
fn joint_names(&self) -> &[String] {
self.client.joint_names()
}
fn current_joint_positions(&self) -> Result<Vec<f64>, Error> {
self.client.current_joint_positions()
}
async fn send_joint_positions(
&self,
positions: Vec<f64>,
duration: std::time::Duration,
) -> Result<(), Error> {
self.client.send_joint_positions(positions, duration).await
}
async fn send_joint_trajectory(&self, trajectory: Vec<TrajectoryPoint>) -> Result<(), Error> {
self.client.send_joint_trajectory(trajectory).await
}
}
pub fn check_ik_with_interpolation_and_constraints(
current_pose: &Isometry3<f64>,
target_pose: &Isometry3<f64>,
ik_solver_with_chain: &IkSolverWithChain,
constraints: &k::Constraints,
duration_sec: f64,
max_resolution: f64,
min_number_of_points: i32,
) -> Result<Vec<TrajectoryPoint>, Error> {
let target_position = target_pose.translation.vector;
let target_rotation = target_pose.rotation;
let current_position = current_pose.translation.vector;
let current_rotation = current_pose.rotation;
let position_diff = target_position - current_position;
let n = std::cmp::max(
min_number_of_points,
(position_diff.norm() / max_resolution) as i32,
);
let mut traj = vec![];
for i in 1..n + 1 {
let t = i as f64 / n as f64;
let tar_pos = current_position.lerp(&target_position, t);
let tar_rot = current_rotation.slerp(&target_rotation, t);
ik_solver_with_chain.solve_with_constraints(
&k::Isometry3::from_parts(na::Translation3::from(tar_pos), tar_rot),
constraints,
)?;
let trajectory = TrajectoryPoint::new(
ik_solver_with_chain.joint_positions(),
std::time::Duration::from_secs_f64(t * duration_sec),
);
traj.push(trajectory);
}
Ok(traj)
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct IkSolverConfig {
pub root_node_name: Option<String>,
pub ik_target: String,
pub use_random_ik: bool,
pub allowable_position_error_m: f64,
pub allowable_angle_error_rad: f64,
pub jacobian_multiplier: f64,
pub num_max_try: usize,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct IkClientConfig {
pub name: String,
pub client_name: String,
pub ik_solver_config: IkSolverConfig,
pub constraints: k::Constraints,
}
pub fn create_ik_solver_with_chain(
full_chain: &k::Chain<f64>,
config: &IkSolverConfig,
) -> IkSolverWithChain {
let chain = if let Some(root_node_name) = &config.root_node_name {
k::SerialChain::from_end_to_root(
full_chain.find(&config.ik_target).unwrap(),
full_chain.find(root_node_name).unwrap(),
)
} else {
k::SerialChain::from_end(full_chain.find(&config.ik_target).unwrap())
};
let parameters = IkSolverParameters {
allowable_position_error: config.allowable_position_error_m,
allowable_angle_error: config.allowable_angle_error_rad,
jacobian_multiplier: config.jacobian_multiplier,
num_max_try: config.num_max_try,
};
IkSolverWithChain::new(
chain,
if config.use_random_ik {
Arc::new(create_random_jacobian_ik_solver(¶meters))
} else {
Arc::new(create_jacobian_ik_solver(¶meters))
},
)
}
pub fn create_ik_client(
client: ArcJointTrajectoryClient,
full_chain: &k::Chain<f64>,
config: &IkSolverConfig,
constraints: k::Constraints,
) -> IkClient<ArcJointTrajectoryClient> {
let arm_chain = if let Some(root_node_name) = &config.root_node_name {
k::Chain::from_end_to_root(
full_chain.find(&config.ik_target).unwrap(),
full_chain.find(root_node_name).unwrap(),
)
} else {
k::Chain::from_end(full_chain.find(&config.ik_target).unwrap())
};
let arm_ik_solver_with_chain = create_ik_solver_with_chain(&full_chain, &config);
if arm_ik_solver_with_chain.ik_arm.dof() != client.joint_names().len() {
panic!(
"Invalid configuration : ik arm dof {} {:?} != joint_names length {} ({:?})",
arm_ik_solver_with_chain.ik_arm.dof(),
arm_ik_solver_with_chain
.ik_arm
.iter_joints()
.map(|j| j.name.to_owned())
.collect::<Vec<_>>(),
client.joint_names().len(),
client.joint_names()
);
}
let mut ik_client = IkClient::new(client, arm_ik_solver_with_chain, arm_chain);
ik_client.constraints = constraints;
ik_client
}
pub fn create_ik_clients(
configs: &[IkClientConfig],
name_to_joint_trajectory_client: &HashMap<String, ArcJointTrajectoryClient>,
full_chain: &k::Chain<f64>,
) -> HashMap<String, Arc<Mutex<IkClient<ArcJointTrajectoryClient>>>> {
let mut clients = HashMap::new();
for config in configs {
clients.insert(
config.name.clone(),
Arc::new(Mutex::new(create_ik_client(
name_to_joint_trajectory_client[&config.client_name].clone(),
full_chain,
&config.ik_solver_config,
config.constraints,
))),
);
}
clients
}
|
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
fn slope(lines: &mut std::str::Lines,
lines_len: usize,
right: usize,
down: usize) -> i64 {
let mut trees = 0;
let mut line_num : usize = 0;
for line in lines {
line_num += 1;
if line_num % down != 0 {
continue;
}
let access : usize = (line_num/down * right) % lines_len;
//println!("check {}[{}]: {}", line_num, access, line);
let c : char = match line
.chars()
.clone()
.nth(access) {
Some(inner) => inner,
None => break,
};
if c == '#' {
trees += 1;
}
}
trees
}
fn main() {
let file = File::open("input").expect("Failed to read file input");
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)
.expect("Failed to bufferize file input");
let mut lines = contents.lines();
let lines_len : usize = lines.next().unwrap().len();
println!("lines length: {}", lines_len);
//println!("R1D1: {}", slope(&mut lines.clone(), lines_len, 1, 1));
//println!("R3D1: {}", slope(&mut lines.clone(), lines_len, 3, 1));
//println!("R5D1: {}", slope(&mut lines.clone(), lines_len, 5, 1));
//println!("R7D1: {}", slope(&mut lines.clone(), lines_len, 7, 1));
//println!("R1D2: {}", slope(&mut lines.clone(), lines_len, 1, 2));
let trees : i64 = slope(&mut lines.clone(), lines_len, 1, 1)
* slope(&mut lines.clone(), lines_len, 3, 1)
* slope(&mut lines.clone(), lines_len, 5, 1)
* slope(&mut lines.clone(), lines_len, 7, 1)
* slope(&mut lines.clone(), lines_len, 1, 2);
println!("trees: {}", trees);
}
|
pub use self::base::*;
pub use self::bitwise::Bitwise;
pub use self::iterable::*;
pub use self::string::*;
pub mod base;
pub mod string;
pub mod bitwise;
pub mod iterable;
|
use super::data::*;
use super::network::*;
use chrono::{DateTime, Utc};
use std::collections::HashMap;
/*
* Node to node private cluster communication
* */
pub trait ClusterCommunicator {
/*
* Cluster management
* */
fn send_message(&self, target: &str, msg: &Message) -> bool;
fn handle_message(&mut self, msg: &Message);
fn get_nghbr_sample(&self, a: &HashMap<String, DateTime<Utc>>) -> Vec<String>;
fn comm_recv_gossip(&mut self, payload: &Vec<String>);
// fn comm_recv_heartbeat(&mut self); // Currently handled in Node.run() by 'responder.send("ACK", 0).unwrap();'
fn update_neighbors(&mut self);
fn delinquent_node_check(&mut self);
}
/* not sure if I like these could be part of the same trait*/
pub trait ClusterCommunicationReceiver {
fn heartbeat_response(peer: &str);
fn sync_response(info: MachineInfo);
}
/*
* Node to node private deployment communication00
* */
pub trait DeploymentCommunicator {
/*
* Deployment management
* */
fn request_run_deployment(deployment: Deployment);
}
/* not sure if I like these */
pub trait DeploymentCommunicationReceiver {}
|
use std::io;
use std::sync::Arc;
use futures::future::{err, Future};
use futures::stream::Stream;
use hyper::client::HttpConnector;
use hyper::{Client, Request, Method, Uri};
use native_tls::TlsConnector;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_service::Service;
use tokio_tls::{TlsConnectorExt, TlsStream};
use serde_json;
use serde_json::Value;
command!(derpi(_ctx, msg) {
let mut core = Core::new().unwrap();
let tls_cx = TlsConnector::builder().unwrap().build().unwrap();
let mut connector = HttpsConnector {
tls: Arc::new(tls_cx),
http: HttpConnector::new(2, &core.handle()),
};
let client = Client::configure()
.connector(connector)
.build(&core.handle());
let uri = "https://derpibooru.org/images.json".parse().unwrap();
let req = Request::new(Method::Get, uri);
let response = core.run(client.request(req)).unwrap();
println!("{} {}", response.version(), response.status());
for header in response.headers().iter() {
print!("{}", header);
}
let body = core.run(response.body().concat2()).unwrap();
println!("{}", String::from_utf8_lossy(&body));
//response.body().concat2().and_then(move |body| {
// let v: Value = serde_json::from_slice(&body).map_err(|e| {
// io::Error::new(
// io::ErrorKind::Other,
// e
// )
// }).unwrap();
// println!("image: {}", v["images"]);
// Ok(())
//});
});
struct HttpsConnector {
tls: Arc<TlsConnector>,
http: HttpConnector,
}
impl Service for HttpsConnector {
type Request = Uri;
type Response = TlsStream<TcpStream>;
type Error = io::Error;
type Future = Box<Future<Item = Self::Response, Error = io::Error>>;
fn call(&self, uri: Uri) -> Self::Future {
// Right now this is intended to showcase `https`, but you could
// also adapt this to return something like `MaybeTls<T>` where
// some clients resolve to TLS streams (https) and others resolve
// to normal TCP streams (http)
if uri.scheme() != Some("https") {
return err(io::Error::new(io::ErrorKind::Other,
"only works with https")).boxed()
}
// Look up the host that we're connecting to as we're going to validate
// this as part of the TLS handshake.
let host = match uri.host() {
Some(s) => s.to_string(),
None => {
return err(io::Error::new(io::ErrorKind::Other,
"missing host")).boxed()
}
};
// Delegate to the standard `HttpConnector` type to create a connected
// TCP socket. Once we've got that socket initiate the TLS handshake
// with the host name that's provided in the URI we extracted above.
let tls_cx = self.tls.clone();
Box::new(self.http.call(uri).and_then(move |tcp| {
tls_cx.connect_async(&host, tcp)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
}))
}
} |
use num::bigint::BigUint;
use num::traits::ToPrimitive;
use num::one;
use num::zero;
pub struct Fib {
prev2: [BigUint; 2],
}
impl Fib {
pub fn new() -> Fib {
Fib { prev2: [zero(), zero()] }
}
}
impl Iterator for Fib {
type Item = BigUint;
fn next(&mut self) -> Option<BigUint> {
if self.prev2[1] == zero() {
self.prev2[1] = one();
} else {
let new_fib = self.prev2[0].clone() + self.prev2[1].clone();
self.prev2[1] = self.prev2[0].clone();
self.prev2[0] = new_fib;
}
Some(self.prev2[0].clone())
}
}
pub fn fib(n: u64) -> Vec<BigUint> {
Fib::new().take(n.to_usize().unwrap()).collect::<Vec<BigUint>>()
}
|
mod code;
mod code_extern;
mod code_node;
mod context;
mod exec;
mod graph;
mod value;
mod variable;
use std::collections::BTreeMap;
use self::graph::Graphs;
pub use self::context::{CompactContext, DecompactContext};
pub use self::exec::Program;
pub trait Compact {
type Output;
fn compact(&self, ctx: &mut CompactContext) -> Self::Output;
}
pub trait ArrangeId {
fn arrange_id(&mut self, ids: &Graphs<u64>);
}
pub trait Decompact {
type Args;
type Output;
fn decompact(self, ctx: &mut DecompactContext, args: Self::Args) -> Self::Output;
}
impl<K, V> Compact for BTreeMap<K, V>
where
K: Clone + Ord,
V: Compact,
{
type Output = BTreeMap<K, V::Output>;
fn compact(&self, ctx: &mut CompactContext) -> Self::Output {
self.iter()
.map(|(k, v)| (k.clone(), v.compact(ctx)))
.collect()
}
}
impl<K, V> ArrangeId for BTreeMap<K, V>
where
K: Clone + Ord,
V: ArrangeId,
{
fn arrange_id(&mut self, ids: &Graphs<u64>) {
self.values_mut().for_each(|x| x.arrange_id(ids))
}
}
impl<K, V> Decompact for BTreeMap<K, V>
where
K: Ord,
V: Decompact<Args = ()>,
{
type Args = V::Args;
type Output = BTreeMap<K, V::Output>;
fn decompact(self, ctx: &mut DecompactContext, (): Self::Args) -> Self::Output {
self.into_iter()
.map(|(k, v)| (k, v.decompact(ctx, ())))
.collect()
}
}
impl<T> Compact for Vec<T>
where
T: Compact,
{
type Output = Vec<T::Output>;
fn compact(&self, ctx: &mut CompactContext) -> Self::Output {
self.iter().map(|x| x.compact(ctx)).collect()
}
}
impl<T> ArrangeId for Vec<T>
where
T: ArrangeId,
{
fn arrange_id(&mut self, ids: &Graphs<u64>) {
self.iter_mut().for_each(|x| x.arrange_id(ids))
}
}
impl<T> Decompact for Vec<T>
where
T: Decompact<Args = ()>,
{
type Args = ();
type Output = Vec<T::Output>;
fn decompact(self, ctx: &mut DecompactContext, (): Self::Args) -> Self::Output {
self.into_iter().map(|x| x.decompact(ctx, ())).collect()
}
}
impl<T> Compact for Option<T>
where
T: Compact,
{
type Output = Option<T::Output>;
fn compact(&self, ctx: &mut CompactContext) -> Self::Output {
self.as_ref().map(|x| x.compact(ctx))
}
}
impl<T> ArrangeId for Option<T>
where
T: ArrangeId,
{
fn arrange_id(&mut self, ids: &Graphs<u64>) {
if let Some(x) = self.as_mut() {
x.arrange_id(ids);
}
}
}
impl<T> Decompact for Option<T>
where
T: Decompact,
{
type Args = T::Args;
type Output = Option<T::Output>;
fn decompact(self, ctx: &mut DecompactContext, args: Self::Args) -> Self::Output {
self.map(|x| x.decompact(ctx, args))
}
}
impl<T> Compact for Box<T>
where
T: Compact,
{
type Output = Box<T::Output>;
fn compact(&self, ctx: &mut CompactContext) -> Self::Output {
Self::Output::new((**self).compact(ctx))
}
}
impl<T> ArrangeId for Box<T>
where
T: ArrangeId,
{
fn arrange_id(&mut self, ids: &Graphs<u64>) {
(**self).arrange_id(ids)
}
}
impl<T> Decompact for Box<T>
where
T: Decompact,
{
type Args = T::Args;
type Output = Box<T::Output>;
fn decompact(self, ctx: &mut DecompactContext, args: Self::Args) -> Self::Output {
Self::Output::new((*self).decompact(ctx, args))
}
}
|
#![unstable]
pub enum Target {
Assembly,
Brainfuck,
DT,
Ook,
Whitespace,
}
pub fn detect_target(option: Option<String>, filename: &String) -> Option<Target> {
match option {
Some(ref val) => match val.as_slice() {
"asm" => Some(Assembly),
"bf" => Some(Brainfuck),
"dt" => Some(DT),
"ook" => Some(Ook),
"ws" => Some(Whitespace),
_ => None,
},
None => {
let slice = filename.as_slice();
let comps: Vec<&str> = slice.split('.').collect();
if comps.len() < 2 {
Some(Whitespace)
} else {
match *comps.last().unwrap() {
"asm" => Some(Assembly),
"bf" => Some(Brainfuck),
"dt" => Some(DT),
"ook" => Some(Ook),
_ => Some(Whitespace),
}
}
},
}
}
|
use proconio::{input, marker::Bytes};
fn main() {
input! {
n: usize,
s: Bytes,
};
for i in 1..n {
let ans = s.iter().zip(s[i..].iter()).take_while(|(b1, b2)| b1 != b2).count();
println!("{}", ans);
}
}
|
extern crate proconio;
use proconio::input;
fn main() {
input! {
n: usize,
k: usize,
mut p: [usize; n],
c: [i64; n],
}
let p = p.iter().map(|x| x - 1).collect::<Vec<_>>();
let mut q = vec![0; n];
for (i, &x) in p.iter().enumerate() {
q[x] = i;
}
let mut ans = std::i64::MIN;
for i in 0..n {
let mut cur = i;
let mut s = 0;
let mut cycle = false;
let mut len: usize = 0;
for _ in 0..k {
cur = p[cur];
s += c[cur];
ans = std::cmp::max(ans, s);
len += 1;
if cur == i {
cycle = true;
break;
}
}
if cycle {
let mut a = k / len;
if a >= 2 {
a -= 2;
}
s = s * a as i64;
cur = i;
let mut t = 0;
for _ in 0..(k - a * len) {
cur = p[cur];
t += c[cur];
ans = std::cmp::max(ans, s + t);
}
}
}
println!("{}", ans);
}
|
//! This module contains helpers when writing pools for objects
//! that don't support async and need to be run inside a thread.
use std::{
any::Any,
fmt,
marker::PhantomData,
sync::{Arc, Mutex},
};
use crate::{runtime::SpawnBlockingError, Runtime};
/// This error is returned when the [`Connection::interact`] call
/// fails.
#[derive(Debug)]
pub enum InteractError<E> {
/// The provided callback panicked
Panic(Box<dyn Any + Send + 'static>),
/// The callback was aborted
Aborted,
/// backend returned an error
Backend(E),
}
impl<E> fmt::Display for InteractError<E>
where
E: std::error::Error,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Panic(_) => write!(f, "Panic"),
Self::Aborted => write!(f, "Aborted"),
Self::Backend(e) => write!(f, "Backend error: {}", e),
}
}
}
impl<E> std::error::Error for InteractError<E> where E: std::error::Error {}
/// A wrapper for objects which only provides blocking functions that
/// need to be called on a separate thread. This wrapper provides access
/// to the wrapped object via the `interact` function.
pub struct SyncWrapper<T, E>
where
T: Send + 'static,
E: Send + 'static,
{
obj: Arc<Mutex<Option<T>>>,
runtime: Runtime,
_error: PhantomData<fn() -> E>,
}
impl<T, E> SyncWrapper<T, E>
where
T: Send + 'static,
E: Send + 'static,
{
/// Create a new wrapped object.
pub async fn new<F>(runtime: Runtime, f: F) -> Result<Self, E>
where
F: FnOnce() -> Result<T, E> + Send + 'static,
{
let result = match runtime.spawn_blocking(move || f()).await {
// FIXME panicking when the creation panics is not nice
// In order to handle this properly the Manager::create
// methods needs to support a custom error enum which
// supports a Panic variant.
Err(SpawnBlockingError::Panic(e)) => panic!("{:?}", e),
Ok(obj) => obj,
};
result.map(|obj| Self {
obj: Arc::new(Mutex::new(Some(obj))),
runtime,
_error: PhantomData::default(),
})
}
/// Interact with the underlying object. This function expects a closure
/// that takes the object as parameter. The closure is executed in a
/// separate thread so that the async runtime is not blocked.
pub async fn interact<F, R>(&self, f: F) -> Result<R, InteractError<E>>
where
F: FnOnce(&T) -> Result<R, E> + Send + 'static,
R: Send + 'static,
{
let arc = self.obj.clone();
self.runtime
.spawn_blocking(move || {
let guard = arc.lock().unwrap();
let conn = guard.as_ref().unwrap();
f(&conn)
})
.await
.map_err(|e| match e {
SpawnBlockingError::Panic(p) => InteractError::Panic(p),
})?
.map_err(InteractError::Backend)
}
/// Returns if the underlying mutex has been poisoned.
/// This happens when a panic occurs while interacting with
/// the object.
pub fn is_mutex_poisoned(&self) -> bool {
self.obj.is_poisoned()
}
}
impl<T, E> Drop for SyncWrapper<T, E>
where
T: Send + 'static,
E: Send + 'static,
{
fn drop(&mut self) {
let arc = self.obj.clone();
// Drop the `rusqlite::Connection` inside a `spawn_blocking`
// as the `drop` function of it can block.
self.runtime
.spawn_blocking_background(move || match arc.lock() {
Ok(mut guard) => drop(guard.take()),
Err(e) => drop(e.into_inner().take()),
})
.unwrap();
}
}
|
extern crate sdl2;
extern crate rand;
use sdl2::pixels::Color;
use sdl2::rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use rand::Rng;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
const X: usize = 1280;
const Y: usize = 720;
const THREAD_NUMBER: u32 = 4;
const BLOCK_SIZE: usize = 200;
#[derive(Debug)]
struct Cell {
live: AtomicBool,
temp_live: AtomicBool,
}
#[derive(Debug)]
struct Block {
x_min: usize,
x_max: usize,
y_min: usize,
y_max: usize,
}
fn initialize_cell_matrix() -> Vec<Vec<Cell>> {
let mut vec: Vec<Vec<Cell>> = Vec::new();
let mut rng = rand::thread_rng();
for x in 0..X {
let mut vec_y: Vec<Cell> = Vec::new();
for y in 0..Y {
//edges = no Cell
if x == 0 || x == X - 1 || y == 0 || y == Y - 1 {
vec_y.push(Cell {
live: AtomicBool::new(false),
temp_live: AtomicBool::new(false),
});
continue;
}
//let bool_value:bool = rng.gen();
let bool_value: bool = rng.gen();
vec_y.push(Cell {
live: AtomicBool::new(bool_value),
temp_live: AtomicBool::new(false),
});
}
vec.push(vec_y);
}
return vec;
}
fn initialize_block() -> Vec<Block> {
#![allow(unused_assignments)]
let mut vec_block:Vec<Block> = Vec::new();
let mut x_min = 0;
let mut y_min = 0;
let mut x_max = 0;
let mut y_max = 0;
let mut max_x:bool = true;
let mut max_y:bool = false;
loop {
if max_x == true {
if max_y == true { return vec_block; }
y_min = y_max;
y_max = y_min + BLOCK_SIZE;
if y_max >= Y - 2 { y_max = Y - 2 ; max_y = true; }
x_max = 0;
max_x = false;
}
x_min = x_max;
x_max = x_min + BLOCK_SIZE;
if x_max >= X - 2 { x_max = X - 2; max_x = true; }
let block = Block {x_min, x_max, y_min, y_max};
vec_block.push(block);
}
}
fn main() {
let mut tick: u32 = 0;
let vec = initialize_cell_matrix();
let arc_vec_renderer = Arc::new(vec);
let arc_vec_compute = arc_vec_renderer.clone();
let vec_block = initialize_block();
let arc_vec_block = Arc::new(vec_block);
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("Game of life", X as u32, Y as u32)
.position_centered()
.opengl()
.build()
.unwrap();
let mut canvas = window.into_canvas().build().unwrap();
let mut event_pump = sdl_context.event_pump().unwrap();
thread::spawn(move || {
let begin_time = Instant::now();
let (tx, rx) = mpsc::channel();
let mut vec_txbis = Vec::new();
for thread_id in 0..THREAD_NUMBER as usize {
let arc_vec = arc_vec_compute.clone();
let arc_vec_block = arc_vec_block.clone();
let tx = mpsc::Sender::clone(&tx);
let (txbis, rxbis) = mpsc::channel();
vec_txbis.push(txbis);
thread::spawn(move || {
update(
arc_vec,
arc_vec_block,
tx,
rxbis,
thread_id as u32,
);
});
}
let block_count_max = arc_vec_block.len() as i32;
loop {
let mut block_count = 0;
let mut block_received_count = 0;
// initialize neighbour_check work
for thread_id in 0..THREAD_NUMBER as usize {
vec_txbis[thread_id].send((0, block_count)).unwrap();
block_count = block_count + 1;
if block_count == block_count_max { break; }
}
// distribute neighbour_check work dynamically
loop {
if block_count == block_count_max { break; }
let received = rx.recv().unwrap();
if received.1 >= 0 { block_received_count = block_received_count + 1 }
vec_txbis[received.0 as usize].send((0, block_count)).unwrap();
block_count = block_count + 1;
}
// wait threads
loop {
let received = rx.recv().unwrap();
if received.1 >= 0 { block_received_count = block_received_count + 1 }
if block_received_count == block_count_max { break; }
}
block_count = 0;
block_received_count = 0;
// initialize update_value work
for thread_id in 0..THREAD_NUMBER as usize {
vec_txbis[thread_id].send((1, block_count)).unwrap();
block_count = block_count + 1;
if block_count == block_count_max { break; }
}
// distribute update_value work dynamically
loop {
if block_count == block_count_max { break; }
let received = rx.recv().unwrap();
if received.1 >= 0 { block_received_count = block_received_count + 1 }
vec_txbis[received.0 as usize].send((1, block_count)).unwrap();
block_count = block_count + 1;
}
// wait threads
loop {
let received = rx.recv().unwrap();
if received.1 >= 0 { block_received_count = block_received_count + 1 }
if block_received_count == block_count_max { break; }
}
tick = tick + 1;
//erase line
print!("\r");
let duration: Duration = Instant::now().duration_since(begin_time);
let tick_per_second: u32 = (tick as f64 / (duration.as_secs() as f64 + duration.subsec_millis() as f64 / 1000.0)) as u32;
print!("tick = {} tick per second = {} time = {:?}", tick, tick_per_second, duration);
}
});
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
break 'running
},
_ => {}
}
}
// The rest of the game loop goes here...
canvas.set_draw_color(Color::RGBA(255, 255, 255, 255));
canvas.clear();
canvas.set_draw_color(Color::RGBA(0, 0, 0, 255));
let mut points: Vec<rect::Point> = Vec::new();
for x in 0..arc_vec_renderer.len() {
for y in 0..arc_vec_renderer[x].len() {
if arc_vec_renderer[x][y].live.load(Ordering::Relaxed) == true {
points.push(rect::Point::new(x as i32, y as i32));
}
}
}
let _ = canvas.draw_points(&points[..]);
canvas.present();
}
}
fn update(
arc_vec: Arc<Vec<Vec<Cell>>>,
vec_block: Arc<Vec<Block>>,
tx: mpsc::Sender<(u32, i32)>,
rx: mpsc::Receiver<(u32, i32)>,
val: u32,
) {
let mut block_received = -1;
loop {
tx.send((val, block_received)).unwrap();
let received = rx.recv().unwrap();
let block = &vec_block[received.1 as usize];
block_received = received.1;
let x_min = block.x_min;
let x_max = block.x_max;
let y_min = block.y_min;
let y_max = block.y_max;
if received.0 == 0 {
let mut temp: u32 = 0;
for x in x_min..x_max {
if x == 0 || x >= X - 1 {
continue;
}
for y in y_min..y_max {
if y == 0 || y >= Y - 1 {
continue;
}
let x_minus = x - 1;
let x_plus = x + 1;
let y_minus = y - 1;
let y_plus = y + 1;
if arc_vec[x_minus][y_minus].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if arc_vec[x_minus][y].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if arc_vec[x_minus][y_plus].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if arc_vec[x][y_plus].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if arc_vec[x_plus][y_plus].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if arc_vec[x_plus][y].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if arc_vec[x_plus][y_minus].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if arc_vec[x][y_minus].live.load(Ordering::Relaxed) == true {
temp = temp + 1;
}
if temp <= 1 || temp >= 4 {
arc_vec[x][y].temp_live.store(false, Ordering::Relaxed)
} else if temp == 3 {
arc_vec[x][y].temp_live.store(true, Ordering::Relaxed)
} else {
arc_vec[x][y].temp_live.store(
arc_vec[x][y].live.load(Ordering::Relaxed),
Ordering::Relaxed,
)
}
temp = 0;
}
}
}
else {
for x in x_min..x_max {
if x == 0 || x >= X - 1 {
continue;
}
for y in y_min..y_max {
if y == 0 || y >= Y - 1 {
continue;
}
arc_vec[x][y].live.store(
arc_vec[x][y].temp_live.load(Ordering::Relaxed),
Ordering::Relaxed,
);
}
}
}
}
}
|
mod interop;
use crate::{
config_paths::CONFIG_PATHS,
event::Event,
topology::config::{DataType, TransformContext},
transforms::{
util::runtime_transform::{RuntimeTransform, Timer},
Transform,
},
};
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::path::PathBuf;
#[derive(Debug, Snafu)]
enum BuildError {
#[snafu(display("Invalid \"search_dirs\": {}", source))]
InvalidSearchDirs { source: rlua::Error },
#[snafu(display("Cannot evaluate Lua code in \"source\": {}", source))]
InvalidSource { source: rlua::Error },
#[snafu(display("Cannot evaluate Lua code defining \"hooks.init\": {}", source))]
InvalidHooksInit { source: rlua::Error },
#[snafu(display("Cannot evaluate Lua code defining \"hooks.process\": {}", source))]
InvalidHooksProcess { source: rlua::Error },
#[snafu(display("Cannot evaluate Lua code defining \"hooks.shutdown\": {}", source))]
InvalidHooksShutdown { source: rlua::Error },
#[snafu(display("Cannot evaluate Lua code defining timer handler: {}", source))]
InvalidTimerHandler { source: rlua::Error },
#[snafu(display("Runtime error in \"hooks.init\" function: {}", source))]
RuntimeErrorHooksInit { source: rlua::Error },
#[snafu(display("Runtime error in \"hooks.process\" function: {}", source))]
RuntimeErrorHooksProcess { source: rlua::Error },
#[snafu(display("Runtime error in \"hooks.shutdown\" function: {}", source))]
RuntimeErrorHooksShutdown { source: rlua::Error },
#[snafu(display("Runtime error in timer handler: {}", source))]
RuntimeErrorTimerHandler { source: rlua::Error },
#[snafu(display("Cannot call GC in Lua runtime: {}", source))]
RuntimeErrorGC { source: rlua::Error },
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct LuaConfig {
#[serde(default = "default_config_paths")]
search_dirs: Vec<PathBuf>,
hooks: HooksConfig,
#[serde(default)]
timers: Vec<TimerConfig>,
source: Option<String>,
}
fn default_config_paths() -> Vec<PathBuf> {
match CONFIG_PATHS.get() {
Some(config_paths) => config_paths
.clone()
.into_iter()
.map(|mut path_buf| {
path_buf.pop();
path_buf
})
.collect(),
None => vec![],
}
}
#[derive(Deserialize, Serialize, Debug)]
struct HooksConfig {
init: Option<String>,
process: String,
shutdown: Option<String>,
}
#[derive(Deserialize, Serialize, Debug)]
struct TimerConfig {
interval_seconds: u64,
handler: String,
}
// Implementation of methods from `TransformConfig`
// Note that they are implemented as struct methods instead of trait implementation methods
// because `TransformConfig` trait requires specification of a unique `typetag::serde` name.
// Specifying some name (for example, "lua_v*") results in this name being listed among
// possible configuration options for `transforms` section, but such internal name should not
// be exposed to users.
impl LuaConfig {
pub fn build(&self, _cx: TransformContext) -> crate::Result<Box<dyn Transform>> {
Lua::new(&self).map(|lua| Box::new(lua) as Box<dyn Transform>)
}
pub fn input_type(&self) -> DataType {
DataType::Any
}
pub fn output_type(&self) -> DataType {
DataType::Any
}
pub fn transform_type(&self) -> &'static str {
"lua"
}
}
// Lua's garbage collector sometimes seems to be not executed automatically on high event rates,
// which leads to leak-like RAM consumption pattern. This constant sets the number of invocations of
// the Lua transform after which GC would be called, thus ensuring that the RAM usage is not too high.
//
// This constant is larger than 1 because calling GC is an expensive operation, so doing it
// after each transform would have significant footprint on the performance.
const GC_INTERVAL: usize = 16;
pub struct Lua {
lua: rlua::Lua,
invocations_after_gc: usize,
timers: Vec<Timer>,
}
impl Lua {
pub fn new(config: &LuaConfig) -> crate::Result<Self> {
let lua = rlua::Lua::new();
let additional_paths = config
.search_dirs
.iter()
.map(|d| format!("{}/?.lua", d.to_string_lossy()))
.collect::<Vec<_>>()
.join(";");
let mut timers = Vec::new();
lua.context(|ctx| -> crate::Result<()> {
if !additional_paths.is_empty() {
let package = ctx.globals().get::<_, rlua::Table<'_>>("package")?;
let current_paths = package
.get::<_, String>("path")
.unwrap_or_else(|_| ";".to_string());
let paths = format!("{};{}", additional_paths, current_paths);
package.set("path", paths)?;
}
if let Some(source) = &config.source {
ctx.load(source).eval().context(InvalidSource)?;
}
if let Some(hooks_init) = &config.hooks.init {
let hooks_init: rlua::Function<'_> =
ctx.load(hooks_init).eval().context(InvalidHooksInit)?;
ctx.set_named_registry_value("hooks_init", Some(hooks_init))?;
}
let hooks_process: rlua::Function<'_> = ctx
.load(&config.hooks.process)
.eval()
.context(InvalidHooksProcess)?;
ctx.set_named_registry_value("hooks_process", hooks_process)?;
if let Some(hooks_shutdown) = &config.hooks.shutdown {
let hooks_shutdown: rlua::Function<'_> = ctx
.load(hooks_shutdown)
.eval()
.context(InvalidHooksShutdown)?;
ctx.set_named_registry_value("hooks_shutdown", Some(hooks_shutdown))?;
}
for (id, timer) in config.timers.iter().enumerate() {
let handler: rlua::Function<'_> = ctx
.load(&timer.handler)
.eval()
.context(InvalidTimerHandler)?;
ctx.set_named_registry_value(&format!("timer_handler_{}", id), handler)?;
timers.push(Timer {
id: id as u32,
interval_seconds: timer.interval_seconds,
});
}
Ok(())
})?;
Ok(Self {
lua,
invocations_after_gc: 0,
timers,
})
}
#[cfg(test)]
fn process(&mut self, event: Event, output: &mut Vec<Event>) -> Result<(), rlua::Error> {
let result = self.lua.context(|ctx: rlua::Context<'_>| {
ctx.scope(|scope| {
let emit = scope.create_function_mut(|_, event: Event| {
output.push(event);
Ok(())
})?;
let process = ctx.named_registry_value::<_, rlua::Function<'_>>("hooks_process")?;
process.call((event, emit))
})
});
self.attempt_gc();
result
}
#[cfg(test)]
fn process_single(&mut self, event: Event) -> Result<Option<Event>, rlua::Error> {
let mut out = Vec::new();
self.process(event, &mut out)?;
assert!(out.len() <= 1);
Ok(out.into_iter().next())
}
fn attempt_gc(&mut self) {
self.invocations_after_gc += 1;
if self.invocations_after_gc % GC_INTERVAL == 0 {
let _ = self
.lua
.gc_collect()
.context(RuntimeErrorGC)
.map_err(|e| error!(error = %e, rate_limit = 30));
self.invocations_after_gc = 0;
}
}
}
// A helper that reduces code duplication.
fn wrap_emit_fn<'lua, 'scope, F: 'scope>(
scope: &rlua::Scope<'lua, 'scope>,
mut emit_fn: F,
) -> rlua::Result<rlua::Function<'lua>>
where
F: FnMut(Event),
{
scope.create_function_mut(move |_, event: Event| -> rlua::Result<()> {
emit_fn(event);
Ok(())
})
}
impl RuntimeTransform for Lua {
fn hook_process<F>(self: &mut Self, event: Event, emit_fn: F)
where
F: FnMut(Event),
{
let _ = self
.lua
.context(|ctx: rlua::Context<'_>| {
ctx.scope(|scope| -> rlua::Result<()> {
let process =
ctx.named_registry_value::<_, rlua::Function<'_>>("hooks_process")?;
process.call((event, wrap_emit_fn(&scope, emit_fn)?))
})
})
.context(RuntimeErrorHooksProcess)
.map_err(|e| error!(error = %e, rate_limit = 30));
self.attempt_gc();
}
fn hook_init<F>(self: &mut Self, emit_fn: F)
where
F: FnMut(Event),
{
let _ = self
.lua
.context(|ctx: rlua::Context<'_>| {
ctx.scope(|scope| -> rlua::Result<()> {
match ctx.named_registry_value::<_, Option<rlua::Function<'_>>>("hooks_init")? {
Some(init) => init.call((wrap_emit_fn(&scope, emit_fn)?,)),
None => Ok(()),
}
})
})
.context(RuntimeErrorHooksInit)
.map_err(|e| error!(error = %e, rate_limit = 30));
self.attempt_gc();
}
fn hook_shutdown<F>(self: &mut Self, emit_fn: F)
where
F: FnMut(Event),
{
let _ = self
.lua
.context(|ctx: rlua::Context<'_>| {
ctx.scope(|scope| -> rlua::Result<()> {
match ctx
.named_registry_value::<_, Option<rlua::Function<'_>>>("hooks_shutdown")?
{
Some(shutdown) => shutdown.call((wrap_emit_fn(&scope, emit_fn)?,)),
None => Ok(()),
}
})
})
.context(RuntimeErrorHooksInit)
.map_err(|e| error!(error = %e, rate_limit = 30));
self.attempt_gc();
}
fn timer_handler<F>(self: &mut Self, timer: Timer, emit_fn: F)
where
F: FnMut(Event),
{
let _ = self
.lua
.context(|ctx: rlua::Context<'_>| {
ctx.scope(|scope| -> rlua::Result<()> {
let handler_name = format!("timer_handler_{}", timer.id);
let handler =
ctx.named_registry_value::<_, rlua::Function<'_>>(&handler_name)?;
handler.call((wrap_emit_fn(&scope, emit_fn)?,))
})
})
.context(RuntimeErrorTimerHandler)
.map_err(|e| error!(error = %e, rate_limit = 30));
self.attempt_gc();
}
fn timers(&self) -> Vec<Timer> {
self.timers.clone()
}
}
#[cfg(test)]
fn format_error(error: &rlua::Error) -> String {
match error {
rlua::Error::CallbackError { traceback, cause } => format_error(&cause) + "\n" + traceback,
err => err.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::{format_error, Lua};
use crate::{
event::{
metric::{Metric, MetricKind, MetricValue},
Event, Value,
},
test_util::runtime,
transforms::Transform,
};
use futures01::{stream, Stream};
fn from_config(config: &str) -> crate::Result<Lua> {
Lua::new(&toml::from_str(config).unwrap())
}
#[test]
fn lua_add_field() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event["log"]["hello"] = "goodbye"
emit(event)
end
"""
"#,
)
.unwrap();
let event = Event::from("program me");
let event = transform.transform(event).unwrap();
assert_eq!(event.as_log()[&"hello".into()], "goodbye".into());
}
#[test]
fn lua_read_field() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
_, _, name = string.find(event.log.message, "Hello, my name is (%a+).")
event.log.name = name
emit(event)
end
"""
"#,
)
.unwrap();
let event = Event::from("Hello, my name is Bob.");
let event = transform.transform(event).unwrap();
assert_eq!(event.as_log()[&"name".into()], "Bob".into());
}
#[test]
fn lua_remove_field() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event.log.name = nil
emit(event)
end
"""
"#,
)
.unwrap();
let mut event = Event::new_empty_log();
event.as_mut_log().insert("name", "Bob");
let event = transform.transform(event).unwrap();
assert!(event.as_log().get(&"name".into()).is_none());
}
#[test]
fn lua_drop_event() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
-- emit nothing
end
"""
"#,
)
.unwrap();
let mut event = Event::new_empty_log();
event.as_mut_log().insert("name", "Bob");
let event = transform.transform(event);
assert!(event.is_none());
}
#[test]
fn lua_duplicate_event() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
emit(event)
emit(event)
end
"""
"#,
)
.unwrap();
let mut event = Event::new_empty_log();
event.as_mut_log().insert("host", "127.0.0.1");
let mut out = Vec::new();
transform.transform_into(&mut out, event);
assert_eq!(out.len(), 2);
}
#[test]
fn lua_read_empty_field() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
if event["log"]["non-existant"] == nil then
event["log"]["result"] = "empty"
else
event["log"]["result"] = "found"
end
emit(event)
end
"""
"#,
)
.unwrap();
let event = Event::new_empty_log();
let event = transform.transform(event).unwrap();
assert_eq!(event.as_log()[&"result".into()], "empty".into());
}
#[test]
fn lua_integer_value() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event["log"]["number"] = 3
emit(event)
end
"""
"#,
)
.unwrap();
let event = transform.transform(Event::new_empty_log()).unwrap();
assert_eq!(event.as_log()[&"number".into()], Value::Integer(3));
}
#[test]
fn lua_numeric_value() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event["log"]["number"] = 3.14159
emit(event)
end
"""
"#,
)
.unwrap();
let event = transform.transform(Event::new_empty_log()).unwrap();
assert_eq!(event.as_log()[&"number".into()], Value::Float(3.14159));
}
#[test]
fn lua_boolean_value() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event["log"]["bool"] = true
emit(event)
end
"""
"#,
)
.unwrap();
let event = transform.transform(Event::new_empty_log()).unwrap();
assert_eq!(event.as_log()[&"bool".into()], Value::Boolean(true));
}
#[test]
fn lua_non_coercible_value() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event["log"]["junk"] = nil
emit(event)
end
"""
"#,
)
.unwrap();
let event = transform.transform(Event::new_empty_log()).unwrap();
assert_eq!(event.as_log().get(&"junk".into()), None);
}
#[test]
fn lua_non_string_key_write() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event["log"][false] = "hello"
emit(event)
end
"""
"#,
)
.unwrap();
let err = transform
.process_single(Event::new_empty_log())
.unwrap_err();
let err = format_error(&err);
assert!(err.contains("error converting Lua boolean to String"), err);
}
#[test]
fn lua_non_string_key_read() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event.log.result = event.log[false]
emit(event)
end
"""
"#,
)
.unwrap();
let event = transform.transform(Event::new_empty_log()).unwrap();
assert_eq!(event.as_log().get(&"result".into()), None);
}
#[test]
fn lua_script_error() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
error("this is an error")
end
"""
"#,
)
.unwrap();
let err = transform
.process_single(Event::new_empty_log())
.unwrap_err();
let err = format_error(&err);
assert!(err.contains("this is an error"), err);
}
#[test]
fn lua_syntax_error() {
crate::test_util::trace_init();
let err = from_config(
r#"
hooks.process = """function (event, emit)
1234 = sadf <>&*!#@
end
"""
"#,
)
.map(|_| ())
.unwrap_err()
.to_string();
assert!(err.contains("syntax error:"), err);
}
#[test]
fn lua_load_file() {
use std::fs::File;
use std::io::Write;
crate::test_util::trace_init();
let dir = tempfile::tempdir().unwrap();
let mut file = File::create(dir.path().join("script2.lua")).unwrap();
write!(
&mut file,
r#"
local M = {{}}
local function modify(event2)
event2["log"]["new field"] = "new value"
end
M.modify = modify
return M
"#
)
.unwrap();
let config = format!(
r#"
hooks.process = """function (event, emit)
local script2 = require("script2")
script2.modify(event)
emit(event)
end
"""
search_dirs = [{:?}]
"#,
dir.path().as_os_str() // This seems a bit weird, but recall we also support windows.
);
let mut transform = from_config(&config).unwrap();
let event = Event::new_empty_log();
let event = transform.transform(event).unwrap();
assert_eq!(event.as_log()[&"new field".into()], "new value".into());
}
#[test]
fn lua_pairs() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
for k,v in pairs(event.log) do
event.log[k] = k .. v
end
emit(event)
end
"""
"#,
)
.unwrap();
let mut event = Event::new_empty_log();
event.as_mut_log().insert("name", "Bob");
event.as_mut_log().insert("friend", "Alice");
let event = transform.transform(event).unwrap();
assert_eq!(event.as_log()[&"name".into()], "nameBob".into());
assert_eq!(event.as_log()[&"friend".into()], "friendAlice".into());
}
#[test]
fn lua_metric() {
crate::test_util::trace_init();
let mut transform = from_config(
r#"
hooks.process = """function (event, emit)
event.metric.counter.value = event.metric.counter.value + 1
emit(event)
end
"""
"#,
)
.unwrap();
let event = Event::Metric(Metric {
name: "example counter".into(),
timestamp: None,
tags: None,
kind: MetricKind::Absolute,
value: MetricValue::Counter { value: 1.0 },
});
let expected = Event::Metric(Metric {
name: "example counter".into(),
timestamp: None,
tags: None,
kind: MetricKind::Absolute,
value: MetricValue::Counter { value: 2.0 },
});
let event = transform.transform(event).unwrap();
assert_eq!(event, expected);
}
#[test]
fn lua_multiple_events() {
crate::test_util::trace_init();
let transform = from_config(
r#"
hooks.process = """function (event, emit)
event["log"]["hello"] = "goodbye"
emit(event)
end
"""
"#,
)
.unwrap();
let n = 10;
let events = (0..n).map(|i| Event::from(format!("program me {}", i)));
let stream =
Transform::transform_stream(Box::new(transform), Box::new(stream::iter_ok(events)));
let mut rt = runtime();
let results = rt.block_on(stream.collect()).unwrap();
assert_eq!(results.len(), n);
}
}
|
use std::error::Error;
use std::path::PathBuf;
use crate::commands::Command;
use crate::config::Config;
use crate::config::{DotItem, DotType};
use crate::error::{SourceFileIsDottied, SymlinkSourceNotSupported, UnknownFileType};
use crate::fs::File;
use crate::{show_error, show_info};
pub struct AddOpt {
path: String,
name: String,
src: String,
}
impl AddOpt {
pub fn new(path: &str, name: &str, src: &str) -> AddOpt {
AddOpt {
name: name.to_string(),
path: path.to_string(),
src: src.to_string(),
}
}
fn default_name(&self, src: &PathBuf) -> String {
if self.name.is_empty() {
// if name is not set, convert fn.ext to fn_ext
let name = src.file_name().unwrap().to_str().unwrap().replace(".", "_");
return name;
}
self.name.to_string()
}
}
impl Command for AddOpt {
fn run(&self) -> Result<(), Box<dyn Error>> {
let mut cfg = Config::from_toml(&PathBuf::from(&self.path)).unwrap();
let src = PathBuf::from(&self.src);
if cfg.is_dottied(&src) {
show_error!("Source dotfile `{}` has already been dottied", self.src);
return Err(Box::new(SourceFileIsDottied));
}
let mut item = DotItem {
name: self.default_name(&src).to_string(),
src,
target: PathBuf::from(&self.path), // TODO: expand source and target
dot_type: DotType::File,
symlinked: false,
};
// TODO: check whether target is dottied
let f = File::from_path(&item.src);
if f.is_symlink() {
show_error!(
"Source dotfile `{}` has been already a symbolic link",
self.src
);
return Err(Box::new(SymlinkSourceNotSupported));
} else if f.is_dir() {
show_info!("Adding directory => {}", self.src);
item.dot_type = DotType::Dir;
} else if f.is_file() {
show_info!("Adding file => {}", self.src);
} else {
show_error!("Unknown file type `{}`", self.src);
return Err(Box::new(UnknownFileType));
}
match cfg.add(item) {
Err(e) => return Err(e),
_ => (),
}
cfg.save()
// TODO: move the files
}
}
#[cfg(test)]
mod test {
use crate::commands::add::*;
#[test]
fn convert_to_default_name() {
let add = AddOpt::new(".", "", "./init.vim");
let def_name = add.default_name(&PathBuf::from("init.vim"));
assert_eq!("init_vim", def_name);
}
}
|
pub mod riscv_vm;
pub mod memory;
pub mod instruction;
pub mod defines;
pub mod bit_utils;
|
// 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.
//! Watchers handles a list of watcher connections attached to a directory. Watchers as described
//! in io.fidl.
use {
failure::Fail,
fidl_fuchsia_io::{
WatchedEvent, MAX_FILENAME, WATCH_EVENT_EXISTING, WATCH_EVENT_IDLE, WATCH_MASK_EXISTING,
WATCH_MASK_IDLE,
},
fuchsia_async::Channel,
fuchsia_zircon::MessageBuf,
futures::{task::Context, Poll},
std::iter,
};
/// Type of the errors that might be generated by the [`Watchers::add`] method.
#[derive(Debug, Fail)]
pub enum WatchersAddError {
/// Provided name of an entry was longer than MAX_FILENAME bytes. Watcher connection will be
/// dropped.
#[fail(display = "Provided entry name exceeds MAX_FILENAME bytes")]
NameTooLong,
/// FIDL communication error. Failure occured while trying to send initial events to the newly
/// connected watcher. Watcher connection will be dropped.
#[fail(display = "Error sending initial list of entries due to a FIDL error")]
FIDL(fidl::Error),
}
/// Type of the errors that might be generated when trying to send new event to watchers.
#[derive(Debug, Fail)]
pub enum WatchersSendError {
/// Provided name of an entry was longer than MAX_FILENAME bytes.
#[fail(display = "Provided entry name exceeds MAX_FILENAME bytes")]
NameTooLong,
}
/// Wraps all watcher connections observing one directory. The directory is responsible for
/// calling [`send_event`], [`remove_dead`] and [`add`] methods when appropriate to make sure
/// watchers are observing a consistent view.
pub struct Watchers {
connections: Vec<WatcherConnection>,
}
impl Watchers {
/// Constructs a new Watchers instance with no connected watchers.
pub fn new() -> Self {
Watchers { connections: Vec::new() }
}
/// Connects a new watcher (connected over the `channel`) to the list of watchers. This
/// watcher will receive WATCH_EVENT_EXISTING event with all the names provided by the `names`
/// argument. `mask` is the event mask this watcher has requested.
// NOTE Initially I have used `&mut Iterator<Item = &str>` as a type for `names`. But that
// effectively says that names of all the entries should exist for the lifetime of the
// iterator. As one may store those references for the duration of the lifetime of the
// iterator reference.
//
// When entry names are dynamically generated, as in the "lazy" directory this could be
// inefficient. I would not want the iterator to own all the entry names. At the same time,
// `add()` does not really need for those names to exist all the time, it only processes one
// name at a time and never returns to the previous name.
//
// One way to be precise about the actual usage pattern that `add` is following is to use a
// "sink" instead of an iterator, controlled by the producer. `names` then becomes:
//
// names: FnMut(&mut FnMut(&str) -> bool),
//
// `add()` will call `names()` providing a "sink" that will see entry names one at time. Sink
// may stop the iteration if it returns `false`. Calling `names` again will continue the
// iteration. But, this interface is quite unusual, as most people will probably expect to see
// an `Iterator` here.
//
// Switching to `AsRef<str>` allows `add` to accept both `Iterator<Item = &str>`, for the case
// when all the entry names exist for the lifetime of the iterator, as well as `Iterator<Item =
// String>` for the case, when ownership of the entry names need to be passed on to the `add()`
// method itself.
pub fn add<Name>(
&mut self,
names: &mut dyn Iterator<Item = Name>,
mask: u32,
channel: Channel,
) -> Result<(), WatchersAddError>
where
Name: AsRef<str>,
{
let conn = WatcherConnection::new(mask, channel);
conn.send_events_existing(names)?;
conn.send_event_idle()?;
self.connections.push(conn);
Ok(())
}
/// Informs all the connected watchers about the specified event. While `mask` and `event`
/// carry the same information, as they are represented by `WATCH_MASK_*` and `WATCH_EVENT_*`
/// constants in io.fidl, it is easier when both forms are provided. `mask` is used to filter
/// out those watchers that did not request for observation of this event and `event` is used
/// to construct the event object. The method will operate correctly only if `mask` and
/// `event` match.
///
/// In case of a communication error with any of the watchers, connection to this watcher is
/// closed.
pub fn send_event<Name>(
&mut self,
mask: u32,
event: u8,
name: Name,
) -> Result<(), WatchersSendError>
where
Name: AsRef<str>,
{
let name = name.as_ref();
if name.len() >= MAX_FILENAME as usize {
return Err(WatchersSendError::NameTooLong);
}
self.connections.retain(|watcher| match watcher.send_event_check_mask(mask, event, name) {
Ok(()) => true,
Err(ConnectionSendError::NameTooLong) => {
// This assertion is never expected to trigger as we checked the name length above.
// It should indicate some kind of bug in the send_event_check_mask() logic.
panic!(
"send_event_check_mask() returned NameTooLong.\n\
Max length in bytes: {}\n\
Name length: '{}'\n\
Name: '{}'",
MAX_FILENAME,
name.len(),
name
);
}
Err(ConnectionSendError::FIDL(_)) => false,
});
Ok(())
}
/// Informs all the connected watchers about the specified event. While `mask` and `event`
/// carry the same information, as they are represented by `WATCH_MASK_*` and `WATCH_EVENT_*`
/// constants in io.fidl, it is easier when both forms are provided. `mask` is used to filter
/// out those watchers that did not request for observation of this event and `event` is used
/// to construct the event object. The method will operate correctly only if `mask` and
/// `event` match.
///
/// In case of a communication error with any of the watchers, connection to this watcher is
/// closed.
pub fn send_events<GetNames, Names, Name>(
&mut self,
mask: u32,
event: u8,
mut get_names: GetNames,
) -> Result<(), WatchersSendError>
where
GetNames: FnMut() -> Names,
Names: Iterator<Item = Name>,
Name: AsRef<str>,
{
let mut res = Ok(());
self.connections.retain(|watcher| {
let mut names = get_names();
match watcher.send_events_check_mask(mask, event, &mut names) {
Ok(()) => true,
Err(ConnectionSendError::NameTooLong) => {
// This is not a connection failure, so we are still keeping the connection
// alive.
res = Err(WatchersSendError::NameTooLong);
true
}
Err(ConnectionSendError::FIDL(_)) => false,
}
});
res
}
/// Checks if there are any connections in the list of watcher connections that has been
/// closed. Removes them and setup up the waker to wake up when any of the live connections is
/// closed.
pub fn remove_dead(&mut self, cx: &mut Context<'_>) {
self.connections.retain(|watcher| !watcher.is_dead(cx));
}
/// Returns true if there are any active watcher connections.
pub fn has_connections(&self) -> bool {
self.connections.len() != 0
}
/// Closes all the currently connected watcher connections. New connections may still be added
/// via add().
pub fn close_all(&mut self) {
self.connections.clear();
}
}
struct WatcherConnection {
mask: u32,
channel: Channel,
}
/// Type of the errors that may occure when trying to send a message over one connection.
enum ConnectionSendError {
/// Provided name was longer than MAX_FILENAME bytes.
NameTooLong,
/// FIDL communication error.
FIDL(fidl::Error),
}
impl From<ConnectionSendError> for WatchersAddError {
fn from(err: ConnectionSendError) -> WatchersAddError {
match err {
ConnectionSendError::NameTooLong => WatchersAddError::NameTooLong,
ConnectionSendError::FIDL(err) => WatchersAddError::FIDL(err),
}
}
}
impl From<fidl::Error> for ConnectionSendError {
fn from(err: fidl::Error) -> ConnectionSendError {
ConnectionSendError::FIDL(err)
}
}
impl WatcherConnection {
fn new(mask: u32, channel: Channel) -> Self {
WatcherConnection { mask, channel }
}
/// A helper used by other send_event*() methods. Sends a collection of
/// fidl_fuchsia_io::WatchEvent instances over this watcher connection. Will check to make
/// sure that `name` fields in the [`WatchedEvent`] instances do not exceed [`MAX_FILENAME`].
/// Will skip those entries where `name` exceeds the [`MAX_FILENAME`] bytes and will return
/// [`ConnectionSendError::NameTooLong`] error in that case.
/// `len` field should be `0`, it will be set to be equal to the length of the `name` field.
fn send_event_structs<Events>(&self, events: Events) -> Result<(), ConnectionSendError>
where
Events: Iterator<Item = WatchedEvent>,
{
// Unfortunately, io.fidl currently does not provide encoding for the watcher events.
// Seems to be due to
//
// https://bugs.fuchsia.dev/p/fuchsia/issues/detail?id=7903
//
// As soon as that is fixed we should switch to the generated binding.
//
// For now this code duplicates what the C++ version is doing:
//
// https://fuchsia.googlesource.com/fuchsia/+/ef9c451ba83a3ece22cad66b9dcfb446be291966/zircon/system/ulib/fs/watcher.cpp
//
// There is no Transaction wrapping the messages, as for the full blown FIDL events.
let mut res = Ok(());
let buffer = &mut vec![];
for event in events {
let name = event.name;
// Make an attempt to send as many names as possible, skipping those that exceed the
// limit.
if name.len() >= MAX_FILENAME as usize {
if res.is_ok() {
res = Err(ConnectionSendError::NameTooLong);
}
continue;
}
// Make sure we have room in our buffer for the next event.
if buffer.len() + (2 + name.len()) > fidl_fuchsia_io::MAX_BUF as usize {
self.channel
.write(&*buffer, &mut vec![])
.map_err(fidl::Error::ServerResponseWrite)?;
buffer.clear();
}
// `len` has to match the length of the `name` field. There is no reason to allow the
// caller to specify anything but 0 here. We make sure `name` is bounded above, and
// now we can actually calculate correct value for `len`.
debug_assert_eq!(event.len, 0);
// We are going to encode the file name length as u8.
debug_assert!(u8::max_value() as u64 >= MAX_FILENAME);
buffer.push(event.event);
buffer.push(name.len() as u8);
buffer.extend_from_slice(&*name);
}
if buffer.len() > 0 {
self.channel.write(&*buffer, &mut vec![]).map_err(fidl::Error::ServerResponseWrite)?;
}
res
}
/// Constructs and sends a fidl_fuchsia_io::WatchEvent instance over the watcher connection.
///
/// `event` is one of the WATCH_EVENT_* constants, with the values used to populate the `event`
/// field.
fn send_event<Name>(&self, event: u8, name: Name) -> Result<(), ConnectionSendError>
where
Name: AsRef<str>,
{
self.send_event_structs(&mut iter::once(WatchedEvent {
event,
len: 0,
name: name.as_ref().as_bytes().to_vec(),
}))
}
/// Constructs and sends a fidl_fuchsia_io::WatchEvent instance over the watcher connection.
///
/// `event` is one of the WATCH_EVENT_* constants, with the values used to populate the `event`
/// field.
fn send_events<Name>(
&self,
event: u8,
names: &mut dyn Iterator<Item = Name>,
) -> Result<(), ConnectionSendError>
where
Name: AsRef<str>,
{
self.send_event_structs(&mut names.map(|name| WatchedEvent {
event,
len: 0,
name: name.as_ref().as_bytes().to_vec(),
}))
}
/// Constructs and sends a fidl_fuchsia_io::WatchEvent instance over the watcher connection,
/// skipping the operation if the watcher did not request this kind of events to be delivered -
/// filtered by the mask value.
fn send_event_check_mask<Name>(
&self,
mask: u32,
event: u8,
name: Name,
) -> Result<(), ConnectionSendError>
where
Name: AsRef<str>,
{
if self.mask & mask == 0 {
return Ok(());
}
self.send_event(event, name)
}
/// Constructs and sends multiple fidl_fuchsia_io::WatchEvent instances over the watcher
/// connection, skipping the operation if the watcher did not request this kind of events to be
/// delivered - filtered by the mask value.
fn send_events_check_mask<Name>(
&self,
mask: u32,
event: u8,
names: &mut dyn Iterator<Item = Name>,
) -> Result<(), ConnectionSendError>
where
Name: AsRef<str>,
{
if self.mask & mask == 0 {
return Ok(());
}
self.send_events(event, names)
}
/// Sends one fidl_fuchsia_io::WatchEvent instance of type WATCH_EVENT_EXISTING, for every name
/// in the list. If the watcher has requested this kind of events - similar to to
/// [`send_event_check_mask`] above, but with a predefined mask and event type.
fn send_events_existing<Name>(
&self,
names: &mut dyn Iterator<Item = Name>,
) -> Result<(), ConnectionSendError>
where
Name: AsRef<str>,
{
if self.mask & WATCH_MASK_EXISTING == 0 {
return Ok(());
}
self.send_event_structs(&mut names.map(|name| WatchedEvent {
event: WATCH_EVENT_EXISTING,
len: 0,
name: name.as_ref().as_bytes().to_vec(),
}))
}
/// Sends one instance of fidl_fuchsia_io::WatchEvent of type WATCH_MASK_IDLE. If the watcher
/// has requested this kind of events - similar to to [`send_event_check_mask`] above, but with
/// the predefined mask and event type.
fn send_event_idle(&self) -> Result<(), ConnectionSendError> {
if self.mask & WATCH_MASK_IDLE == 0 {
return Ok(());
}
self.send_event(WATCH_EVENT_IDLE, "")
}
/// Checks if the watcher has closed the connection. And sets the waker to trigger when the
/// connection is closed if it was still opened during the call.
fn is_dead(&self, cx: &mut Context<'_>) -> bool {
let channel = &self.channel;
if channel.is_closed() {
return true;
}
// Make sure we will be notified when the watcher has closed its connected or when any
// message is send.
//
// We are going to close the connection when we receive any message as this is currently an
// error. When we fix ZX-2645 and wrap the watcher connection with FIDL, it would be up to
// the binding code to fail on any unexpected messages. At that point we can switch to
// fuchsia_async::OnSignals and only monitor for the close event.
//
// We rely on [`Channel::recv_from()`] to invoke [`Channel::poll_read()`], which would call
// [`RWHandle::poll_read()`] that would set the signal mask to `READABLE | CLOSE`.
let mut msg = MessageBuf::new();
match channel.recv_from(cx, &mut msg) {
// We are not expecting any messages. Returning true would cause this watcher
// connection to be dropped and closed as a result.
Poll::Ready(_) => true,
// Poll::Pending is actually the only value we are expecting to see from a watcher that
// did not close it's side of the connection. And when the connection is closed, we
// are expecting Poll::Ready(Err(Status::PEER_CLOSED.into_raw())), but that is covered
// by the case above.
Poll::Pending => false,
}
}
}
|
//! x86-64 Linux system calls.
use crate::backend::reg::{
ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm, A0, A1, A2, A3, A4, A5, R0,
};
use core::arch::asm;
#[cfg(target_pointer_width = "32")]
compile_error!("x32 is not yet supported");
#[inline]
pub(in crate::backend) unsafe fn syscall0_readonly(nr: SyscallNumber<'_>) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags, readonly)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall1(nr: SyscallNumber<'_>, a0: ArgReg<'_, A0>) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall1_readonly(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags, readonly)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall1_noreturn(nr: SyscallNumber<'_>, a0: ArgReg<'_, A0>) -> ! {
asm!(
"syscall",
in("rax") nr.to_asm(),
in("rdi") a0.to_asm(),
options(noreturn)
)
}
#[inline]
pub(in crate::backend) unsafe fn syscall2(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall2_readonly(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags, readonly)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall3(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall3_readonly(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags, readonly)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall4(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
a3: ArgReg<'_, A3>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
in("r10") a3.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall4_readonly(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
a3: ArgReg<'_, A3>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
in("r10") a3.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags, readonly)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall5(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
a3: ArgReg<'_, A3>,
a4: ArgReg<'_, A4>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
in("r10") a3.to_asm(),
in("r8") a4.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall5_readonly(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
a3: ArgReg<'_, A3>,
a4: ArgReg<'_, A4>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
in("r10") a3.to_asm(),
in("r8") a4.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags, readonly)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall6(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
a3: ArgReg<'_, A3>,
a4: ArgReg<'_, A4>,
a5: ArgReg<'_, A5>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
in("r10") a3.to_asm(),
in("r8") a4.to_asm(),
in("r9") a5.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags)
);
FromAsm::from_asm(r0)
}
#[inline]
pub(in crate::backend) unsafe fn syscall6_readonly(
nr: SyscallNumber<'_>,
a0: ArgReg<'_, A0>,
a1: ArgReg<'_, A1>,
a2: ArgReg<'_, A2>,
a3: ArgReg<'_, A3>,
a4: ArgReg<'_, A4>,
a5: ArgReg<'_, A5>,
) -> RetReg<R0> {
let r0;
asm!(
"syscall",
inlateout("rax") nr.to_asm() => r0,
in("rdi") a0.to_asm(),
in("rsi") a1.to_asm(),
in("rdx") a2.to_asm(),
in("r10") a3.to_asm(),
in("r8") a4.to_asm(),
in("r9") a5.to_asm(),
lateout("rcx") _,
lateout("r11") _,
options(nostack, preserves_flags, readonly)
);
FromAsm::from_asm(r0)
}
|
// See LICENSE file for copyright and license details.
pub mod visualizer;
pub mod mgl;
pub mod camera;
pub mod types;
pub mod geom;
pub mod picker;
pub mod obj;
pub mod mesh;
pub mod event_visualizer;
pub mod shader;
pub mod texture;
pub mod font_stash;
pub mod scene;
pub mod gui;
pub mod selection;
pub mod context;
pub mod state_visualizer;
pub mod game_state_visualizer;
pub mod menu_state_visualizer;
pub mod unit_type_visual_info;
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
|
mod with_false_left;
mod with_true_left;
use proptest::prop_assert_eq;
use proptest::test_runner::{Config, TestRunner};
use crate::erlang::or_2::result;
use crate::test::strategy;
#[test]
fn without_boolean_left_errors_badarg() {
crate::test::without_boolean_left_errors_badarg(file!(), result);
}
|
use std::{
fmt::{Debug, Display},
sync::Arc,
};
use data_types::ParquetFile;
use crate::{file_classification::FileClassification, partition_info::PartitionInfo, RoundInfo};
pub mod logging;
pub mod split_based;
pub trait FileClassifier: Debug + Display + Send + Sync {
fn classify(
&self,
partition_info: &PartitionInfo,
round_info: &RoundInfo,
files: Vec<ParquetFile>,
) -> FileClassification;
}
impl<T> FileClassifier for Arc<T>
where
T: FileClassifier + ?Sized,
{
fn classify(
&self,
partition_info: &PartitionInfo,
round_info: &RoundInfo,
files: Vec<ParquetFile>,
) -> FileClassification {
self.as_ref().classify(partition_info, round_info, files)
}
}
|
mod utils;
|
use std::hash::Hasher;
pub use json_utils::json::JsValue;
const HASH_PREFIX_NULL: u8 = 0;
const HASH_PREFIX_BOOL: u8 = 1;
const HASH_PREFIX_NUMBER: u8 = 2;
const HASH_PREFIX_STRING: u8 = 3;
const HASH_PREFIX_ARRAY: u8 = 4;
const HASH_PREFIX_OBJECT: u8 = 5;
pub fn js_value_hash<H: Hasher>(value: &JsValue, hasher: &mut H) {
match value {
JsValue::Null => hasher.write_u8(HASH_PREFIX_NULL),
JsValue::Bool(false) => hasher.write(&[HASH_PREFIX_BOOL, 0]),
JsValue::Bool(true) => hasher.write(&[HASH_PREFIX_BOOL, 1]),
JsValue::String(string) => {
hasher.write_u8(HASH_PREFIX_STRING);
hasher.write(string.as_bytes());
}
JsValue::Number(number) => {
hasher.write_u8(HASH_PREFIX_NUMBER);
if let Some(u) = number.as_u64() {
hasher.write_u64(u)
} else if let Some(i) = number.as_i64() {
hasher.write_i64(i)
} else if let Some(f) = number.as_f64() {
hasher.write_u64(f.to_bits())
} else {
unreachable!()
}
}
JsValue::Array(ref values) => {
hasher.write_u8(HASH_PREFIX_ARRAY);
for v in values {
js_value_hash(v, hasher)
}
}
JsValue::Object(ref fields) => {
hasher.write_u8(HASH_PREFIX_OBJECT);
let mut keys = fields.keys().collect::<Vec<_>>();
keys.sort_unstable();
for key in keys {
hasher.write(key.as_bytes());
if let Some(value) = fields.get(key) {
js_value_hash(value, hasher)
} else {
unreachable!("The key from the keys-iterator does not exist in the map")
}
}
}
}
}
|
use blockstore::Blockstore;
use config::Config;
use merkledag::DagService;
use std::sync::Arc;
pub struct IpfsNode {
pub config: Config,
pub blockstore: Arc<Blockstore>,
pub dagservice: Arc<DagService>,
}
impl IpfsNode {
pub fn new(blockstore: Blockstore, cfg: Config) -> Self {
let bs = Arc::new(blockstore);
IpfsNode {
config: cfg,
blockstore: bs.clone(),
dagservice: Arc::new(DagService::new(bs)),
}
}
}
|
#![link(name="git2")]
extern crate git2;
use git2::git2;
use git2::git2::{OID, ToOID};
#[test]
fn test_oid() {
let repo = match git2::Repository::open(&Path::new("/storage/home/achin/devel/libgit2.rs/tests/data/repoA")) {
Ok(r) => r,
Err(e) => fail!("Failed to open repo:\n{}", e.message)
};
assert!(repo.is_empty() == false);
let oid: OID = match "95d09f2b10159347eece71399a7e2e907ea3df4f".to_oid() {
Ok(o) => o,
Err(e) => fail!(e)
};
println!("OID is {}", oid);
assert!(oid.to_string().as_slice() == "95d09f2b10159347eece71399a7e2e907ea3df4f");
}
|
use chrono::NaiveDateTime;
use diesel;
use diesel::dsl::{exists, select};
use diesel::expression::dsl;
use diesel::prelude::*;
use models::scopes;
use models::*;
use schema::{organization_users, organizations, users, venues};
use utils::errors::*;
use uuid::Uuid;
#[derive(Identifiable, Associations, Queryable, AsChangeset)]
#[belongs_to(User, foreign_key = "owner_user_id")]
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[table_name = "organizations"]
pub struct Organization {
pub id: Uuid,
pub owner_user_id: Uuid,
pub name: String,
pub address: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub postal_code: Option<String>,
pub phone: Option<String>,
pub event_fee_in_cents: Option<i64>,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub fee_schedule_id: Uuid,
}
#[derive(Serialize)]
pub struct DisplayOrganizationLink {
pub id: Uuid,
pub name: String,
pub role: String,
}
#[derive(Default, Insertable, Serialize, Deserialize, PartialEq, Debug)]
#[table_name = "organizations"]
pub struct NewOrganization {
pub owner_user_id: Uuid,
pub name: String,
pub fee_schedule_id: Uuid,
pub event_fee_in_cents: Option<i64>,
pub address: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub postal_code: Option<String>,
pub phone: Option<String>,
}
impl NewOrganization {
pub fn commit(&self, conn: &PgConnection) -> Result<Organization, DatabaseError> {
let db_err = diesel::insert_into(organizations::table)
.values(self)
.get_result(conn)
.to_db_error(ErrorCode::InsertError, "Could not create new organization")?;
Ok(db_err)
}
}
#[derive(AsChangeset, Default, Deserialize)]
#[table_name = "organizations"]
pub struct OrganizationEditableAttributes {
pub name: Option<String>,
pub address: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub postal_code: Option<String>,
pub phone: Option<String>,
pub fee_schedule_id: Option<Uuid>,
pub event_fee_in_cents: Option<i64>,
}
impl Organization {
pub fn create(owner_user_id: Uuid, name: &str, fee_schedule_id: Uuid) -> NewOrganization {
NewOrganization {
owner_user_id: owner_user_id,
name: name.into(),
fee_schedule_id,
..Default::default()
}
}
pub fn update(
&self,
attributes: OrganizationEditableAttributes,
conn: &PgConnection,
) -> Result<Organization, DatabaseError> {
diesel::update(self)
.set((attributes, organizations::updated_at.eq(dsl::now)))
.get_result(conn)
.to_db_error(ErrorCode::UpdateError, "Could not update organization")
}
pub fn set_owner(
&self,
owner_user_id: Uuid,
conn: &PgConnection,
) -> Result<Organization, DatabaseError> {
diesel::update(self)
.set((
organizations::owner_user_id.eq(owner_user_id),
organizations::updated_at.eq(dsl::now),
)).get_result(conn)
.to_db_error(
ErrorCode::UpdateError,
"Could not update organization owner",
)
}
pub fn users(&self, conn: &PgConnection) -> Result<Vec<User>, DatabaseError> {
let organization_users = OrganizationUser::belonging_to(self);
let organization_owner = users::table
.find(self.owner_user_id)
.first::<User>(conn)
.to_db_error(
ErrorCode::QueryError,
"Could not retrieve organization users",
)?;
let mut users = organization_users
.inner_join(users::table)
.filter(users::id.ne(self.owner_user_id))
.select(users::all_columns)
.order_by(users::last_name.asc())
.then_order_by(users::first_name.asc())
.load::<User>(conn)
.to_db_error(
ErrorCode::QueryError,
"Could not retrieve organization users",
)?;
users.insert(0, organization_owner);
Ok(users)
}
pub fn venues(&self, conn: &PgConnection) -> Result<Vec<Venue>, DatabaseError> {
venues::table
.filter(venues::organization_id.eq(self.id))
.order_by(venues::name)
.get_results(conn)
.to_db_error(ErrorCode::QueryError, "Could not retrieve venues")
}
pub fn get_scopes_for_user(
&self,
user: &User,
conn: &PgConnection,
) -> Result<Vec<String>, DatabaseError> {
Ok(scopes::get_scopes(self.get_roles_for_user(user, conn)?))
}
pub fn get_roles_for_user(
&self,
user: &User,
conn: &PgConnection,
) -> Result<Vec<String>, DatabaseError> {
let mut roles = Vec::new();
if user.id == self.owner_user_id {
roles.push(Roles::OrgOwner.to_string());
roles.push(Roles::OrgMember.to_string());
} else {
if self.is_member(user, conn)? {
roles.push(Roles::OrgMember.to_string());
}
}
Ok(roles)
}
pub fn find(id: Uuid, conn: &PgConnection) -> Result<Organization, DatabaseError> {
organizations::table
.find(id)
.first::<Organization>(conn)
.to_db_error(ErrorCode::QueryError, "Error loading organization")
}
pub fn all(conn: &PgConnection) -> Result<Vec<Organization>, DatabaseError> {
DatabaseError::wrap(
ErrorCode::QueryError,
"Unable to load all organizations",
organizations::table
.order_by(organizations::name)
.load(conn),
)
}
pub fn owner(&self, conn: &PgConnection) -> Result<User, DatabaseError> {
DatabaseError::wrap(
ErrorCode::QueryError,
"Unable to load owner",
users::table.find(self.owner_user_id).first::<User>(conn),
)
}
pub fn all_linked_to_user(
user_id: Uuid,
conn: &PgConnection,
) -> Result<Vec<Organization>, DatabaseError> {
let orgs = organizations::table
.filter(organizations::owner_user_id.eq(user_id))
.load(conn)
.to_db_error(ErrorCode::QueryError, "Unable to load all organizations");
let mut orgs = match orgs {
Ok(o) => o,
Err(e) => return Err(e),
};
let mut org_members = organization_users::table
.filter(organization_users::user_id.eq(user_id))
.inner_join(organizations::table)
.select(organizations::all_columns)
.load::<Organization>(conn)
.to_db_error(ErrorCode::QueryError, "Unable to load all organizations")?;
orgs.append(&mut org_members);
orgs.sort_by(|a, b| a.name.cmp(&b.name));
Ok(orgs)
}
pub fn all_org_names_linked_to_user(
user_id: Uuid,
conn: &PgConnection,
) -> Result<Vec<DisplayOrganizationLink>, DatabaseError> {
//Compile list of organisations where the user is the owner
let org_owner_list: Vec<Organization> = organizations::table
.filter(organizations::owner_user_id.eq(user_id))
.load(conn)
.to_db_error(ErrorCode::QueryError, "Unable to load all organizations")?;
//Compile list of organisations where the user is a member of that organisation
let org_member_list: Vec<Organization> = organization_users::table
.filter(organization_users::user_id.eq(user_id))
.inner_join(organizations::table)
.select(organizations::all_columns)
.load::<Organization>(conn)
.to_db_error(ErrorCode::QueryError, "Unable to load all organizations")?;
//Compile complete list with only display information
let role_owner_string = String::from("owner");
let role_member_string = String::from("member");
let mut result_list: Vec<DisplayOrganizationLink> = Vec::new();
for curr_org_owner in &org_owner_list {
let curr_entry = DisplayOrganizationLink {
id: curr_org_owner.id,
name: curr_org_owner.name.clone(),
role: role_owner_string.clone(),
};
result_list.push(curr_entry);
}
for curr_org_member in &org_member_list {
let curr_entry = DisplayOrganizationLink {
id: curr_org_member.id,
name: curr_org_member.name.clone(),
role: role_member_string.clone(),
};
result_list.push(curr_entry);
}
result_list.sort_by(|a, b| a.name.cmp(&b.name));
Ok(result_list)
}
pub fn remove_user(&self, user_id: Uuid, conn: &PgConnection) -> Result<usize, DatabaseError> {
diesel::delete(
organization_users::table
.filter(organization_users::user_id.eq(user_id))
.filter(organization_users::organization_id.eq(self.id)),
).execute(conn)
.to_db_error(ErrorCode::DeleteError, "Error removing user")
}
pub fn add_user(
&self,
user_id: Uuid,
conn: &PgConnection,
) -> Result<OrganizationUser, DatabaseError> {
let org_user = OrganizationUser::create(self.id, user_id).commit(conn)?;
Ok(org_user)
}
pub fn is_member(&self, user: &User, conn: &PgConnection) -> Result<bool, DatabaseError> {
if self.owner_user_id == user.id {
return Ok(true);
}
let query = select(exists(
organization_users::table
.filter(
organization_users::user_id
.eq(user.id)
.and(organization_users::organization_id.eq(self.id)),
).select(organization_users::organization_id),
));
query
.get_result(conn)
.to_db_error(ErrorCode::QueryError, "Could not check user member status")
}
pub fn add_fee_schedule(
&self,
fee_schedule: &FeeSchedule,
conn: &PgConnection,
) -> Result<Organization, DatabaseError> {
let attributes = OrganizationEditableAttributes {
fee_schedule_id: Some(fee_schedule.id),
..Default::default()
};
diesel::update(self)
.set((attributes, organizations::updated_at.eq(dsl::now)))
.get_result(conn)
.to_db_error(
ErrorCode::UpdateError,
"Could not set the fee schedule for this organization",
)
}
}
|
use super::{opengl, Filter, Wrap, Texture, TextureHolder};
use super::opengl::{Attachment, Framebuffer};
use crate::error::{GameError, GameResult};
use crate::math::Size;
use crate::engine::Engine;
use std::rc::Rc;
pub struct Canvas {
framebuffer: Rc<Framebuffer>,
texture: Texture,
}
impl Canvas {
pub fn new(engine: &mut Engine, size: impl Into<Size<u32>>) -> GameResult<Self> {
let framebuffer = Framebuffer::new(engine.graphics().gl().clone())
.map_err(|error| GameError::InitError(error.into()))?;
let texture = Texture::new(engine, size, None)?;
framebuffer.bind();
framebuffer.attach_texture(Attachment::Color(0), Some(texture.texture().id()));
framebuffer.check_status().map_err(|error| GameError::InitError(error.into()))?;
framebuffer.unbind();
Ok(Self {
framebuffer: Rc::new(framebuffer),
texture,
})
}
pub(crate) fn framebuffer(&self) -> &Rc<Framebuffer> {
&self.framebuffer
}
pub fn size(&self) -> Size<u32> {
self.texture.size()
}
pub fn filter(&self) -> Filter {
self.texture.filter()
}
pub fn set_filter(&mut self, filter: Filter) {
self.texture.set_filter(filter)
}
pub fn wrap(&self) -> Wrap {
self.texture.wrap()
}
pub fn set_wrap(&mut self, wrap: Wrap) {
self.texture.set_wrap(wrap)
}
}
impl TextureHolder for Canvas {
fn texture(&self) -> &Rc<opengl::Texture> {
self.texture.texture()
}
fn texture_size(&self) -> Size<u32> {
self.texture.size()
}
}
pub const NO_CANVAS: Option<&Canvas> = None;
|
use std::io::{Read, Write};
use std::net::{TcpStream, Shutdown};
use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Sender, Receiver, TryRecvError};
use byteorder::{BigEndian, ReadBytesExt};
use ::{zrle, protocol, Rect, Colour, Error, Result};
use protocol::Message;
use security::des;
#[cfg(feature = "apple-auth")]
use security::apple_auth;
#[derive(Debug)]
pub enum AuthMethod {
None,
Password,
AppleRemoteDesktop,
/* more to come */
#[doc(hidden)]
__Nonexhaustive,
}
#[derive(Debug)]
pub enum AuthChoice {
None,
Password([u8; 8]),
AppleRemoteDesktop(String, String),
/* more to come */
#[doc(hidden)]
__Nonexhaustive,
}
#[derive(Debug)]
pub enum Event {
Disconnected(Option<Error>),
Resize(u16, u16),
SetColourMap { first_colour: u16, colours: Vec<Colour> },
PutPixels(Rect, Vec<u8>),
CopyPixels { src: Rect, dst: Rect },
EndOfFrame,
SetCursor { size: (u16, u16), hotspot: (u16, u16), pixels: Vec<u8>, mask_bits: Vec<u8> },
Clipboard(String),
Bell,
}
impl Event {
fn pump(mut stream: TcpStream, format: Arc<Mutex<protocol::PixelFormat>>,
tx_events: &mut Sender<Event>) -> Result<()> {
macro_rules! send {
($chan:expr, $data:expr) => ({
match $chan.send($data) {
Ok(()) => (),
Err(_) => break
}
})
}
let mut zrle_decoder = zrle::Decoder::new();
loop {
let packet =
match protocol::S2C::read_from(&mut stream) {
Ok(packet) => packet,
Err(Error::Disconnected) => {
send!(tx_events, Event::Disconnected(None));
break
},
Err(error) => return Err(error)
};
debug!("<- {:?}", packet);
let format = *format.lock().unwrap();
match packet {
protocol::S2C::SetColourMapEntries { first_colour, colours } => {
send!(tx_events, Event::SetColourMap {
first_colour: first_colour, colours: colours
})
},
protocol::S2C::FramebufferUpdate { count } => {
for _ in 0..count {
let rectangle = try!(protocol::Rectangle::read_from(&mut stream));
debug!("<- {:?}", rectangle);
let dst = Rect {
left: rectangle.x_position,
top: rectangle.y_position,
width: rectangle.width,
height: rectangle.height
};
match rectangle.encoding {
protocol::Encoding::Raw => {
let length = (rectangle.width as usize) *
(rectangle.height as usize) *
(format.bits_per_pixel as usize / 8);
let mut pixels = Vec::with_capacity(length);
unsafe { pixels.set_len(length as usize) }
try!(stream.read_exact(&mut pixels));
debug!("<- ...pixels");
send!(tx_events, Event::PutPixels(dst, pixels))
},
protocol::Encoding::CopyRect => {
let copy_rect = try!(protocol::CopyRect::read_from(&mut stream));
let src = Rect {
left: copy_rect.src_x_position,
top: copy_rect.src_y_position,
width: rectangle.width,
height: rectangle.height
};
send!(tx_events, Event::CopyPixels { src: src, dst: dst })
},
protocol::Encoding::Zrle => {
let length = try!(stream.read_u32::<BigEndian>());
let mut data = Vec::with_capacity(length as usize);
unsafe { data.set_len(length as usize) }
try!(stream.read_exact(&mut data));
debug!("<- ...compressed pixels");
let result = try!(zrle_decoder.decode(format, dst, &data,
|tile, pixels| {
Ok(tx_events.send(Event::PutPixels(tile, pixels)).is_ok())
}));
if !result { break }
}
protocol::Encoding::Cursor => {
let mut pixels = vec![0; (rectangle.width as usize) *
(rectangle.height as usize) *
(format.bits_per_pixel as usize / 8)];
try!(stream.read_exact(&mut pixels));
let mut mask_bits = vec![0; ((rectangle.width as usize + 7) / 8) *
(rectangle.height as usize)];
try!(stream.read_exact(&mut mask_bits));
send!(tx_events, Event::SetCursor {
size: (rectangle.width, rectangle.height),
hotspot: (rectangle.x_position, rectangle.y_position),
pixels: pixels,
mask_bits: mask_bits
})
},
protocol::Encoding::DesktopSize => {
send!(tx_events,
Event::Resize(rectangle.width, rectangle.height))
}
_ => return Err(Error::Unexpected("encoding"))
};
}
send!(tx_events, Event::EndOfFrame);
},
protocol::S2C::Bell =>
send!(tx_events, Event::Bell),
protocol::S2C::CutText(text) =>
send!(tx_events, Event::Clipboard(text))
}
}
Ok(())
}
}
pub struct Client {
stream: TcpStream,
events: Receiver<Event>,
name: String,
size: (u16, u16),
format: Arc<Mutex<protocol::PixelFormat>>
}
impl Client {
pub fn from_tcp_stream<Auth>(mut stream: TcpStream, shared: bool,
auth: Auth) -> Result<Client>
where Auth: FnOnce(&[AuthMethod]) -> Option<AuthChoice> {
let version = try!(protocol::Version::read_from(&mut stream));
debug!("<- Version::{:?}", version);
debug!("-> Version::{:?}", version);
try!(protocol::Version::write_to(&version, &mut stream));
let security_types = match version {
protocol::Version::Rfb33 => {
let security_type = try!(protocol::SecurityType::read_from(&mut stream));
debug!("<- SecurityType::{:?}", security_type);
if security_type == protocol::SecurityType::Invalid {
vec![]
} else {
vec![security_type]
}
},
_ => {
let security_types = try!(protocol::SecurityTypes::read_from(&mut stream));
debug!("<- {:?}", security_types);
security_types.0
}
};
if security_types.len() == 0 {
let reason = try!(String::read_from(&mut stream));
debug!("<- {:?}", reason);
return Err(Error::Server(reason))
}
let mut auth_methods = Vec::new();
for security_type in security_types {
match security_type {
protocol::SecurityType::None =>
auth_methods.push(AuthMethod::None),
protocol::SecurityType::VncAuthentication =>
auth_methods.push(AuthMethod::Password),
protocol::SecurityType::AppleRemoteDesktop =>
auth_methods.push(AuthMethod::AppleRemoteDesktop),
_ => ()
}
}
let auth_choice = try!(auth(&auth_methods).ok_or(Error::AuthenticationUnavailable));
match version {
protocol::Version::Rfb33 => (),
_ => {
let used_security_type = match auth_choice {
AuthChoice::None => protocol::SecurityType::None,
AuthChoice::Password(_) => protocol::SecurityType::VncAuthentication,
AuthChoice::AppleRemoteDesktop(_, _) => protocol::SecurityType::AppleRemoteDesktop,
AuthChoice::__Nonexhaustive => unreachable!()
};
debug!("-> SecurityType::{:?}", used_security_type);
try!(protocol::SecurityType::write_to(&used_security_type, &mut stream));
}
}
match auth_choice {
AuthChoice::Password(mut password) => {
// Reverse the bits in every byte of password.
// DES is 56-bit and as commonly implemented, it takes a 8-octet key
// and ignores LSB of every octet; this of course would be bad for
// ASCII passwords.
//
// I've spent *hours* figuring this out.
// I hate every single fucker involved in the chain of decisions that
// led to this authentication scheme, and doubly so because it is completely
// undocumented in what passes for the specification of the RFB protocol.
for i in 0..8 {
let c = password[i];
let mut cs = 0u8;
for j in 0..8 { cs |= ((c >> j) & 1) << (7 - j) }
password[i] = cs;
}
let mut challenge = [0; 16];
try!(stream.read_exact(&mut challenge));
let response = des(&challenge, &password);
try!(stream.write(&response));
},
#[cfg(feature = "apple-auth")]
AuthChoice::AppleRemoteDesktop(ref username, ref password) => {
let handshake = try!(protocol::AppleAuthHandshake::read_from(&mut stream));
let response = apple_auth(username, password, &handshake);
try!(response.write_to(&mut stream));
},
_ => (),
}
let mut skip_security_result = false;
match &(auth_choice, version) {
&(AuthChoice::None, protocol::Version::Rfb33) |
&(AuthChoice::None, protocol::Version::Rfb37) => skip_security_result = true,
_ => ()
}
if !skip_security_result {
match try!(protocol::SecurityResult::read_from(&mut stream)) {
protocol::SecurityResult::Succeeded => (),
protocol::SecurityResult::Failed => {
match version {
protocol::Version::Rfb33 |
protocol::Version::Rfb37 =>
return Err(Error::AuthenticationFailure(String::from(""))),
protocol::Version::Rfb38 => {
let reason = try!(String::read_from(&mut stream));
debug!("<- {:?}", reason);
return Err(Error::AuthenticationFailure(reason))
}
}
}
}
}
let client_init = protocol::ClientInit { shared: shared };
debug!("-> {:?}", client_init);
try!(protocol::ClientInit::write_to(&client_init, &mut stream));
let server_init = try!(protocol::ServerInit::read_from(&mut stream));
debug!("<- {:?}", server_init);
let format = Arc::new(Mutex::new(server_init.pixel_format));
let (tx_events, rx_events) = channel();
{
let stream = stream.try_clone().unwrap();
let format = format.clone();
thread::spawn(move || {
let mut tx_events = tx_events;
let error = Event::pump(stream, format, &mut tx_events).err();
let _ = tx_events.send(Event::Disconnected(error));
});
}
Ok(Client {
stream: stream,
events: rx_events,
name: server_init.name,
size: (server_init.framebuffer_width, server_init.framebuffer_height),
format: format
})
}
pub fn name(&self) -> &str { &self.name }
pub fn size(&self) -> (u16, u16) { self.size }
pub fn format(&self) -> protocol::PixelFormat { *self.format.lock().unwrap() }
pub fn set_encodings(&mut self, encodings: &[protocol::Encoding]) -> Result<()> {
let set_encodings = protocol::C2S::SetEncodings(Vec::from(encodings));
debug!("-> {:?}", set_encodings);
try!(protocol::C2S::write_to(&set_encodings, &mut self.stream));
Ok(())
}
pub fn request_update(&mut self, rect: Rect, incremental: bool) -> Result<()> {
let update_req = protocol::C2S::FramebufferUpdateRequest {
incremental: incremental,
x_position: rect.left,
y_position: rect.top,
width: rect.width,
height: rect.height
};
trace!("-> {:?}", update_req);
try!(protocol::C2S::write_to(&update_req, &mut self.stream));
Ok(())
}
pub fn send_key_event(&mut self, down: bool, key: u32) -> Result<()> {
let key_event = protocol::C2S::KeyEvent {
down: down,
key: key
};
debug!("-> {:?}", key_event);
try!(protocol::C2S::write_to(&key_event, &mut self.stream));
Ok(())
}
pub fn send_pointer_event(&mut self, buttons: u8, x: u16, y: u16) -> Result<()> {
let pointer_event = protocol::C2S::PointerEvent {
button_mask: buttons,
x_position: x,
y_position: y
};
debug!("-> {:?}", pointer_event);
try!(protocol::C2S::write_to(&pointer_event, &mut self.stream));
Ok(())
}
pub fn update_clipboard(&mut self, text: &str) -> Result<()> {
let cut_text = protocol::C2S::CutText(String::from(text));
debug!("-> {:?}", cut_text);
try!(protocol::C2S::write_to(&cut_text, &mut self.stream));
Ok(())
}
// Note that due to inherent weaknesses of the VNC protocol, this
// function is prone to race conditions that break the connection framing.
// The ZRLE encoding is self-delimiting and if both the client and server
// support and use it, there can be no race condition, but we currently don't.
pub fn set_format(&mut self, format: protocol::PixelFormat) -> Result<()> {
// Request (and discard) one full update to try and ensure that there
// are no FramebufferUpdate's in the buffers somewhere.
// This is not fully robust though (and cannot possibly be).
let _ = self.poll_iter().count(); // drain it
let framebuffer_rect = Rect { left: 0, top: 0, width: self.size.0, height: self.size.1 };
try!(self.request_update(framebuffer_rect, false));
'outer: loop {
for event in self.poll_iter() {
match event {
Event::PutPixels(rect, _) if rect == framebuffer_rect => break 'outer,
_ => ()
}
}
}
// Since VNC is fully client-driven, by this point the event thread is stuck
// waiting for the next message and the server is not sending us anything,
// so it's safe to switch to the new pixel format.
let set_pixel_format = protocol::C2S::SetPixelFormat(format);
debug!("-> {:?}", set_pixel_format);
try!(protocol::C2S::write_to(&set_pixel_format, &mut self.stream));
*self.format.lock().unwrap() = format;
Ok(())
}
#[doc(hidden)]
pub fn poke_qemu(&mut self) -> Result<()> {
let set_pixel_format = protocol::C2S::SetPixelFormat(*self.format.lock().unwrap());
debug!("-> {:?}", set_pixel_format);
try!(protocol::C2S::write_to(&set_pixel_format, &mut self.stream));
Ok(())
}
pub fn poll_event(&mut self) -> Option<Event> {
match self.events.try_recv() {
Err(TryRecvError::Empty) |
Err(TryRecvError::Disconnected) => None,
Ok(Event::Resize(width, height)) => {
self.size = (width, height);
Some(Event::Resize(width, height))
}
Ok(event) => Some(event)
}
}
pub fn poll_iter(&mut self) -> EventPollIterator {
EventPollIterator { client: self }
}
pub fn disconnect(self) -> Result<()> {
try!(self.stream.shutdown(Shutdown::Both));
Ok(())
}
}
pub struct EventPollIterator<'a> {
client: &'a mut Client
}
impl<'a> Iterator for EventPollIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Self::Item> { self.client.poll_event() }
}
|
use actix_web::{AsyncResponder, FutureResponse, HttpResponse, Json, State};
use futures::Future;
use super::super::model::user::{SigninUser, SignupUser};
use super::super::share::state::AppState;
pub fn signup(
(signup_user, state): (Json<SignupUser>, State<AppState>),
) -> FutureResponse<HttpResponse> {
state
.db
.send(SignupUser {
username: signup_user.username.clone(),
email: signup_user.email.clone(),
password: signup_user.password.clone(),
confirm_password: signup_user.confirm_password.clone(),
})
.from_err()
.and_then(|res| match res {
Ok(signup_msg) => Ok(HttpResponse::Ok().json(signup_msg)),
Err(_) => Ok(HttpResponse::InternalServerError().into()),
})
.responder()
}
pub fn signin(
(signin_user, state): (Json<SigninUser>, State<AppState>),
) -> FutureResponse<HttpResponse> {
state
.db
.send(SigninUser {
username: signin_user.username.clone(),
password: signin_user.password.clone(),
})
.from_err()
.and_then(|res| match res {
Ok(signin_msg) => Ok(HttpResponse::Ok().json(signin_msg)),
Err(_) => Ok(HttpResponse::InternalServerError().into()),
})
.responder()
}
|
#[doc = "Reader of register SECCFGR2"]
pub type R = crate::R<u32, super::SECCFGR2>;
#[doc = "Writer for register SECCFGR2"]
pub type W = crate::W<u32, super::SECCFGR2>;
#[doc = "Register SECCFGR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::SECCFGR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SEC32`"]
pub type SEC32_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC32`"]
pub struct SEC32_W<'a> {
w: &'a mut W,
}
impl<'a> SEC32_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `SEC33`"]
pub type SEC33_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC33`"]
pub struct SEC33_W<'a> {
w: &'a mut W,
}
impl<'a> SEC33_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `SEC34`"]
pub type SEC34_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC34`"]
pub struct SEC34_W<'a> {
w: &'a mut W,
}
impl<'a> SEC34_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `SEC35`"]
pub type SEC35_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC35`"]
pub struct SEC35_W<'a> {
w: &'a mut W,
}
impl<'a> SEC35_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `SEC36`"]
pub type SEC36_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC36`"]
pub struct SEC36_W<'a> {
w: &'a mut W,
}
impl<'a> SEC36_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `SEC37`"]
pub type SEC37_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC37`"]
pub struct SEC37_W<'a> {
w: &'a mut W,
}
impl<'a> SEC37_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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `SEC38`"]
pub type SEC38_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC38`"]
pub struct SEC38_W<'a> {
w: &'a mut W,
}
impl<'a> SEC38_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 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `SEC39`"]
pub type SEC39_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC39`"]
pub struct SEC39_W<'a> {
w: &'a mut W,
}
impl<'a> SEC39_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 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `SEC40`"]
pub type SEC40_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC40`"]
pub struct SEC40_W<'a> {
w: &'a mut W,
}
impl<'a> SEC40_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 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `SEC41`"]
pub type SEC41_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC41`"]
pub struct SEC41_W<'a> {
w: &'a mut W,
}
impl<'a> SEC41_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `SEC42`"]
pub type SEC42_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEC42`"]
pub struct SEC42_W<'a> {
w: &'a mut W,
}
impl<'a> SEC42_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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
impl R {
#[doc = "Bit 0 - SEC32"]
#[inline(always)]
pub fn sec32(&self) -> SEC32_R {
SEC32_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - SEC33"]
#[inline(always)]
pub fn sec33(&self) -> SEC33_R {
SEC33_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - SEC34"]
#[inline(always)]
pub fn sec34(&self) -> SEC34_R {
SEC34_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - SEC35"]
#[inline(always)]
pub fn sec35(&self) -> SEC35_R {
SEC35_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - SEC36"]
#[inline(always)]
pub fn sec36(&self) -> SEC36_R {
SEC36_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - SEC37"]
#[inline(always)]
pub fn sec37(&self) -> SEC37_R {
SEC37_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - SEC38"]
#[inline(always)]
pub fn sec38(&self) -> SEC38_R {
SEC38_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - SEC39"]
#[inline(always)]
pub fn sec39(&self) -> SEC39_R {
SEC39_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - SEC40"]
#[inline(always)]
pub fn sec40(&self) -> SEC40_R {
SEC40_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - SEC41"]
#[inline(always)]
pub fn sec41(&self) -> SEC41_R {
SEC41_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - SEC42"]
#[inline(always)]
pub fn sec42(&self) -> SEC42_R {
SEC42_R::new(((self.bits >> 10) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - SEC32"]
#[inline(always)]
pub fn sec32(&mut self) -> SEC32_W {
SEC32_W { w: self }
}
#[doc = "Bit 1 - SEC33"]
#[inline(always)]
pub fn sec33(&mut self) -> SEC33_W {
SEC33_W { w: self }
}
#[doc = "Bit 2 - SEC34"]
#[inline(always)]
pub fn sec34(&mut self) -> SEC34_W {
SEC34_W { w: self }
}
#[doc = "Bit 3 - SEC35"]
#[inline(always)]
pub fn sec35(&mut self) -> SEC35_W {
SEC35_W { w: self }
}
#[doc = "Bit 4 - SEC36"]
#[inline(always)]
pub fn sec36(&mut self) -> SEC36_W {
SEC36_W { w: self }
}
#[doc = "Bit 5 - SEC37"]
#[inline(always)]
pub fn sec37(&mut self) -> SEC37_W {
SEC37_W { w: self }
}
#[doc = "Bit 6 - SEC38"]
#[inline(always)]
pub fn sec38(&mut self) -> SEC38_W {
SEC38_W { w: self }
}
#[doc = "Bit 7 - SEC39"]
#[inline(always)]
pub fn sec39(&mut self) -> SEC39_W {
SEC39_W { w: self }
}
#[doc = "Bit 8 - SEC40"]
#[inline(always)]
pub fn sec40(&mut self) -> SEC40_W {
SEC40_W { w: self }
}
#[doc = "Bit 9 - SEC41"]
#[inline(always)]
pub fn sec41(&mut self) -> SEC41_W {
SEC41_W { w: self }
}
#[doc = "Bit 10 - SEC42"]
#[inline(always)]
pub fn sec42(&mut self) -> SEC42_W {
SEC42_W { w: self }
}
}
|
use test_interop::{
Windows::Foundation::Collections::StringMap,
Windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED},
Windows::Win32::System::WinRT::RoActivateInstance,
};
use windows::core::{Interface, Result};
// Calling RoActivateInstance is a useful interop test because it is a function defined by Win32 metadata
// but refers to three types that are intrinsic to WinRT and thus directly mapped to type in the Windows
// crate. Calling RoActivateInstance in production code is discouraged. Instead, let the Windows crate
// activate WinRT types directly as it can do so far more efficiently.
#[test]
fn test() -> Result<()> {
unsafe { CoInitializeEx(core::ptr::null_mut(), COINIT_MULTITHREADED)? };
let instance = unsafe { RoActivateInstance("Windows.Foundation.Collections.StringMap")? };
let map = instance.cast::<StringMap>()?;
map.Insert("hello", "world")?;
assert_eq!(map.Lookup("hello")?, "world");
Ok(())
}
|
use amiquip::{
Auth, Connection, ConnectionOptions, ConnectionTuning, ExchangeDeclareOptions, ExchangeType,
FieldTable, Publish, QueueDeclareOptions,
};
use log::{info, LevelFilter};
use mio::net::TcpStream;
use native_tls::{Certificate, Identity, TlsConnector};
use simple_logger::SimpleLogger;
use std::{fs, path::Path};
// certificate 'Common Name' was set on cration, do not touch this!
const C_CA_CN: &str = "rabbit_tls_srv";
const C_RABBIT_IP: &str = "127.0.0.1";
const C_RABBIT_PORT: u16 = 5671;
const C_CERT_DIR: &str = r"certificate";
// Rabbit configuration struct
#[derive(Debug)]
struct Rabbit<P: AsRef<Path>> {
username: String,
password: String,
host: String,
port: u16,
client_cert: P,
client_p12: P,
}
impl<P: AsRef<Path>> Rabbit<P> {
fn new(
username: &str,
password: &str,
host: &str,
port: u16,
client_cert: P,
client_p12: P,
) -> Self {
Self {
username: username.to_owned(),
password: password.to_owned(),
host: host.to_owned(),
port,
client_cert,
client_p12,
}
}
// get connection options
fn get_conn_options(&self) -> ConnectionOptions<Auth> {
ConnectionOptions::default().auth(Auth::Plain {
username: self.username.clone(),
password: self.password.clone(),
})
}
// get TLS connector configurad with needed certifications
fn get_connector(&self) -> TlsConnector {
let cert_byte_vec = fs::read(&self.client_cert).expect("failed to load cert");
let cert = Certificate::from_pem(&cert_byte_vec).expect("failed to parse cert");
let identity_byte_vec = fs::read(&self.client_p12).expect("failed to load client_p12");
let identity =
Identity::from_pkcs12(&identity_byte_vec, "").expect("failed to parse client_p12");
TlsConnector::builder()
.identity(identity)
.add_root_certificate(cert)
.build()
.unwrap()
}
// open tcp stream on the rabbit port
fn get_stream(&self) -> TcpStream {
TcpStream::connect(&format!("{}:{}", self.host, self.port).parse().unwrap()).unwrap()
}
}
fn client_demo(index: usize) {
let rabbit = Rabbit::new(
"guest",
"guest",
C_RABBIT_IP,
C_RABBIT_PORT,
Path::new(C_CERT_DIR).join(format!("client_{}_certificate.pem", index)),
Path::new(C_CERT_DIR).join(format!("client_{}_key.p12", index)),
);
// client-side TLS connection
let connector = rabbit.get_connector();
let stream = rabbit.get_stream();
info!("Connected to TCP stream");
// Open connection.
let mut connection = Connection::open_tls_stream::<Auth, TlsConnector, TcpStream>(
connector,
C_CA_CN,
stream,
rabbit.get_conn_options(),
ConnectionTuning::default(),
)
.expect("Rabbit Connection failed");
info!("TLS connection successful");
// Open a channel - None says let the library choose the channel ID.
let channel = connection
.open_channel(None)
.expect("Opening channel failed");
// Get a handle to the direct exchange on our channel.
let exchange = channel
.exchange_declare(
ExchangeType::Direct,
"tls_exchange".to_owned(),
ExchangeDeclareOptions::default(),
)
.expect("Failed declaring exchange");
channel
.queue_declare("tls_queue", QueueDeclareOptions::default())
.expect("Failed declaring queue");
channel
.queue_bind("tls_queue", "tls_exchange", "hello", FieldTable::default())
.expect("Failed binding queue to exchange");
// publish 10 messages
for _ in 0..10 {
exchange
.publish(Publish::new(
format!("hello there from client {}", index).as_bytes(),
"hello",
))
.expect("Publish had failed");
}
info!("All messages sent seccessfuly");
}
fn main() {
SimpleLogger::new()
.with_level(LevelFilter::Info)
.init()
.unwrap();
client_demo(1);
client_demo(2);
client_demo(3);
}
|
pub(crate) trait Converts<A, B> {
fn convert(&self, a: A) -> B;
}
|
pub struct Line {
pub xbeg: f64,
pub ybeg: f64,
pub xend: f64,
pub yend: f64,
// If finite = false, line ends at (xend, yend)
// Otherwise, line goes past (xend, yend)
pub finite: bool
} |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Perception_Spatial_Preview")]
pub mod Preview;
#[cfg(feature = "Perception_Spatial_Surfaces")]
pub mod Surfaces;
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchor(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchor {
type Vtable = ISpatialAnchor_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0529e5ce_1d34_3702_bcec_eabff578a869);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchor_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchor2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchor2 {
type Vtable = ISpatialAnchor2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed17c908_a695_4cf6_92fd_97263ba71047);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchor2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchorExportSufficiency(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorExportSufficiency {
type Vtable = ISpatialAnchorExportSufficiency_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x77c25b2b_3409_4088_b91b_fdfd05d1648f);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorExportSufficiency_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchorExporter(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorExporter {
type Vtable = ISpatialAnchorExporter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a2a4338_24fb_4269_89c5_88304aeef20f);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorExporter_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, anchor: ::windows::core::RawPtr, purpose: SpatialAnchorExportPurpose, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, anchor: ::windows::core::RawPtr, purpose: SpatialAnchorExportPurpose, stream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchorExporterStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorExporterStatics {
type Vtable = ISpatialAnchorExporterStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xed2507b8_2475_439c_85ff_7fed341fdc88);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorExporterStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(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 ISpatialAnchorManagerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorManagerStatics {
type Vtable = ISpatialAnchorManagerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x88e30eab_f3b7_420b_b086_8a80c07d910d);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorManagerStatics_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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchorRawCoordinateSystemAdjustedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorRawCoordinateSystemAdjustedEventArgs {
type Vtable = ISpatialAnchorRawCoordinateSystemAdjustedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa1e81eb8_56c7_3117_a2e4_81e0fcf28e00);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorRawCoordinateSystemAdjustedEventArgs_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_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Matrix4x4) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchorStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorStatics {
type Vtable = ISpatialAnchorStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa9928642_0174_311c_ae79_0e5107669f16);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorStatics_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, coordinatesystem: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, position: super::super::Foundation::Numerics::Vector3, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, position: super::super::Foundation::Numerics::Vector3, orientation: super::super::Foundation::Numerics::Quaternion, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchorStore(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorStore {
type Vtable = ISpatialAnchorStore_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0bc3636_486a_3cb0_9e6f_1245165c4db6);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorStore_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, anchor: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialAnchorTransferManagerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialAnchorTransferManagerStatics {
type Vtable = ISpatialAnchorTransferManagerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x03bbf9b9_12d8_4bce_8835_c5df3ac0adab);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialAnchorTransferManagerStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, stream: ::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", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, anchors: ::windows::core::RawPtr, stream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams")))] 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 ISpatialBoundingVolume(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialBoundingVolume {
type Vtable = ISpatialBoundingVolume_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb2065da_68c3_33df_b7af_4c787207999c);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialBoundingVolume_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialBoundingVolumeStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialBoundingVolumeStatics {
type Vtable = ISpatialBoundingVolumeStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x05889117_b3e1_36d8_b017_566181a5b196);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialBoundingVolumeStatics_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_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, r#box: SpatialBoundingBox, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, r#box: SpatialBoundingOrientedBox, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, sphere: SpatialBoundingSphere, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, frustum: SpatialBoundingFrustum, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialCoordinateSystem(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialCoordinateSystem {
type Vtable = ISpatialCoordinateSystem_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x69ebca4b_60a3_3586_a653_59a7bd676d07);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialCoordinateSystem_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, target: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialEntity(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntity {
type Vtable = ISpatialEntity_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x166de955_e1eb_454c_ba08_e6c0668ddc65);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntity_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(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 ISpatialEntityAddedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntityAddedEventArgs {
type Vtable = ISpatialEntityAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa397f49b_156a_4707_ac2c_d31d570ed399);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntityAddedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialEntityFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntityFactory {
type Vtable = ISpatialEntityFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe1f1e325_349f_4225_a2f3_4b01c15fe056);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntityFactory_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, spatialanchor: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, spatialanchor: ::windows::core::RawPtr, propertyset: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialEntityRemovedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntityRemovedEventArgs {
type Vtable = ISpatialEntityRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x91741800_536d_4e9f_abf6_415b5444d651);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntityRemovedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialEntityStore(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntityStore {
type Vtable = ISpatialEntityStore_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x329788ba_e513_4f06_889d_1be30ecf43e6);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntityStore_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, entity: ::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, entity: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialEntityStoreStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntityStoreStatics {
type Vtable = ISpatialEntityStoreStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6b4b389e_7c50_4e92_8a62_4d1d4b7ccd3e);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntityStoreStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "System_RemoteSystems")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, session: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "System_RemoteSystems"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialEntityUpdatedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntityUpdatedEventArgs {
type Vtable = ISpatialEntityUpdatedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe5671766_627b_43cb_a49f_b3be6d47deed);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntityUpdatedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialEntityWatcher(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialEntityWatcher {
type Vtable = ISpatialEntityWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb3b85fa0_6d5e_4bbc_805d_5fe5b9ba1959);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialEntityWatcher_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 SpatialEntityWatcherStatus) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialLocation(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialLocation {
type Vtable = ISpatialLocation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1d81d29d_24a1_37d5_8fa1_39b4f9ad67e2);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialLocation_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_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Quaternion) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Quaternion) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Quaternion) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialLocation2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialLocation2 {
type Vtable = ISpatialLocation2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x117f2416_38a7_4a18_b404_ab8fabe1d78b);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialLocation2_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_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialLocator(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialLocator {
type Vtable = ISpatialLocator_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf6478925_9e0c_3bb6_997e_b64ecca24cf4);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialLocator_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 SpatialLocatability) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, timestamp: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, relativeposition: super::super::Foundation::Numerics::Vector3, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, relativeposition: super::super::Foundation::Numerics::Vector3, relativeorientation: super::super::Foundation::Numerics::Quaternion, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, relativeposition: super::super::Foundation::Numerics::Vector3, relativeorientation: super::super::Foundation::Numerics::Quaternion, relativeheadinginradians: f64, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, relativeposition: super::super::Foundation::Numerics::Vector3, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, relativeposition: super::super::Foundation::Numerics::Vector3, relativeorientation: super::super::Foundation::Numerics::Quaternion, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, relativeposition: super::super::Foundation::Numerics::Vector3, relativeorientation: super::super::Foundation::Numerics::Quaternion, relativeheadinginradians: f64, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialLocatorAttachedFrameOfReference(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialLocatorAttachedFrameOfReference {
type Vtable = ISpatialLocatorAttachedFrameOfReference_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe1774ef6_1f4f_499c_9625_ef5e6ed7a048);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialLocatorAttachedFrameOfReference_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_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::Numerics::Quaternion) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::Numerics::Quaternion) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, headingoffsetinradians: f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, timestamp: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, timestamp: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialLocatorPositionalTrackingDeactivatingEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialLocatorPositionalTrackingDeactivatingEventArgs {
type Vtable = ISpatialLocatorPositionalTrackingDeactivatingEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb8a84063_e3f4_368b_9061_9ea9d1d6cc16);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialLocatorPositionalTrackingDeactivatingEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialLocatorStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialLocatorStatics {
type Vtable = ISpatialLocatorStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb76e3340_a7c2_361b_bb82_56e93b89b1bb);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialLocatorStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialStageFrameOfReference(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialStageFrameOfReference {
type Vtable = ISpatialStageFrameOfReference_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a8a3464_ad0d_4590_ab86_33062b674926);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialStageFrameOfReference_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut SpatialMovementRange) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut SpatialLookDirectionRange) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, locator: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Numerics")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, coordinatesystem: ::windows::core::RawPtr, result_size__: *mut u32, result__: *mut *mut super::super::Foundation::Numerics::Vector3) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Numerics"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialStageFrameOfReferenceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialStageFrameOfReferenceStatics {
type Vtable = ISpatialStageFrameOfReferenceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf78d5c4d_a0a4_499c_8d91_a8c965d40654);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialStageFrameOfReferenceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISpatialStationaryFrameOfReference(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISpatialStationaryFrameOfReference {
type Vtable = ISpatialStationaryFrameOfReference_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09dbccb9_bcf8_3e7f_be7e_7edccbb178a8);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISpatialStationaryFrameOfReference_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialAnchor(pub ::windows::core::IInspectable);
impl SpatialAnchor {
pub fn CoordinateSystem(&self) -> ::windows::core::Result<SpatialCoordinateSystem> {
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::<SpatialCoordinateSystem>(result__)
}
}
pub fn RawCoordinateSystem(&self) -> ::windows::core::Result<SpatialCoordinateSystem> {
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::<SpatialCoordinateSystem>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RawCoordinateSystemAdjusted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SpatialAnchor, SpatialAnchorRawCoordinateSystemAdjustedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveRawCoordinateSystemAdjusted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() }
}
pub fn TryCreateRelativeTo<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>>(coordinatesystem: Param0) -> ::windows::core::Result<SpatialAnchor> {
Self::ISpatialAnchorStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), &mut result__).from_abi::<SpatialAnchor>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn TryCreateWithPositionRelativeTo<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>>(coordinatesystem: Param0, position: Param1) -> ::windows::core::Result<SpatialAnchor> {
Self::ISpatialAnchorStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), position.into_param().abi(), &mut result__).from_abi::<SpatialAnchor>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn TryCreateWithPositionAndOrientationRelativeTo<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Quaternion>>(coordinatesystem: Param0, position: Param1, orientation: Param2) -> ::windows::core::Result<SpatialAnchor> {
Self::ISpatialAnchorStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), position.into_param().abi(), orientation.into_param().abi(), &mut result__).from_abi::<SpatialAnchor>(result__)
})
}
pub fn RemovedByUser(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ISpatialAnchor2>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn ISpatialAnchorStatics<R, F: FnOnce(&ISpatialAnchorStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialAnchor, ISpatialAnchorStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialAnchor {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialAnchor;{0529e5ce-1d34-3702-bcec-eabff578a869})");
}
unsafe impl ::windows::core::Interface for SpatialAnchor {
type Vtable = ISpatialAnchor_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0529e5ce_1d34_3702_bcec_eabff578a869);
}
impl ::windows::core::RuntimeName for SpatialAnchor {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialAnchor";
}
impl ::core::convert::From<SpatialAnchor> for ::windows::core::IUnknown {
fn from(value: SpatialAnchor) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialAnchor> for ::windows::core::IUnknown {
fn from(value: &SpatialAnchor) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialAnchor {
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 SpatialAnchor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialAnchor> for ::windows::core::IInspectable {
fn from(value: SpatialAnchor) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialAnchor> for ::windows::core::IInspectable {
fn from(value: &SpatialAnchor) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialAnchor {
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 SpatialAnchor {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialAnchor {}
unsafe impl ::core::marker::Sync for SpatialAnchor {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SpatialAnchorExportPurpose(pub i32);
impl SpatialAnchorExportPurpose {
pub const Relocalization: SpatialAnchorExportPurpose = SpatialAnchorExportPurpose(0i32);
pub const Sharing: SpatialAnchorExportPurpose = SpatialAnchorExportPurpose(1i32);
}
impl ::core::convert::From<i32> for SpatialAnchorExportPurpose {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SpatialAnchorExportPurpose {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SpatialAnchorExportPurpose {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Perception.Spatial.SpatialAnchorExportPurpose;i4)");
}
impl ::windows::core::DefaultType for SpatialAnchorExportPurpose {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialAnchorExportSufficiency(pub ::windows::core::IInspectable);
impl SpatialAnchorExportSufficiency {
pub fn IsMinimallySufficient(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SufficiencyLevel(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn RecommendedSufficiencyLevel(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialAnchorExportSufficiency {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialAnchorExportSufficiency;{77c25b2b-3409-4088-b91b-fdfd05d1648f})");
}
unsafe impl ::windows::core::Interface for SpatialAnchorExportSufficiency {
type Vtable = ISpatialAnchorExportSufficiency_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x77c25b2b_3409_4088_b91b_fdfd05d1648f);
}
impl ::windows::core::RuntimeName for SpatialAnchorExportSufficiency {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialAnchorExportSufficiency";
}
impl ::core::convert::From<SpatialAnchorExportSufficiency> for ::windows::core::IUnknown {
fn from(value: SpatialAnchorExportSufficiency) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialAnchorExportSufficiency> for ::windows::core::IUnknown {
fn from(value: &SpatialAnchorExportSufficiency) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialAnchorExportSufficiency {
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 SpatialAnchorExportSufficiency {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialAnchorExportSufficiency> for ::windows::core::IInspectable {
fn from(value: SpatialAnchorExportSufficiency) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialAnchorExportSufficiency> for ::windows::core::IInspectable {
fn from(value: &SpatialAnchorExportSufficiency) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialAnchorExportSufficiency {
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 SpatialAnchorExportSufficiency {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialAnchorExportSufficiency {}
unsafe impl ::core::marker::Sync for SpatialAnchorExportSufficiency {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialAnchorExporter(pub ::windows::core::IInspectable);
impl SpatialAnchorExporter {
#[cfg(feature = "Foundation")]
pub fn GetAnchorExportSufficiencyAsync<'a, Param0: ::windows::core::IntoParam<'a, SpatialAnchor>>(&self, anchor: Param0, purpose: SpatialAnchorExportPurpose) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<SpatialAnchorExportSufficiency>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), anchor.into_param().abi(), purpose, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<SpatialAnchorExportSufficiency>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn TryExportAnchorAsync<'a, Param0: ::windows::core::IntoParam<'a, SpatialAnchor>, Param2: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(&self, anchor: Param0, purpose: SpatialAnchorExportPurpose, stream: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), anchor.into_param().abi(), purpose, stream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
pub fn GetDefault() -> ::windows::core::Result<SpatialAnchorExporter> {
Self::ISpatialAnchorExporterStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialAnchorExporter>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn RequestAccessAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<SpatialPerceptionAccessStatus>> {
Self::ISpatialAnchorExporterStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<SpatialPerceptionAccessStatus>>(result__)
})
}
pub fn ISpatialAnchorExporterStatics<R, F: FnOnce(&ISpatialAnchorExporterStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialAnchorExporter, ISpatialAnchorExporterStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialAnchorExporter {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialAnchorExporter;{9a2a4338-24fb-4269-89c5-88304aeef20f})");
}
unsafe impl ::windows::core::Interface for SpatialAnchorExporter {
type Vtable = ISpatialAnchorExporter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a2a4338_24fb_4269_89c5_88304aeef20f);
}
impl ::windows::core::RuntimeName for SpatialAnchorExporter {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialAnchorExporter";
}
impl ::core::convert::From<SpatialAnchorExporter> for ::windows::core::IUnknown {
fn from(value: SpatialAnchorExporter) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialAnchorExporter> for ::windows::core::IUnknown {
fn from(value: &SpatialAnchorExporter) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialAnchorExporter {
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 SpatialAnchorExporter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialAnchorExporter> for ::windows::core::IInspectable {
fn from(value: SpatialAnchorExporter) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialAnchorExporter> for ::windows::core::IInspectable {
fn from(value: &SpatialAnchorExporter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialAnchorExporter {
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 SpatialAnchorExporter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialAnchorExporter {}
unsafe impl ::core::marker::Sync for SpatialAnchorExporter {}
pub struct SpatialAnchorManager {}
impl SpatialAnchorManager {
#[cfg(feature = "Foundation")]
pub fn RequestStoreAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<SpatialAnchorStore>> {
Self::ISpatialAnchorManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<SpatialAnchorStore>>(result__)
})
}
pub fn ISpatialAnchorManagerStatics<R, F: FnOnce(&ISpatialAnchorManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialAnchorManager, ISpatialAnchorManagerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for SpatialAnchorManager {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialAnchorManager";
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialAnchorRawCoordinateSystemAdjustedEventArgs(pub ::windows::core::IInspectable);
impl SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
#[cfg(feature = "Foundation_Numerics")]
pub fn OldRawCoordinateSystemToNewRawCoordinateSystemTransform(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Matrix4x4> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Matrix4x4 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Matrix4x4>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialAnchorRawCoordinateSystemAdjustedEventArgs;{a1e81eb8-56c7-3117-a2e4-81e0fcf28e00})");
}
unsafe impl ::windows::core::Interface for SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
type Vtable = ISpatialAnchorRawCoordinateSystemAdjustedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa1e81eb8_56c7_3117_a2e4_81e0fcf28e00);
}
impl ::windows::core::RuntimeName for SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialAnchorRawCoordinateSystemAdjustedEventArgs";
}
impl ::core::convert::From<SpatialAnchorRawCoordinateSystemAdjustedEventArgs> for ::windows::core::IUnknown {
fn from(value: SpatialAnchorRawCoordinateSystemAdjustedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialAnchorRawCoordinateSystemAdjustedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SpatialAnchorRawCoordinateSystemAdjustedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
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 SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialAnchorRawCoordinateSystemAdjustedEventArgs> for ::windows::core::IInspectable {
fn from(value: SpatialAnchorRawCoordinateSystemAdjustedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialAnchorRawCoordinateSystemAdjustedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SpatialAnchorRawCoordinateSystemAdjustedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
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 SpatialAnchorRawCoordinateSystemAdjustedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialAnchorRawCoordinateSystemAdjustedEventArgs {}
unsafe impl ::core::marker::Sync for SpatialAnchorRawCoordinateSystemAdjustedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialAnchorStore(pub ::windows::core::IInspectable);
impl SpatialAnchorStore {
#[cfg(feature = "Foundation_Collections")]
pub fn GetAllSavedAnchors(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, SpatialAnchor>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, SpatialAnchor>>(result__)
}
}
pub fn TrySave<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, SpatialAnchor>>(&self, id: Param0, anchor: Param1) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), id.into_param().abi(), anchor.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, id: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), id.into_param().abi()).ok() }
}
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialAnchorStore {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialAnchorStore;{b0bc3636-486a-3cb0-9e6f-1245165c4db6})");
}
unsafe impl ::windows::core::Interface for SpatialAnchorStore {
type Vtable = ISpatialAnchorStore_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0bc3636_486a_3cb0_9e6f_1245165c4db6);
}
impl ::windows::core::RuntimeName for SpatialAnchorStore {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialAnchorStore";
}
impl ::core::convert::From<SpatialAnchorStore> for ::windows::core::IUnknown {
fn from(value: SpatialAnchorStore) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialAnchorStore> for ::windows::core::IUnknown {
fn from(value: &SpatialAnchorStore) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialAnchorStore {
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 SpatialAnchorStore {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialAnchorStore> for ::windows::core::IInspectable {
fn from(value: SpatialAnchorStore) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialAnchorStore> for ::windows::core::IInspectable {
fn from(value: &SpatialAnchorStore) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialAnchorStore {
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 SpatialAnchorStore {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialAnchorStore {}
unsafe impl ::core::marker::Sync for SpatialAnchorStore {}
pub struct SpatialAnchorTransferManager {}
impl SpatialAnchorTransferManager {
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))]
pub fn TryImportAnchorsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IInputStream>>(stream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, SpatialAnchor>>> {
Self::ISpatialAnchorTransferManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), stream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, SpatialAnchor>>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections", feature = "Storage_Streams"))]
pub fn TryExportAnchorsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::HSTRING, SpatialAnchor>>>, Param1: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IOutputStream>>(anchors: Param0, stream: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
Self::ISpatialAnchorTransferManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), anchors.into_param().abi(), stream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RequestAccessAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<SpatialPerceptionAccessStatus>> {
Self::ISpatialAnchorTransferManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<SpatialPerceptionAccessStatus>>(result__)
})
}
pub fn ISpatialAnchorTransferManagerStatics<R, F: FnOnce(&ISpatialAnchorTransferManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialAnchorTransferManager, ISpatialAnchorTransferManagerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for SpatialAnchorTransferManager {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialAnchorTransferManager";
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Foundation_Numerics")]
pub struct SpatialBoundingBox {
pub Center: super::super::Foundation::Numerics::Vector3,
pub Extents: super::super::Foundation::Numerics::Vector3,
}
#[cfg(feature = "Foundation_Numerics")]
impl SpatialBoundingBox {}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::default::Default for SpatialBoundingBox {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::fmt::Debug for SpatialBoundingBox {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("SpatialBoundingBox").field("Center", &self.Center).field("Extents", &self.Extents).finish()
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::PartialEq for SpatialBoundingBox {
fn eq(&self, other: &Self) -> bool {
self.Center == other.Center && self.Extents == other.Extents
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::Eq for SpatialBoundingBox {}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::Abi for SpatialBoundingBox {
type Abi = Self;
}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::RuntimeType for SpatialBoundingBox {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Perception.Spatial.SpatialBoundingBox;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4))");
}
#[cfg(feature = "Foundation_Numerics")]
impl ::windows::core::DefaultType for SpatialBoundingBox {
type DefaultType = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Foundation_Numerics")]
pub struct SpatialBoundingFrustum {
pub Near: super::super::Foundation::Numerics::Plane,
pub Far: super::super::Foundation::Numerics::Plane,
pub Right: super::super::Foundation::Numerics::Plane,
pub Left: super::super::Foundation::Numerics::Plane,
pub Top: super::super::Foundation::Numerics::Plane,
pub Bottom: super::super::Foundation::Numerics::Plane,
}
#[cfg(feature = "Foundation_Numerics")]
impl SpatialBoundingFrustum {}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::default::Default for SpatialBoundingFrustum {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::fmt::Debug for SpatialBoundingFrustum {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("SpatialBoundingFrustum").field("Near", &self.Near).field("Far", &self.Far).field("Right", &self.Right).field("Left", &self.Left).field("Top", &self.Top).field("Bottom", &self.Bottom).finish()
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::PartialEq for SpatialBoundingFrustum {
fn eq(&self, other: &Self) -> bool {
self.Near == other.Near && self.Far == other.Far && self.Right == other.Right && self.Left == other.Left && self.Top == other.Top && self.Bottom == other.Bottom
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::Eq for SpatialBoundingFrustum {}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::Abi for SpatialBoundingFrustum {
type Abi = Self;
}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::RuntimeType for SpatialBoundingFrustum {
const SIGNATURE : :: windows :: core :: ConstBuffer = :: windows :: core :: ConstBuffer :: from_slice ( b"struct(Windows.Perception.Spatial.SpatialBoundingFrustum;struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4);struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4);struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4);struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4);struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4);struct(Windows.Foundation.Numerics.Plane;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4))" ) ;
}
#[cfg(feature = "Foundation_Numerics")]
impl ::windows::core::DefaultType for SpatialBoundingFrustum {
type DefaultType = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Foundation_Numerics")]
pub struct SpatialBoundingOrientedBox {
pub Center: super::super::Foundation::Numerics::Vector3,
pub Extents: super::super::Foundation::Numerics::Vector3,
pub Orientation: super::super::Foundation::Numerics::Quaternion,
}
#[cfg(feature = "Foundation_Numerics")]
impl SpatialBoundingOrientedBox {}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::default::Default for SpatialBoundingOrientedBox {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::fmt::Debug for SpatialBoundingOrientedBox {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("SpatialBoundingOrientedBox").field("Center", &self.Center).field("Extents", &self.Extents).field("Orientation", &self.Orientation).finish()
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::PartialEq for SpatialBoundingOrientedBox {
fn eq(&self, other: &Self) -> bool {
self.Center == other.Center && self.Extents == other.Extents && self.Orientation == other.Orientation
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::Eq for SpatialBoundingOrientedBox {}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::Abi for SpatialBoundingOrientedBox {
type Abi = Self;
}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::RuntimeType for SpatialBoundingOrientedBox {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Perception.Spatial.SpatialBoundingOrientedBox;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);struct(Windows.Foundation.Numerics.Quaternion;f4;f4;f4;f4))");
}
#[cfg(feature = "Foundation_Numerics")]
impl ::windows::core::DefaultType for SpatialBoundingOrientedBox {
type DefaultType = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Foundation_Numerics")]
pub struct SpatialBoundingSphere {
pub Center: super::super::Foundation::Numerics::Vector3,
pub Radius: f32,
}
#[cfg(feature = "Foundation_Numerics")]
impl SpatialBoundingSphere {}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::default::Default for SpatialBoundingSphere {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::fmt::Debug for SpatialBoundingSphere {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("SpatialBoundingSphere").field("Center", &self.Center).field("Radius", &self.Radius).finish()
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::PartialEq for SpatialBoundingSphere {
fn eq(&self, other: &Self) -> bool {
self.Center == other.Center && self.Radius == other.Radius
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::Eq for SpatialBoundingSphere {}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::Abi for SpatialBoundingSphere {
type Abi = Self;
}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::RuntimeType for SpatialBoundingSphere {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Perception.Spatial.SpatialBoundingSphere;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);f4)");
}
#[cfg(feature = "Foundation_Numerics")]
impl ::windows::core::DefaultType for SpatialBoundingSphere {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialBoundingVolume(pub ::windows::core::IInspectable);
impl SpatialBoundingVolume {
#[cfg(feature = "Foundation_Numerics")]
pub fn FromBox<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, SpatialBoundingBox>>(coordinatesystem: Param0, r#box: Param1) -> ::windows::core::Result<SpatialBoundingVolume> {
Self::ISpatialBoundingVolumeStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), r#box.into_param().abi(), &mut result__).from_abi::<SpatialBoundingVolume>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn FromOrientedBox<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, SpatialBoundingOrientedBox>>(coordinatesystem: Param0, r#box: Param1) -> ::windows::core::Result<SpatialBoundingVolume> {
Self::ISpatialBoundingVolumeStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), r#box.into_param().abi(), &mut result__).from_abi::<SpatialBoundingVolume>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn FromSphere<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, SpatialBoundingSphere>>(coordinatesystem: Param0, sphere: Param1) -> ::windows::core::Result<SpatialBoundingVolume> {
Self::ISpatialBoundingVolumeStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), sphere.into_param().abi(), &mut result__).from_abi::<SpatialBoundingVolume>(result__)
})
}
#[cfg(feature = "Foundation_Numerics")]
pub fn FromFrustum<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>, Param1: ::windows::core::IntoParam<'a, SpatialBoundingFrustum>>(coordinatesystem: Param0, frustum: Param1) -> ::windows::core::Result<SpatialBoundingVolume> {
Self::ISpatialBoundingVolumeStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), frustum.into_param().abi(), &mut result__).from_abi::<SpatialBoundingVolume>(result__)
})
}
pub fn ISpatialBoundingVolumeStatics<R, F: FnOnce(&ISpatialBoundingVolumeStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialBoundingVolume, ISpatialBoundingVolumeStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialBoundingVolume {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialBoundingVolume;{fb2065da-68c3-33df-b7af-4c787207999c})");
}
unsafe impl ::windows::core::Interface for SpatialBoundingVolume {
type Vtable = ISpatialBoundingVolume_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb2065da_68c3_33df_b7af_4c787207999c);
}
impl ::windows::core::RuntimeName for SpatialBoundingVolume {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialBoundingVolume";
}
impl ::core::convert::From<SpatialBoundingVolume> for ::windows::core::IUnknown {
fn from(value: SpatialBoundingVolume) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialBoundingVolume> for ::windows::core::IUnknown {
fn from(value: &SpatialBoundingVolume) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialBoundingVolume {
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 SpatialBoundingVolume {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialBoundingVolume> for ::windows::core::IInspectable {
fn from(value: SpatialBoundingVolume) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialBoundingVolume> for ::windows::core::IInspectable {
fn from(value: &SpatialBoundingVolume) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialBoundingVolume {
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 SpatialBoundingVolume {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialBoundingVolume {}
unsafe impl ::core::marker::Sync for SpatialBoundingVolume {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialCoordinateSystem(pub ::windows::core::IInspectable);
impl SpatialCoordinateSystem {
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics"))]
pub fn TryGetTransformTo<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>>(&self, target: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::Numerics::Matrix4x4>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), target.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::Numerics::Matrix4x4>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialCoordinateSystem {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialCoordinateSystem;{69ebca4b-60a3-3586-a653-59a7bd676d07})");
}
unsafe impl ::windows::core::Interface for SpatialCoordinateSystem {
type Vtable = ISpatialCoordinateSystem_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x69ebca4b_60a3_3586_a653_59a7bd676d07);
}
impl ::windows::core::RuntimeName for SpatialCoordinateSystem {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialCoordinateSystem";
}
impl ::core::convert::From<SpatialCoordinateSystem> for ::windows::core::IUnknown {
fn from(value: SpatialCoordinateSystem) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialCoordinateSystem> for ::windows::core::IUnknown {
fn from(value: &SpatialCoordinateSystem) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialCoordinateSystem {
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 SpatialCoordinateSystem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialCoordinateSystem> for ::windows::core::IInspectable {
fn from(value: SpatialCoordinateSystem) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialCoordinateSystem> for ::windows::core::IInspectable {
fn from(value: &SpatialCoordinateSystem) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialCoordinateSystem {
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 SpatialCoordinateSystem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialCoordinateSystem {}
unsafe impl ::core::marker::Sync for SpatialCoordinateSystem {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialEntity(pub ::windows::core::IInspectable);
impl SpatialEntity {
pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Anchor(&self) -> ::windows::core::Result<SpatialAnchor> {
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::<SpatialAnchor>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::ValueSet> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::ValueSet>(result__)
}
}
pub fn CreateWithSpatialAnchor<'a, Param0: ::windows::core::IntoParam<'a, SpatialAnchor>>(spatialanchor: Param0) -> ::windows::core::Result<SpatialEntity> {
Self::ISpatialEntityFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), spatialanchor.into_param().abi(), &mut result__).from_abi::<SpatialEntity>(result__)
})
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreateWithSpatialAnchorAndProperties<'a, Param0: ::windows::core::IntoParam<'a, SpatialAnchor>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::ValueSet>>(spatialanchor: Param0, propertyset: Param1) -> ::windows::core::Result<SpatialEntity> {
Self::ISpatialEntityFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), spatialanchor.into_param().abi(), propertyset.into_param().abi(), &mut result__).from_abi::<SpatialEntity>(result__)
})
}
pub fn ISpatialEntityFactory<R, F: FnOnce(&ISpatialEntityFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialEntity, ISpatialEntityFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialEntity {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialEntity;{166de955-e1eb-454c-ba08-e6c0668ddc65})");
}
unsafe impl ::windows::core::Interface for SpatialEntity {
type Vtable = ISpatialEntity_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x166de955_e1eb_454c_ba08_e6c0668ddc65);
}
impl ::windows::core::RuntimeName for SpatialEntity {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialEntity";
}
impl ::core::convert::From<SpatialEntity> for ::windows::core::IUnknown {
fn from(value: SpatialEntity) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialEntity> for ::windows::core::IUnknown {
fn from(value: &SpatialEntity) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialEntity {
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 SpatialEntity {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialEntity> for ::windows::core::IInspectable {
fn from(value: SpatialEntity) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialEntity> for ::windows::core::IInspectable {
fn from(value: &SpatialEntity) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialEntity {
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 SpatialEntity {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialEntity {}
unsafe impl ::core::marker::Sync for SpatialEntity {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialEntityAddedEventArgs(pub ::windows::core::IInspectable);
impl SpatialEntityAddedEventArgs {
pub fn Entity(&self) -> ::windows::core::Result<SpatialEntity> {
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::<SpatialEntity>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialEntityAddedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialEntityAddedEventArgs;{a397f49b-156a-4707-ac2c-d31d570ed399})");
}
unsafe impl ::windows::core::Interface for SpatialEntityAddedEventArgs {
type Vtable = ISpatialEntityAddedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa397f49b_156a_4707_ac2c_d31d570ed399);
}
impl ::windows::core::RuntimeName for SpatialEntityAddedEventArgs {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialEntityAddedEventArgs";
}
impl ::core::convert::From<SpatialEntityAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: SpatialEntityAddedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialEntityAddedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SpatialEntityAddedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialEntityAddedEventArgs {
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 SpatialEntityAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialEntityAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: SpatialEntityAddedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialEntityAddedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SpatialEntityAddedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialEntityAddedEventArgs {
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 SpatialEntityAddedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialEntityAddedEventArgs {}
unsafe impl ::core::marker::Sync for SpatialEntityAddedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialEntityRemovedEventArgs(pub ::windows::core::IInspectable);
impl SpatialEntityRemovedEventArgs {
pub fn Entity(&self) -> ::windows::core::Result<SpatialEntity> {
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::<SpatialEntity>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialEntityRemovedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialEntityRemovedEventArgs;{91741800-536d-4e9f-abf6-415b5444d651})");
}
unsafe impl ::windows::core::Interface for SpatialEntityRemovedEventArgs {
type Vtable = ISpatialEntityRemovedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x91741800_536d_4e9f_abf6_415b5444d651);
}
impl ::windows::core::RuntimeName for SpatialEntityRemovedEventArgs {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialEntityRemovedEventArgs";
}
impl ::core::convert::From<SpatialEntityRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: SpatialEntityRemovedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialEntityRemovedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SpatialEntityRemovedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialEntityRemovedEventArgs {
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 SpatialEntityRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialEntityRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: SpatialEntityRemovedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialEntityRemovedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SpatialEntityRemovedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialEntityRemovedEventArgs {
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 SpatialEntityRemovedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialEntityRemovedEventArgs {}
unsafe impl ::core::marker::Sync for SpatialEntityRemovedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialEntityStore(pub ::windows::core::IInspectable);
impl SpatialEntityStore {
#[cfg(feature = "Foundation")]
pub fn SaveAsync<'a, Param0: ::windows::core::IntoParam<'a, SpatialEntity>>(&self, entity: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), entity.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveAsync<'a, Param0: ::windows::core::IntoParam<'a, SpatialEntity>>(&self, entity: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), entity.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
pub fn CreateEntityWatcher(&self) -> ::windows::core::Result<SpatialEntityWatcher> {
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::<SpatialEntityWatcher>(result__)
}
}
pub fn IsSupported() -> ::windows::core::Result<bool> {
Self::ISpatialEntityStoreStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
#[cfg(feature = "System_RemoteSystems")]
pub fn TryGetForRemoteSystemSession<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::RemoteSystems::RemoteSystemSession>>(session: Param0) -> ::windows::core::Result<SpatialEntityStore> {
Self::ISpatialEntityStoreStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), session.into_param().abi(), &mut result__).from_abi::<SpatialEntityStore>(result__)
})
}
pub fn ISpatialEntityStoreStatics<R, F: FnOnce(&ISpatialEntityStoreStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialEntityStore, ISpatialEntityStoreStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialEntityStore {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialEntityStore;{329788ba-e513-4f06-889d-1be30ecf43e6})");
}
unsafe impl ::windows::core::Interface for SpatialEntityStore {
type Vtable = ISpatialEntityStore_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x329788ba_e513_4f06_889d_1be30ecf43e6);
}
impl ::windows::core::RuntimeName for SpatialEntityStore {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialEntityStore";
}
impl ::core::convert::From<SpatialEntityStore> for ::windows::core::IUnknown {
fn from(value: SpatialEntityStore) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialEntityStore> for ::windows::core::IUnknown {
fn from(value: &SpatialEntityStore) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialEntityStore {
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 SpatialEntityStore {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialEntityStore> for ::windows::core::IInspectable {
fn from(value: SpatialEntityStore) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialEntityStore> for ::windows::core::IInspectable {
fn from(value: &SpatialEntityStore) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialEntityStore {
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 SpatialEntityStore {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialEntityStore {}
unsafe impl ::core::marker::Sync for SpatialEntityStore {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialEntityUpdatedEventArgs(pub ::windows::core::IInspectable);
impl SpatialEntityUpdatedEventArgs {
pub fn Entity(&self) -> ::windows::core::Result<SpatialEntity> {
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::<SpatialEntity>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialEntityUpdatedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialEntityUpdatedEventArgs;{e5671766-627b-43cb-a49f-b3be6d47deed})");
}
unsafe impl ::windows::core::Interface for SpatialEntityUpdatedEventArgs {
type Vtable = ISpatialEntityUpdatedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe5671766_627b_43cb_a49f_b3be6d47deed);
}
impl ::windows::core::RuntimeName for SpatialEntityUpdatedEventArgs {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialEntityUpdatedEventArgs";
}
impl ::core::convert::From<SpatialEntityUpdatedEventArgs> for ::windows::core::IUnknown {
fn from(value: SpatialEntityUpdatedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialEntityUpdatedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SpatialEntityUpdatedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialEntityUpdatedEventArgs {
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 SpatialEntityUpdatedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialEntityUpdatedEventArgs> for ::windows::core::IInspectable {
fn from(value: SpatialEntityUpdatedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialEntityUpdatedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SpatialEntityUpdatedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialEntityUpdatedEventArgs {
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 SpatialEntityUpdatedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialEntityUpdatedEventArgs {}
unsafe impl ::core::marker::Sync for SpatialEntityUpdatedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialEntityWatcher(pub ::windows::core::IInspectable);
impl SpatialEntityWatcher {
pub fn Status(&self) -> ::windows::core::Result<SpatialEntityWatcherStatus> {
let this = self;
unsafe {
let mut result__: SpatialEntityWatcherStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialEntityWatcherStatus>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Added<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SpatialEntityWatcher, SpatialEntityAddedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveAdded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Updated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SpatialEntityWatcher, SpatialEntityUpdatedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveUpdated<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Removed<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SpatialEntityWatcher, SpatialEntityRemovedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveRemoved<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn EnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SpatialEntityWatcher, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveEnumerationCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
pub fn Start(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this)).ok() }
}
pub fn Stop(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialEntityWatcher {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialEntityWatcher;{b3b85fa0-6d5e-4bbc-805d-5fe5b9ba1959})");
}
unsafe impl ::windows::core::Interface for SpatialEntityWatcher {
type Vtable = ISpatialEntityWatcher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb3b85fa0_6d5e_4bbc_805d_5fe5b9ba1959);
}
impl ::windows::core::RuntimeName for SpatialEntityWatcher {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialEntityWatcher";
}
impl ::core::convert::From<SpatialEntityWatcher> for ::windows::core::IUnknown {
fn from(value: SpatialEntityWatcher) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialEntityWatcher> for ::windows::core::IUnknown {
fn from(value: &SpatialEntityWatcher) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialEntityWatcher {
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 SpatialEntityWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialEntityWatcher> for ::windows::core::IInspectable {
fn from(value: SpatialEntityWatcher) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialEntityWatcher> for ::windows::core::IInspectable {
fn from(value: &SpatialEntityWatcher) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialEntityWatcher {
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 SpatialEntityWatcher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialEntityWatcher {}
unsafe impl ::core::marker::Sync for SpatialEntityWatcher {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SpatialEntityWatcherStatus(pub i32);
impl SpatialEntityWatcherStatus {
pub const Created: SpatialEntityWatcherStatus = SpatialEntityWatcherStatus(0i32);
pub const Started: SpatialEntityWatcherStatus = SpatialEntityWatcherStatus(1i32);
pub const EnumerationCompleted: SpatialEntityWatcherStatus = SpatialEntityWatcherStatus(2i32);
pub const Stopping: SpatialEntityWatcherStatus = SpatialEntityWatcherStatus(3i32);
pub const Stopped: SpatialEntityWatcherStatus = SpatialEntityWatcherStatus(4i32);
pub const Aborted: SpatialEntityWatcherStatus = SpatialEntityWatcherStatus(5i32);
}
impl ::core::convert::From<i32> for SpatialEntityWatcherStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SpatialEntityWatcherStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SpatialEntityWatcherStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Perception.Spatial.SpatialEntityWatcherStatus;i4)");
}
impl ::windows::core::DefaultType for SpatialEntityWatcherStatus {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SpatialLocatability(pub i32);
impl SpatialLocatability {
pub const Unavailable: SpatialLocatability = SpatialLocatability(0i32);
pub const OrientationOnly: SpatialLocatability = SpatialLocatability(1i32);
pub const PositionalTrackingActivating: SpatialLocatability = SpatialLocatability(2i32);
pub const PositionalTrackingActive: SpatialLocatability = SpatialLocatability(3i32);
pub const PositionalTrackingInhibited: SpatialLocatability = SpatialLocatability(4i32);
}
impl ::core::convert::From<i32> for SpatialLocatability {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SpatialLocatability {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SpatialLocatability {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Perception.Spatial.SpatialLocatability;i4)");
}
impl ::windows::core::DefaultType for SpatialLocatability {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialLocation(pub ::windows::core::IInspectable);
impl SpatialLocation {
#[cfg(feature = "Foundation_Numerics")]
pub fn Position(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Vector3> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Vector3>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn Orientation(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Quaternion> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Quaternion = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Quaternion>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn AbsoluteLinearVelocity(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Vector3> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Vector3>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn AbsoluteLinearAcceleration(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Vector3> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Vector3>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Numerics")]
pub fn AbsoluteAngularVelocity(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Quaternion> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Quaternion = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Quaternion>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation_Numerics")]
pub fn AbsoluteAngularAcceleration(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Quaternion> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Quaternion = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Quaternion>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn AbsoluteAngularVelocityAxisAngle(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Vector3> {
let this = &::windows::core::Interface::cast::<ISpatialLocation2>(self)?;
unsafe {
let mut result__: super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Vector3>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn AbsoluteAngularAccelerationAxisAngle(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Vector3> {
let this = &::windows::core::Interface::cast::<ISpatialLocation2>(self)?;
unsafe {
let mut result__: super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Vector3>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialLocation {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialLocation;{1d81d29d-24a1-37d5-8fa1-39b4f9ad67e2})");
}
unsafe impl ::windows::core::Interface for SpatialLocation {
type Vtable = ISpatialLocation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1d81d29d_24a1_37d5_8fa1_39b4f9ad67e2);
}
impl ::windows::core::RuntimeName for SpatialLocation {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialLocation";
}
impl ::core::convert::From<SpatialLocation> for ::windows::core::IUnknown {
fn from(value: SpatialLocation) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialLocation> for ::windows::core::IUnknown {
fn from(value: &SpatialLocation) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialLocation {
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 SpatialLocation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialLocation> for ::windows::core::IInspectable {
fn from(value: SpatialLocation) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialLocation> for ::windows::core::IInspectable {
fn from(value: &SpatialLocation) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialLocation {
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 SpatialLocation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialLocation {}
unsafe impl ::core::marker::Sync for SpatialLocation {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialLocator(pub ::windows::core::IInspectable);
impl SpatialLocator {
pub fn Locatability(&self) -> ::windows::core::Result<SpatialLocatability> {
let this = self;
unsafe {
let mut result__: SpatialLocatability = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialLocatability>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn LocatabilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SpatialLocator, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveLocatabilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn PositionalTrackingDeactivating<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SpatialLocator, SpatialLocatorPositionalTrackingDeactivatingEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemovePositionalTrackingDeactivating<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() }
}
pub fn TryLocateAtTimestamp<'a, Param0: ::windows::core::IntoParam<'a, super::PerceptionTimestamp>, Param1: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>>(&self, timestamp: Param0, coordinatesystem: Param1) -> ::windows::core::Result<SpatialLocation> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), timestamp.into_param().abi(), coordinatesystem.into_param().abi(), &mut result__).from_abi::<SpatialLocation>(result__)
}
}
pub fn CreateAttachedFrameOfReferenceAtCurrentHeading(&self) -> ::windows::core::Result<SpatialLocatorAttachedFrameOfReference> {
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::<SpatialLocatorAttachedFrameOfReference>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateAttachedFrameOfReferenceAtCurrentHeadingWithPosition<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>>(&self, relativeposition: Param0) -> ::windows::core::Result<SpatialLocatorAttachedFrameOfReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), relativeposition.into_param().abi(), &mut result__).from_abi::<SpatialLocatorAttachedFrameOfReference>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateAttachedFrameOfReferenceAtCurrentHeadingWithPositionAndOrientation<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Quaternion>>(&self, relativeposition: Param0, relativeorientation: Param1) -> ::windows::core::Result<SpatialLocatorAttachedFrameOfReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), relativeposition.into_param().abi(), relativeorientation.into_param().abi(), &mut result__).from_abi::<SpatialLocatorAttachedFrameOfReference>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateAttachedFrameOfReferenceAtCurrentHeadingWithPositionAndOrientationAndRelativeHeading<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Quaternion>>(&self, relativeposition: Param0, relativeorientation: Param1, relativeheadinginradians: f64) -> ::windows::core::Result<SpatialLocatorAttachedFrameOfReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), relativeposition.into_param().abi(), relativeorientation.into_param().abi(), relativeheadinginradians, &mut result__).from_abi::<SpatialLocatorAttachedFrameOfReference>(result__)
}
}
pub fn CreateStationaryFrameOfReferenceAtCurrentLocation(&self) -> ::windows::core::Result<SpatialStationaryFrameOfReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialStationaryFrameOfReference>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateStationaryFrameOfReferenceAtCurrentLocationWithPosition<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>>(&self, relativeposition: Param0) -> ::windows::core::Result<SpatialStationaryFrameOfReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), relativeposition.into_param().abi(), &mut result__).from_abi::<SpatialStationaryFrameOfReference>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateStationaryFrameOfReferenceAtCurrentLocationWithPositionAndOrientation<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Quaternion>>(&self, relativeposition: Param0, relativeorientation: Param1) -> ::windows::core::Result<SpatialStationaryFrameOfReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), relativeposition.into_param().abi(), relativeorientation.into_param().abi(), &mut result__).from_abi::<SpatialStationaryFrameOfReference>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn CreateStationaryFrameOfReferenceAtCurrentLocationWithPositionAndOrientationAndRelativeHeading<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Quaternion>>(&self, relativeposition: Param0, relativeorientation: Param1, relativeheadinginradians: f64) -> ::windows::core::Result<SpatialStationaryFrameOfReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), relativeposition.into_param().abi(), relativeorientation.into_param().abi(), relativeheadinginradians, &mut result__).from_abi::<SpatialStationaryFrameOfReference>(result__)
}
}
pub fn GetDefault() -> ::windows::core::Result<SpatialLocator> {
Self::ISpatialLocatorStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialLocator>(result__)
})
}
pub fn ISpatialLocatorStatics<R, F: FnOnce(&ISpatialLocatorStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialLocator, ISpatialLocatorStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialLocator {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialLocator;{f6478925-9e0c-3bb6-997e-b64ecca24cf4})");
}
unsafe impl ::windows::core::Interface for SpatialLocator {
type Vtable = ISpatialLocator_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf6478925_9e0c_3bb6_997e_b64ecca24cf4);
}
impl ::windows::core::RuntimeName for SpatialLocator {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialLocator";
}
impl ::core::convert::From<SpatialLocator> for ::windows::core::IUnknown {
fn from(value: SpatialLocator) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialLocator> for ::windows::core::IUnknown {
fn from(value: &SpatialLocator) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialLocator {
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 SpatialLocator {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialLocator> for ::windows::core::IInspectable {
fn from(value: SpatialLocator) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialLocator> for ::windows::core::IInspectable {
fn from(value: &SpatialLocator) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialLocator {
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 SpatialLocator {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialLocator {}
unsafe impl ::core::marker::Sync for SpatialLocator {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialLocatorAttachedFrameOfReference(pub ::windows::core::IInspectable);
impl SpatialLocatorAttachedFrameOfReference {
#[cfg(feature = "Foundation_Numerics")]
pub fn RelativePosition(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Vector3> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Vector3 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Vector3>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn SetRelativePosition<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Vector3>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation_Numerics")]
pub fn RelativeOrientation(&self) -> ::windows::core::Result<super::super::Foundation::Numerics::Quaternion> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::Numerics::Quaternion = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Numerics::Quaternion>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn SetRelativeOrientation<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Numerics::Quaternion>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn AdjustHeading(&self, headingoffsetinradians: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), headingoffsetinradians).ok() }
}
pub fn GetStationaryCoordinateSystemAtTimestamp<'a, Param0: ::windows::core::IntoParam<'a, super::PerceptionTimestamp>>(&self, timestamp: Param0) -> ::windows::core::Result<SpatialCoordinateSystem> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), timestamp.into_param().abi(), &mut result__).from_abi::<SpatialCoordinateSystem>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryGetRelativeHeadingAtTimestamp<'a, Param0: ::windows::core::IntoParam<'a, super::PerceptionTimestamp>>(&self, timestamp: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), timestamp.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialLocatorAttachedFrameOfReference {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialLocatorAttachedFrameOfReference;{e1774ef6-1f4f-499c-9625-ef5e6ed7a048})");
}
unsafe impl ::windows::core::Interface for SpatialLocatorAttachedFrameOfReference {
type Vtable = ISpatialLocatorAttachedFrameOfReference_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe1774ef6_1f4f_499c_9625_ef5e6ed7a048);
}
impl ::windows::core::RuntimeName for SpatialLocatorAttachedFrameOfReference {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialLocatorAttachedFrameOfReference";
}
impl ::core::convert::From<SpatialLocatorAttachedFrameOfReference> for ::windows::core::IUnknown {
fn from(value: SpatialLocatorAttachedFrameOfReference) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialLocatorAttachedFrameOfReference> for ::windows::core::IUnknown {
fn from(value: &SpatialLocatorAttachedFrameOfReference) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialLocatorAttachedFrameOfReference {
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 SpatialLocatorAttachedFrameOfReference {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialLocatorAttachedFrameOfReference> for ::windows::core::IInspectable {
fn from(value: SpatialLocatorAttachedFrameOfReference) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialLocatorAttachedFrameOfReference> for ::windows::core::IInspectable {
fn from(value: &SpatialLocatorAttachedFrameOfReference) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialLocatorAttachedFrameOfReference {
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 SpatialLocatorAttachedFrameOfReference {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialLocatorAttachedFrameOfReference {}
unsafe impl ::core::marker::Sync for SpatialLocatorAttachedFrameOfReference {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialLocatorPositionalTrackingDeactivatingEventArgs(pub ::windows::core::IInspectable);
impl SpatialLocatorPositionalTrackingDeactivatingEventArgs {
pub fn Canceled(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetCanceled(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialLocatorPositionalTrackingDeactivatingEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialLocatorPositionalTrackingDeactivatingEventArgs;{b8a84063-e3f4-368b-9061-9ea9d1d6cc16})");
}
unsafe impl ::windows::core::Interface for SpatialLocatorPositionalTrackingDeactivatingEventArgs {
type Vtable = ISpatialLocatorPositionalTrackingDeactivatingEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb8a84063_e3f4_368b_9061_9ea9d1d6cc16);
}
impl ::windows::core::RuntimeName for SpatialLocatorPositionalTrackingDeactivatingEventArgs {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialLocatorPositionalTrackingDeactivatingEventArgs";
}
impl ::core::convert::From<SpatialLocatorPositionalTrackingDeactivatingEventArgs> for ::windows::core::IUnknown {
fn from(value: SpatialLocatorPositionalTrackingDeactivatingEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialLocatorPositionalTrackingDeactivatingEventArgs> for ::windows::core::IUnknown {
fn from(value: &SpatialLocatorPositionalTrackingDeactivatingEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialLocatorPositionalTrackingDeactivatingEventArgs {
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 SpatialLocatorPositionalTrackingDeactivatingEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialLocatorPositionalTrackingDeactivatingEventArgs> for ::windows::core::IInspectable {
fn from(value: SpatialLocatorPositionalTrackingDeactivatingEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialLocatorPositionalTrackingDeactivatingEventArgs> for ::windows::core::IInspectable {
fn from(value: &SpatialLocatorPositionalTrackingDeactivatingEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialLocatorPositionalTrackingDeactivatingEventArgs {
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 SpatialLocatorPositionalTrackingDeactivatingEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialLocatorPositionalTrackingDeactivatingEventArgs {}
unsafe impl ::core::marker::Sync for SpatialLocatorPositionalTrackingDeactivatingEventArgs {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SpatialLookDirectionRange(pub i32);
impl SpatialLookDirectionRange {
pub const ForwardOnly: SpatialLookDirectionRange = SpatialLookDirectionRange(0i32);
pub const Omnidirectional: SpatialLookDirectionRange = SpatialLookDirectionRange(1i32);
}
impl ::core::convert::From<i32> for SpatialLookDirectionRange {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SpatialLookDirectionRange {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SpatialLookDirectionRange {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Perception.Spatial.SpatialLookDirectionRange;i4)");
}
impl ::windows::core::DefaultType for SpatialLookDirectionRange {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SpatialMovementRange(pub i32);
impl SpatialMovementRange {
pub const NoMovement: SpatialMovementRange = SpatialMovementRange(0i32);
pub const Bounded: SpatialMovementRange = SpatialMovementRange(1i32);
}
impl ::core::convert::From<i32> for SpatialMovementRange {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SpatialMovementRange {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SpatialMovementRange {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Perception.Spatial.SpatialMovementRange;i4)");
}
impl ::windows::core::DefaultType for SpatialMovementRange {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SpatialPerceptionAccessStatus(pub i32);
impl SpatialPerceptionAccessStatus {
pub const Unspecified: SpatialPerceptionAccessStatus = SpatialPerceptionAccessStatus(0i32);
pub const Allowed: SpatialPerceptionAccessStatus = SpatialPerceptionAccessStatus(1i32);
pub const DeniedByUser: SpatialPerceptionAccessStatus = SpatialPerceptionAccessStatus(2i32);
pub const DeniedBySystem: SpatialPerceptionAccessStatus = SpatialPerceptionAccessStatus(3i32);
}
impl ::core::convert::From<i32> for SpatialPerceptionAccessStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SpatialPerceptionAccessStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SpatialPerceptionAccessStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Perception.Spatial.SpatialPerceptionAccessStatus;i4)");
}
impl ::windows::core::DefaultType for SpatialPerceptionAccessStatus {
type DefaultType = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Foundation_Numerics")]
pub struct SpatialRay {
pub Origin: super::super::Foundation::Numerics::Vector3,
pub Direction: super::super::Foundation::Numerics::Vector3,
}
#[cfg(feature = "Foundation_Numerics")]
impl SpatialRay {}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::default::Default for SpatialRay {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::fmt::Debug for SpatialRay {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("SpatialRay").field("Origin", &self.Origin).field("Direction", &self.Direction).finish()
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::PartialEq for SpatialRay {
fn eq(&self, other: &Self) -> bool {
self.Origin == other.Origin && self.Direction == other.Direction
}
}
#[cfg(feature = "Foundation_Numerics")]
impl ::core::cmp::Eq for SpatialRay {}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::Abi for SpatialRay {
type Abi = Self;
}
#[cfg(feature = "Foundation_Numerics")]
unsafe impl ::windows::core::RuntimeType for SpatialRay {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Perception.Spatial.SpatialRay;struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4);struct(Windows.Foundation.Numerics.Vector3;f4;f4;f4))");
}
#[cfg(feature = "Foundation_Numerics")]
impl ::windows::core::DefaultType for SpatialRay {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialStageFrameOfReference(pub ::windows::core::IInspectable);
impl SpatialStageFrameOfReference {
pub fn CoordinateSystem(&self) -> ::windows::core::Result<SpatialCoordinateSystem> {
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::<SpatialCoordinateSystem>(result__)
}
}
pub fn MovementRange(&self) -> ::windows::core::Result<SpatialMovementRange> {
let this = self;
unsafe {
let mut result__: SpatialMovementRange = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialMovementRange>(result__)
}
}
pub fn LookDirectionRange(&self) -> ::windows::core::Result<SpatialLookDirectionRange> {
let this = self;
unsafe {
let mut result__: SpatialLookDirectionRange = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialLookDirectionRange>(result__)
}
}
pub fn GetCoordinateSystemAtCurrentLocation<'a, Param0: ::windows::core::IntoParam<'a, SpatialLocator>>(&self, locator: Param0) -> ::windows::core::Result<SpatialCoordinateSystem> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), locator.into_param().abi(), &mut result__).from_abi::<SpatialCoordinateSystem>(result__)
}
}
#[cfg(feature = "Foundation_Numerics")]
pub fn TryGetMovementBounds<'a, Param0: ::windows::core::IntoParam<'a, SpatialCoordinateSystem>>(&self, coordinatesystem: Param0) -> ::windows::core::Result<::windows::core::Array<super::super::Foundation::Numerics::Vector3>> {
let this = self;
unsafe {
let mut result__: ::windows::core::Array<super::super::Foundation::Numerics::Vector3> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), coordinatesystem.into_param().abi(), ::windows::core::Array::<super::super::Foundation::Numerics::Vector3>::set_abi_len(&mut result__), &mut result__ as *mut _ as _).and_then(|| result__)
}
}
pub fn Current() -> ::windows::core::Result<SpatialStageFrameOfReference> {
Self::ISpatialStageFrameOfReferenceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SpatialStageFrameOfReference>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn CurrentChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<::windows::core::IInspectable>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
Self::ISpatialStageFrameOfReferenceStatics(|this| unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn RemoveCurrentChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(cookie: Param0) -> ::windows::core::Result<()> {
Self::ISpatialStageFrameOfReferenceStatics(|this| unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() })
}
#[cfg(feature = "Foundation")]
pub fn RequestNewStageAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<SpatialStageFrameOfReference>> {
Self::ISpatialStageFrameOfReferenceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<SpatialStageFrameOfReference>>(result__)
})
}
pub fn ISpatialStageFrameOfReferenceStatics<R, F: FnOnce(&ISpatialStageFrameOfReferenceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SpatialStageFrameOfReference, ISpatialStageFrameOfReferenceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SpatialStageFrameOfReference {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialStageFrameOfReference;{7a8a3464-ad0d-4590-ab86-33062b674926})");
}
unsafe impl ::windows::core::Interface for SpatialStageFrameOfReference {
type Vtable = ISpatialStageFrameOfReference_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7a8a3464_ad0d_4590_ab86_33062b674926);
}
impl ::windows::core::RuntimeName for SpatialStageFrameOfReference {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialStageFrameOfReference";
}
impl ::core::convert::From<SpatialStageFrameOfReference> for ::windows::core::IUnknown {
fn from(value: SpatialStageFrameOfReference) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialStageFrameOfReference> for ::windows::core::IUnknown {
fn from(value: &SpatialStageFrameOfReference) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialStageFrameOfReference {
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 SpatialStageFrameOfReference {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialStageFrameOfReference> for ::windows::core::IInspectable {
fn from(value: SpatialStageFrameOfReference) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialStageFrameOfReference> for ::windows::core::IInspectable {
fn from(value: &SpatialStageFrameOfReference) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialStageFrameOfReference {
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 SpatialStageFrameOfReference {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialStageFrameOfReference {}
unsafe impl ::core::marker::Sync for SpatialStageFrameOfReference {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SpatialStationaryFrameOfReference(pub ::windows::core::IInspectable);
impl SpatialStationaryFrameOfReference {
pub fn CoordinateSystem(&self) -> ::windows::core::Result<SpatialCoordinateSystem> {
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::<SpatialCoordinateSystem>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SpatialStationaryFrameOfReference {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Perception.Spatial.SpatialStationaryFrameOfReference;{09dbccb9-bcf8-3e7f-be7e-7edccbb178a8})");
}
unsafe impl ::windows::core::Interface for SpatialStationaryFrameOfReference {
type Vtable = ISpatialStationaryFrameOfReference_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09dbccb9_bcf8_3e7f_be7e_7edccbb178a8);
}
impl ::windows::core::RuntimeName for SpatialStationaryFrameOfReference {
const NAME: &'static str = "Windows.Perception.Spatial.SpatialStationaryFrameOfReference";
}
impl ::core::convert::From<SpatialStationaryFrameOfReference> for ::windows::core::IUnknown {
fn from(value: SpatialStationaryFrameOfReference) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SpatialStationaryFrameOfReference> for ::windows::core::IUnknown {
fn from(value: &SpatialStationaryFrameOfReference) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SpatialStationaryFrameOfReference {
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 SpatialStationaryFrameOfReference {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SpatialStationaryFrameOfReference> for ::windows::core::IInspectable {
fn from(value: SpatialStationaryFrameOfReference) -> Self {
value.0
}
}
impl ::core::convert::From<&SpatialStationaryFrameOfReference> for ::windows::core::IInspectable {
fn from(value: &SpatialStationaryFrameOfReference) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SpatialStationaryFrameOfReference {
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 SpatialStationaryFrameOfReference {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SpatialStationaryFrameOfReference {}
unsafe impl ::core::marker::Sync for SpatialStationaryFrameOfReference {}
|
//! Utilities for common diff related operations.
//!
//! This module provides specialized utilities and simplified diff operations
//! for common operations. It's useful when you want to work with text diffs
//! and you're interested in getting vectors of these changes directly.
//!
//! # Slice Remapping
//!
//! When working with [`TextDiff`] it's common that one takes advantage of the
//! built-in tokenization of the differ. This for instance lets you do
//! grapheme level diffs. This is implemented by the differ generating rather
//! small slices of strings and running a diff algorithm over them.
//!
//! The downside of this is that all the [`DiffOp`] objects produced by the
//! diffing algorithm encode operations on these rather small slices. For
//! a lot of use cases this is not what one wants which can make this very
//! inconvenient. This module provides a [`TextDiffRemapper`] which lets you
//! map from the ranges that the [`TextDiff`] returns to the original input
//! strings. For more information see [`TextDiffRemapper`].
//!
//! # Simple Diff Functions
//!
//! This module provides a range of common test diff functions that will
//! produce vectors of `(change_tag, value)` tuples. They will automatically
//! optimize towards returning the most useful slice that one would expect for
//! the type of diff performed.
use std::hash::Hash;
use std::ops::{Index, Range};
use crate::{
capture_diff_slices, Algorithm, ChangeTag, DiffOp, DiffableStr, DiffableStrRef, TextDiff,
};
struct SliceRemapper<'x, T: ?Sized> {
source: &'x T,
indexes: Vec<Range<usize>>,
}
impl<'x, T: DiffableStr + ?Sized> SliceRemapper<'x, T> {
fn new(source: &'x T, slices: &[&'x T]) -> SliceRemapper<'x, T> {
let indexes = slices
.iter()
.scan(0, |state, item| {
let start = *state;
let end = start + item.len();
*state = end;
Some(start..end)
})
.collect();
SliceRemapper { source, indexes }
}
fn slice(&self, range: Range<usize>) -> Option<&'x T> {
let start = self.indexes.get(range.start)?.start;
let end = self.indexes.get(range.end - 1)?.end;
Some(self.source.slice(start..end))
}
}
impl<'x, T: DiffableStr + ?Sized> Index<Range<usize>> for SliceRemapper<'x, T> {
type Output = T;
fn index(&self, range: Range<usize>) -> &Self::Output {
self.slice(range).expect("out of bounds")
}
}
/// A remapper that can remap diff ops to the original slices.
///
/// The idea here is that when a [`TextDiff`](crate::TextDiff) is created from
/// two strings and the internal tokenization is used, this remapper can take
/// a range in the tokenized sequences and remap it to the original string.
/// This is particularly useful when you want to do things like character or
/// grapheme level diffs but you want to not have to iterate over small sequences
/// but large consequitive ones from the source.
///
/// ```rust
/// use similar::{ChangeTag, TextDiff};
/// use similar::utils::TextDiffRemapper;
///
/// let old = "yo! foo bar baz";
/// let new = "yo! foo bor baz";
/// let diff = TextDiff::from_words(old, new);
/// let remapper = TextDiffRemapper::from_text_diff(&diff, old, new);
/// let changes: Vec<_> = diff.ops()
/// .iter()
/// .flat_map(move |x| remapper.iter_slices(x))
/// .collect();
///
/// assert_eq!(changes, vec![
/// (ChangeTag::Equal, "yo! foo "),
/// (ChangeTag::Delete, "bar"),
/// (ChangeTag::Insert, "bor"),
/// (ChangeTag::Equal, " baz")
/// ]);
pub struct TextDiffRemapper<'x, T: ?Sized> {
old: SliceRemapper<'x, T>,
new: SliceRemapper<'x, T>,
}
impl<'x, T: DiffableStr + ?Sized> TextDiffRemapper<'x, T> {
/// Creates a new remapper from strings and slices.
pub fn new(
old_slices: &[&'x T],
new_slices: &[&'x T],
old: &'x T,
new: &'x T,
) -> TextDiffRemapper<'x, T> {
TextDiffRemapper {
old: SliceRemapper::new(old, old_slices),
new: SliceRemapper::new(new, new_slices),
}
}
/// Creates a new remapper from a text diff and the original strings.
pub fn from_text_diff<'old, 'new, 'bufs>(
diff: &TextDiff<'old, 'new, 'bufs, T>,
old: &'x T,
new: &'x T,
) -> TextDiffRemapper<'x, T>
where
'old: 'x,
'new: 'x,
{
TextDiffRemapper {
old: SliceRemapper::new(old, diff.old_slices()),
new: SliceRemapper::new(new, diff.new_slices()),
}
}
/// Slices into the old string.
pub fn slice_old(&self, range: Range<usize>) -> Option<&'x T> {
self.old.slice(range)
}
/// Slices into the new string.
pub fn slice_new(&self, range: Range<usize>) -> Option<&'x T> {
self.new.slice(range)
}
/// Given a diffop yields the changes it encodes against the original strings.
///
/// This is the same as the [`DiffOp::iter_slices`] method.
///
/// ## Panics
///
/// This method can panic if the input strings passed to the constructor
/// are incompatible with the input strings passed to the diffing algorithm.
pub fn iter_slices(&self, op: &DiffOp) -> impl Iterator<Item = (ChangeTag, &'x T)> {
// note: this is equivalent to the code in `DiffOp::iter_slices`. It is
// a copy/paste because the slicing currently cannot be well abstracted
// because of lifetime issues caused by the `Index` trait.
match *op {
DiffOp::Equal { old_index, len, .. } => {
Some((ChangeTag::Equal, self.old.slice(old_index..old_index + len)))
.into_iter()
.chain(None.into_iter())
}
DiffOp::Insert {
new_index, new_len, ..
} => Some((
ChangeTag::Insert,
self.new.slice(new_index..new_index + new_len),
))
.into_iter()
.chain(None.into_iter()),
DiffOp::Delete {
old_index, old_len, ..
} => Some((
ChangeTag::Delete,
self.old.slice(old_index..old_index + old_len),
))
.into_iter()
.chain(None.into_iter()),
DiffOp::Replace {
old_index,
old_len,
new_index,
new_len,
} => Some((
ChangeTag::Delete,
self.old.slice(old_index..old_index + old_len),
))
.into_iter()
.chain(
Some((
ChangeTag::Insert,
self.new.slice(new_index..new_index + new_len),
))
.into_iter(),
),
}
.map(|(tag, opt_val)| (tag, opt_val.expect("slice out of bounds")))
}
}
/// Shortcut for diffing two slices.
///
/// This function produces the diff of two slices and returns a vector
/// with the changes.
///
/// ```rust
/// use similar::{Algorithm, ChangeTag};
/// use similar::utils::diff_slices;
///
/// let old = "foo\nbar\nbaz".lines().collect::<Vec<_>>();
/// let new = "foo\nbar\nBAZ".lines().collect::<Vec<_>>();
/// assert_eq!(diff_slices(Algorithm::Myers, &old, &new), vec![
/// (ChangeTag::Equal, &["foo", "bar"][..]),
/// (ChangeTag::Delete, &["baz"][..]),
/// (ChangeTag::Insert, &["BAZ"][..]),
/// ]);
/// ```
pub fn diff_slices<'x, T: PartialEq + Hash + Ord>(
alg: Algorithm,
old: &'x [T],
new: &'x [T],
) -> Vec<(ChangeTag, &'x [T])> {
capture_diff_slices(alg, old, new)
.iter()
.flat_map(|op| op.iter_slices(old, new))
.collect()
}
/// Shortcut for making a character level diff.
///
/// This function produces the diff of two strings and returns a vector
/// with the changes. It returns connected slices into the original string
/// rather than character level slices.
///
/// ```rust
/// use similar::{Algorithm, ChangeTag};
/// use similar::utils::diff_chars;
///
/// assert_eq!(diff_chars(Algorithm::Myers, "foobarbaz", "fooBARbaz"), vec![
/// (ChangeTag::Equal, "foo"),
/// (ChangeTag::Delete, "bar"),
/// (ChangeTag::Insert, "BAR"),
/// (ChangeTag::Equal, "baz"),
/// ]);
/// ```
pub fn diff_chars<'x, T: DiffableStrRef + ?Sized>(
alg: Algorithm,
old: &'x T,
new: &'x T,
) -> Vec<(ChangeTag, &'x T::Output)> {
let old = old.as_diffable_str();
let new = new.as_diffable_str();
let diff = TextDiff::configure().algorithm(alg).diff_chars(old, new);
let remapper = TextDiffRemapper::from_text_diff(&diff, old, new);
diff.ops()
.iter()
.flat_map(move |x| remapper.iter_slices(x))
.collect()
}
/// Shortcut for making a word level diff.
///
/// This function produces the diff of two strings and returns a vector
/// with the changes. It returns connected slices into the original string
/// rather than word level slices.
///
/// ```rust
/// use similar::{Algorithm, ChangeTag};
/// use similar::utils::diff_words;
///
/// assert_eq!(diff_words(Algorithm::Myers, "foo bar baz", "foo bor baz"), vec![
/// (ChangeTag::Equal, "foo "),
/// (ChangeTag::Delete, "bar"),
/// (ChangeTag::Insert, "bor"),
/// (ChangeTag::Equal, " baz"),
/// ]);
/// ```
pub fn diff_words<'x, T: DiffableStrRef + ?Sized>(
alg: Algorithm,
old: &'x T,
new: &'x T,
) -> Vec<(ChangeTag, &'x T::Output)> {
let old = old.as_diffable_str();
let new = new.as_diffable_str();
let diff = TextDiff::configure().algorithm(alg).diff_words(old, new);
let remapper = TextDiffRemapper::from_text_diff(&diff, old, new);
diff.ops()
.iter()
.flat_map(move |x| remapper.iter_slices(x))
.collect()
}
/// Shortcut for making a unicode word level diff.
///
/// This function produces the diff of two strings and returns a vector
/// with the changes. It returns connected slices into the original string
/// rather than word level slices.
///
/// ```rust
/// use similar::{Algorithm, ChangeTag};
/// use similar::utils::diff_unicode_words;
///
/// let old = "The quick (\"brown\") fox can't jump 32.3 feet, right?";
/// let new = "The quick (\"brown\") fox can't jump 9.84 meters, right?";
/// assert_eq!(diff_unicode_words(Algorithm::Myers, old, new), vec![
/// (ChangeTag::Equal, "The quick (\"brown\") fox can\'t jump "),
/// (ChangeTag::Delete, "32.3"),
/// (ChangeTag::Insert, "9.84"),
/// (ChangeTag::Equal, " "),
/// (ChangeTag::Delete, "feet"),
/// (ChangeTag::Insert, "meters"),
/// (ChangeTag::Equal, ", right?")
/// ]);
/// ```
///
/// This requires the `unicode` feature.
#[cfg(feature = "unicode")]
pub fn diff_unicode_words<'x, T: DiffableStrRef + ?Sized>(
alg: Algorithm,
old: &'x T,
new: &'x T,
) -> Vec<(ChangeTag, &'x T::Output)> {
let old = old.as_diffable_str();
let new = new.as_diffable_str();
let diff = TextDiff::configure()
.algorithm(alg)
.diff_unicode_words(old, new);
let remapper = TextDiffRemapper::from_text_diff(&diff, old, new);
diff.ops()
.iter()
.flat_map(move |x| remapper.iter_slices(x))
.collect()
}
/// Shortcut for making a grapheme level diff.
///
/// This function produces the diff of two strings and returns a vector
/// with the changes. It returns connected slices into the original string
/// rather than grapheme level slices.
///
/// ```rust
/// use similar::{Algorithm, ChangeTag};
/// use similar::utils::diff_graphemes;
///
/// let old = "The flag of Austria is 🇦🇹";
/// let new = "The flag of Albania is 🇦🇱";
/// assert_eq!(diff_graphemes(Algorithm::Myers, old, new), vec![
/// (ChangeTag::Equal, "The flag of A"),
/// (ChangeTag::Delete, "ustr"),
/// (ChangeTag::Insert, "lban"),
/// (ChangeTag::Equal, "ia is "),
/// (ChangeTag::Delete, "🇦🇹"),
/// (ChangeTag::Insert, "🇦🇱"),
/// ]);
/// ```
///
/// This requires the `unicode` feature.
#[cfg(feature = "unicode")]
pub fn diff_graphemes<'x, T: DiffableStrRef + ?Sized>(
alg: Algorithm,
old: &'x T,
new: &'x T,
) -> Vec<(ChangeTag, &'x T::Output)> {
let old = old.as_diffable_str();
let new = new.as_diffable_str();
let diff = TextDiff::configure()
.algorithm(alg)
.diff_graphemes(old, new);
let remapper = TextDiffRemapper::from_text_diff(&diff, old, new);
diff.ops()
.iter()
.flat_map(move |x| remapper.iter_slices(x))
.collect()
}
/// Shortcut for making a line diff.
///
/// This function produces the diff of two slices and returns a vector
/// with the changes. Unlike [`diff_chars`] or [`diff_slices`] it returns a
/// change tag for each line.
///
/// ```rust
/// use similar::{Algorithm, ChangeTag};
/// use similar::utils::diff_lines;
///
/// assert_eq!(diff_lines(Algorithm::Myers, "foo\nbar\nbaz\nblah", "foo\nbar\nbaz\nblurgh"), vec![
/// (ChangeTag::Equal, "foo\n"),
/// (ChangeTag::Equal, "bar\n"),
/// (ChangeTag::Equal, "baz\n"),
/// (ChangeTag::Delete, "blah"),
/// (ChangeTag::Insert, "blurgh"),
/// ]);
/// ```
pub fn diff_lines<'x, T: DiffableStrRef + ?Sized>(
alg: Algorithm,
old: &'x T,
new: &'x T,
) -> Vec<(ChangeTag, &'x T::Output)> {
TextDiff::configure()
.algorithm(alg)
.diff_lines(old, new)
.iter_all_changes()
.map(|change| (change.tag(), change.value()))
.collect()
}
#[test]
fn test_remapper() {
let a = "foo bar baz";
let words = a.tokenize_words();
dbg!(&words);
let remap = SliceRemapper::new(a, &words);
assert_eq!(remap.slice(0..3), Some("foo bar"));
assert_eq!(remap.slice(1..3), Some(" bar"));
assert_eq!(remap.slice(0..1), Some("foo"));
assert_eq!(remap.slice(0..5), Some("foo bar baz"));
assert_eq!(remap.slice(0..6), None);
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
pub(crate) trait UnsafeCast
{
#[inline(always)]
fn as_usize_pointer(&self) -> usize
{
self as *const Self as *const () as usize
}
#[inline(always)]
fn unsafe_cast<To>(&self) -> &To
{
unsafe { & * (self.as_usize_pointer() as *const To) }
}
#[inline(always)]
fn unsafe_cast_slice<To>(&self, length: usize) -> &[To]
{
unsafe { from_raw_parts(self.unsafe_cast::<To>(), length) }
}
}
impl<T: ?Sized> UnsafeCast for T
{
}
|
#![cfg(feature = "macros")]
use std::{
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
mpsc, Arc,
},
time::Duration,
};
use actix::prelude::*;
use actix_rt::time::{sleep, Instant};
#[derive(Clone, Debug)]
struct Num(usize);
impl Message for Num {
type Result = ();
}
struct MyActor(Arc<AtomicUsize>, Arc<AtomicBool>, Running);
impl Actor for MyActor {
type Context = actix::Context<Self>;
fn stopping(&mut self, _: &mut Self::Context) -> Running {
System::current().stop();
Running::Stop
}
}
impl StreamHandler<Num> for MyActor {
fn handle(&mut self, msg: Num, _: &mut Context<MyActor>) {
self.0.fetch_add(msg.0, Ordering::Relaxed);
}
fn finished(&mut self, _: &mut Context<MyActor>) {
self.1.store(true, Ordering::Relaxed);
}
}
#[actix::test]
async fn test_stream() {
let count = Arc::new(AtomicUsize::new(0));
let err = Arc::new(AtomicBool::new(false));
let items = vec![Num(1), Num(1), Num(1), Num(1), Num(1), Num(1), Num(1)];
let act_count = Arc::clone(&count);
let act_err = Arc::clone(&err);
MyActor::create(move |ctx| {
MyActor::add_stream(futures_util::stream::iter::<_>(items), ctx);
MyActor(act_count, act_err, Running::Stop)
});
sleep(Duration::new(0, 1_000_000)).await;
assert_eq!(count.load(Ordering::Relaxed), 7);
assert!(err.load(Ordering::Relaxed));
}
#[derive(Message)]
#[rtype(result = "()")]
struct Stop;
struct StopOnRequest(Arc<AtomicUsize>, Arc<AtomicBool>, Arc<AtomicBool>);
impl Actor for StopOnRequest {
type Context = actix::Context<Self>;
}
impl StreamHandler<Num> for StopOnRequest {
fn handle(&mut self, msg: Num, _: &mut Self::Context) {
self.0.fetch_add(msg.0, Ordering::Relaxed);
}
fn finished(&mut self, _: &mut Self::Context) {
self.2.store(true, Ordering::Relaxed);
}
}
impl actix::Handler<Stop> for StopOnRequest {
type Result = ();
fn handle(&mut self, _: Stop, ctx: &mut Self::Context) {
self.1.store(true, Ordering::Relaxed);
ctx.stop();
}
}
#[actix::test]
async fn test_infinite_stream() {
let count = Arc::new(AtomicUsize::new(0));
let stopped = Arc::new(AtomicBool::new(false));
let finished = Arc::new(AtomicBool::new(false));
let act_count = Arc::clone(&count);
let act_stopped = Arc::clone(&stopped);
let act_finished = Arc::clone(&finished);
let addr = StopOnRequest::create(move |ctx| {
StopOnRequest::add_stream(futures_util::stream::repeat(Num(1)), ctx);
StopOnRequest(act_count, act_stopped, act_finished)
});
sleep(Duration::new(0, 1_000_000)).await;
addr.send(Stop).await.unwrap();
assert!(
count.load(Ordering::Relaxed) > 0,
"Some items should be processed as actor has ran for some time"
);
assert!(
stopped.load(Ordering::Relaxed),
"Actor should have processed the Stop message"
);
assert!(
!finished.load(Ordering::Relaxed),
"As the stream is infinite, finished should never be called"
);
}
struct MySyncActor {
started: Arc<AtomicUsize>,
stopping: Arc<AtomicUsize>,
stopped: Arc<AtomicUsize>,
msgs: Arc<AtomicUsize>,
stop: bool,
}
impl Actor for MySyncActor {
type Context = actix::SyncContext<Self>;
fn started(&mut self, _: &mut Self::Context) {
self.started.fetch_add(1, Ordering::Relaxed);
}
fn stopping(&mut self, _: &mut Self::Context) -> Running {
self.stopping.fetch_add(1, Ordering::Relaxed);
Running::Continue
}
fn stopped(&mut self, _: &mut Self::Context) {
self.stopped.fetch_add(1, Ordering::Relaxed);
if self.stopped.load(Ordering::Relaxed) >= 2 {
System::current().stop();
}
}
}
impl actix::Handler<Num> for MySyncActor {
type Result = ();
fn handle(&mut self, msg: Num, ctx: &mut Self::Context) {
self.msgs.fetch_add(msg.0, Ordering::Relaxed);
if self.stop {
ctx.stop();
}
}
}
#[test]
fn test_restart_sync_actor() {
let started = Arc::new(AtomicUsize::new(0));
let stopping = Arc::new(AtomicUsize::new(0));
let stopped = Arc::new(AtomicUsize::new(0));
let msgs = Arc::new(AtomicUsize::new(0));
let started1 = Arc::clone(&started);
let stopping1 = Arc::clone(&stopping);
let stopped1 = Arc::clone(&stopped);
let msgs1 = Arc::clone(&msgs);
let sys = System::new();
sys.block_on(async move {
let addr = SyncArbiter::start(1, move || MySyncActor {
started: Arc::clone(&started1),
stopping: Arc::clone(&stopping1),
stopped: Arc::clone(&stopped1),
msgs: Arc::clone(&msgs1),
stop: started1.load(Ordering::Relaxed) == 0,
});
addr.do_send(Num(2));
actix_rt::spawn(async move {
let _ = addr.send(Num(4)).await;
});
});
sys.run().unwrap();
assert_eq!(started.load(Ordering::Relaxed), 2);
assert_eq!(stopping.load(Ordering::Relaxed), 2);
assert_eq!(stopped.load(Ordering::Relaxed), 2);
assert_eq!(msgs.load(Ordering::Relaxed), 6);
}
struct IntervalActor {
elapses_left: usize,
sender: mpsc::Sender<Instant>,
instant: Option<Instant>,
}
impl IntervalActor {
pub fn new(elapses_left: usize, sender: mpsc::Sender<Instant>) -> Self {
Self {
//We stop at 0, so add 1 to make number of intervals equal to elapses_left
elapses_left: elapses_left + 1,
sender,
instant: None,
}
}
}
impl Actor for IntervalActor {
type Context = actix::Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
self.instant = Some(Instant::now());
ctx.run_interval(Duration::from_millis(110), move |act, ctx| {
act.elapses_left -= 1;
if act.elapses_left == 0 {
act.sender
.send(act.instant.take().expect("To have Instant"))
.expect("To send result");
ctx.stop();
System::current().stop();
}
});
}
}
#[test]
fn test_run_interval() {
const MAX_WAIT: Duration = Duration::from_millis(10_000);
let (sender, receiver) = mpsc::channel();
std::thread::spawn(move || {
let sys = System::new();
sys.block_on(async move {
let _addr = IntervalActor::new(10, sender).start();
});
sys.run().unwrap();
});
let result = receiver
.recv_timeout(MAX_WAIT)
.expect("To receive response in time");
// We wait 10 intervals by ~100ms
assert_eq!(result.elapsed().as_secs(), 1);
}
|
#[cfg(feature = "fast_shanten")]
mod fast_hand_calculator;
pub mod hand;
pub mod riichi_error;
pub mod rules;
pub mod scores;
#[cfg(not(feature = "fast_shanten"))]
mod shanten;
mod shape_finder;
pub mod shapes;
pub mod table;
pub mod tile;
pub mod yaku;
|
use super::random_bytes;
use cipher::{ctr::AES_128_CTR, Cipher};
use encoding::base64::*;
use std::fs;
#[derive(Default)]
pub struct Key(Vec<u8>);
impl Key {
pub fn new() -> Key {
Key(random_bytes(16))
}
pub fn successive_encryption(&self) -> Vec<Vec<u8>> {
let pt_str = fs::read_to_string("challenges/data/chal19.txt").unwrap();
let all_pt: Vec<Vec<u8>> = pt_str
.lines()
.collect::<Vec<_>>()
.iter()
.map(|s| Base64::from_str(s).unwrap().as_bytes())
.collect();
let ctr_cipher = AES_128_CTR::new_with_nonce(0);
let mut all_ct: Vec<Vec<u8>> = vec![];
for pt in all_pt.iter() {
all_ct.push(ctr_cipher.encrypt(&self.0, pt));
}
all_ct
}
}
|
use std::error;
mod common;
#[test]
fn test_arg_error_display() {
let error = wordcount_core::Error::new(common::EXPECTED_ERROR);
assert_eq!(String::from(common::EXPECTED_ERROR), format!("{}", error));
}
#[test]
fn test_arg_error_debug() {
let error = wordcount_core::Error::new(common::EXPECTED_ERROR);
assert_eq!(String::from(common::EXPECTED_ERROR), format!("{:?}", error));
}
#[test]
fn test_parse_file_name() {
let empty_args = vec!["".to_string()].into_iter();
let dummy_args = vec!["1".to_string(), "2".to_string()].into_iter();
if wordcount_core::parse_file_name(empty_args).is_ok() {
panic!("unexpected success with empty arguments");
};
if let Err(error) = wordcount_core::parse_file_name(dummy_args) {
panic!("unexpected error: {}", error)
};
}
#[test]
fn test_config_new() {
if let Err(error) = wordcount_core::Config::new("test".as_bytes()) {
panic!("{}", error)
};
}
#[test]
fn test_wordcount_display() {
const EXPECTED_DISPLAY: &str =
"Words: 6\nLines: 3\nUnique words:\n\ttest3: 3\n\ttest2: 2\n\ttest1: 1\n";
let word_count = common::new_wordcount();
assert_eq!(String::from(EXPECTED_DISPLAY), format!("{}", word_count));
}
#[test]
fn test_wordcount_debug() {
const EXPECTED_DEBUG: &str =
"WordCount { total: 6, lines: 3, unique_words: [(\"test3\", 3), (\"test2\", 2), (\"test1\", 1)] }";
let word_count = common::new_wordcount();
assert_eq!(String::from(EXPECTED_DEBUG), format!("{:?}", word_count));
}
#[test]
fn test_count_words() -> Result<(), Box<dyn error::Error>> {
const INPUT: &str = "test1\ntest2 test2\ntest3 test3 test3\n";
let config = wordcount_core::Config::new(INPUT.as_bytes())?;
let word_count = wordcount_core::WordCount::new(config, sort_desc);
assert_eq!(
common::EXPECTED_TOTAL_WORDS,
word_count.total,
"unexpected total words"
);
assert_eq!(
common::EXPECTED_TOTAL_LINES,
word_count.lines,
"unexpected total lines"
);
assert_eq!(
common::EXPECTED_UNIQUE_WORDS,
word_count.unique_words.len(),
"unexpected unique words"
);
Ok(())
}
fn sort_desc(a: u32, b: u32) -> std::cmp::Ordering {
b.cmp(&a)
}
|
use crate::{Context, Krate};
use failure::Error;
use tame_gcs::objects::{InsertObjectOptional, Object};
pub fn to_gcs(ctx: &Context<'_>, source: bytes::Bytes, krate: &Krate) -> Result<(), Error> {
use bytes::{Buf, IntoBuf};
let content_len = source.len() as u64;
let insert_req = Object::insert_simple(
&(&ctx.gcs_bucket, &ctx.object_name(&krate)?),
source,
content_len,
Some(InsertObjectOptional {
content_type: Some("application/x-tar"),
..Default::default()
}),
)?;
let (parts, body) = insert_req.into_parts();
let uri = parts.uri.to_string();
let builder = ctx.client.post(&uri);
let request = builder
.headers(parts.headers)
.body(reqwest::Body::new(body.into_buf().reader()))
.build()?;
ctx.client.execute(request)?.error_for_status()?;
Ok(())
}
|
use crate::types_structs::{Enum, Struct, Trait};
///Supported types
#[derive(Debug)]
pub enum Types {
Struct,
Trait,
Enum,
}
#[derive(Debug)]
pub enum TypeHolder {
Struct(Struct),
Trait(Trait),
Enum(Enum),
}
impl TypeHolder {
pub fn generate_interface(&mut self) -> String {
match self {
TypeHolder::Trait(ref mut val) => val.generate_interface(),
TypeHolder::Struct(ref mut val) => val.generate_interface(),
TypeHolder::Enum(ref mut val) => val.generate_interface(),
}
}
pub fn types(&self) -> Vec<&String> {
let mut types = Vec::new();
match self {
TypeHolder::Struct(val) => {
val.extras
.iter()
.filter_map(|it| it.method_info.as_ref())
.for_each(|it| types.append(&mut it.all_types().collect::<Vec<&String>>()));
}
TypeHolder::Trait(val) => {
val.extras
.iter()
.filter_map(|it| it.method_info.as_ref())
.for_each(|it| types.append(&mut it.all_types().collect::<Vec<&String>>()));
}
_ => {
unimplemented!()
}
}
types
}
pub fn name(&self) -> &str {
match self {
TypeHolder::Struct(val) => val.name.as_str(),
TypeHolder::Trait(val) => val.name.as_str(),
TypeHolder::Enum(val) => val.name.as_str(),
}
}
}
///`Current` refers to just adding a new line\
/// `ShiftRight` refers to adding a new line and then a tab more than the previous line\
/// `ShiftLeft` refers to adding a new line and then a tab less than the previous line
#[derive(Debug)]
pub enum NewLineState {
Current,
ShiftRight,
ShiftLeft,
}
pub enum Delimiters {
Bracket,
Parenthesis,
}
|
use std::mem::MaybeUninit;
/// This crate contains methods for modifying arrays and converting
/// them to vectors and back.
use std::ptr;
/// This trait helps to join array with a new element.
pub trait Stick<T> {
type Target;
/// Appends an item to an array:
/// ```rust
/// # extern crate no_vec;
/// # use no_vec::Stick;
/// let arr: [u16; 2] = [123u16].stick(456);
/// ```
fn stick(self, item: T) -> Self::Target;
}
/// This trait helps to remove an item element from sized array.
pub trait Unstick<T> {
type Target;
/// Removes an item from an array:
/// ```rust
/// # extern crate no_vec;
/// # use no_vec::Unstick;
/// let (arr, item): ([u16; 1], u16) = [123u16, 456].unstick();
/// ```
fn unstick(self) -> (Self::Target, T);
}
/// Helps to covert `Vec<T>` to `[T]`.
pub trait Concrete<T>: Sized {
/// Converts from a vector to an array:
/// ```rust
/// # extern crate no_vec;
/// # use no_vec::Concrete;
/// let arr: Result<[u16; 2], Vec<u16>> = vec![123u16, 456].concrete();
/// ```
fn concrete(self) -> Result<T, Self>;
}
/// Helps to covert `[T]` into `Vec<T>`.
pub trait Melt<T> {
/// Converts from an array to a vector:
/// ```rust
/// # extern crate no_vec;
/// # use no_vec::Melt;
/// let vec: Vec<u16> = [123u16, 456].melt();
/// ```
fn melt(self) -> Vec<T>;
}
macro_rules! impl_stick_unstick {
($from:expr, $to:expr) => {
impl<T> Stick<T> for [T; $from] {
type Target = [T; $to];
fn stick(self, item: T) -> Self::Target {
unsafe {
let mut result: Self::Target = MaybeUninit::uninit().assume_init();
ptr::copy(self.as_ptr(), result.as_mut_ptr(), $from);
result[$from] = item;
result
}
}
}
impl<T> Unstick<T> for [T; $to] {
type Target = [T; $from];
fn unstick(mut self) -> (Self::Target, T) {
unsafe {
let mut result: Self::Target = MaybeUninit::uninit().assume_init();
ptr::copy(self.as_ptr(), result.as_mut_ptr(), $from);
let mut item: T = MaybeUninit::uninit().assume_init();
ptr::swap(&mut item, &mut self[$from]);
(result, item)
}
}
}
impl<T> Concrete<[T; $from]> for Vec<T> {
fn concrete(self) -> Result<[T; $from], Self> {
if self.len() == $from {
unsafe {
let mut result: [T; $from] = MaybeUninit::uninit().assume_init();
ptr::copy(self.as_ptr(), result.as_mut_ptr(), $from);
drop(self);
Ok(result)
}
} else {
Err(self)
}
}
}
impl<T> Melt<T> for [T; $from] {
fn melt(self) -> Vec<T> {
let boxed: Box<[T]> = Box::new(self);
boxed.into_vec()
}
}
};
}
macro_rules! impl_stick_unstick_all {
() => { };
($last:expr ,) => { };
($from:expr , $to:expr , $($qnt:expr,)*) => {
impl_stick_unstick!($from, $to);
impl_stick_unstick_all!($to, $( $qnt, )*);
};
}
impl_stick_unstick_all!(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32,
);
#[cfg(test)]
mod tests {
use {Concrete, Melt, Stick, Unstick};
#[test]
fn test_stick_and_unstick() {
let arr = [123u16].stick(321);
assert_eq!(arr, [123, 321]);
let arr = arr.stick(999);
assert_eq!(arr, [123, 321, 999]);
let mut vec: Vec<u16> = arr.melt();
vec.push(111);
let arr: [u16; 4] = vec.concrete().unwrap();
assert_eq!(arr, [123, 321, 999, 111]);
let (arr, item) = arr.unstick();
assert_eq!(arr, [123, 321, 999]);
assert_eq!(item, 111);
let (arr, item) = arr.unstick();
assert_eq!(arr, [123, 321]);
assert_eq!(item, 999);
let (arr, item) = arr.unstick();
assert_eq!(arr, [123]);
assert_eq!(item, 321);
}
}
|
use crate::hlist::*;
use core::cell::UnsafeCell;
pub unsafe trait Identifier {
type Id;
fn id(&self) -> Self::Id;
fn check_id(&self, id: &Self::Id) -> bool;
}
pub unsafe trait Transparent {}
#[repr(transparent)]
pub struct Owner<I> {
pub ident: I,
}
#[repr(C)]
pub struct ICell<Id, T: ?Sized> {
id: Id,
value: UnsafeCell<T>,
}
unsafe impl<Id: Sync, T: Send + Sync> Sync for ICell<Id, T> {}
impl<O> Owner<O> {
pub const fn new(ident: O) -> Self {
Self { ident }
}
}
impl<I: Identifier> Owner<I> {
pub fn cell<T>(&self, value: T) -> ICell<I::Id, T> {
unsafe { ICell::from_raw_parts(self.ident.id(), value) }
}
pub fn read<'a, T: ?Sized>(&'a self, cell: &'a ICell<I::Id, T>) -> &'a T {
assert!(
self.ident.check_id(cell.id()),
"Tried to read using an unrelated owner"
);
unsafe { &*cell.as_ptr() }
}
pub fn swap<T>(&mut self, a: &ICell<I::Id, T>, b: &ICell<I::Id, T>) {
assert!(
self.ident.check_id(a.id()) && self.ident.check_id(b.id()),
"Tried to swap using an unrelated owner"
);
unsafe { a.as_ptr().swap(b.as_ptr()) }
}
pub fn write<'a, T: ?Sized>(&'a mut self, cell: &'a ICell<I::Id, T>) -> &'a mut T {
assert!(
self.ident.check_id(cell.id()),
"Tried to write using an unrelated owner"
);
unsafe { &mut *cell.as_ptr() }
}
pub fn write_2<'a, T: ?Sized, U: ?Sized>(
&'a mut self,
a: &'a ICell<I::Id, T>,
b: &'a ICell<I::Id, U>,
) -> (&'a mut T, &'a mut U) {
write_all!(self => a, b)
}
pub fn write_3<'a, T: ?Sized, U: ?Sized, V: ?Sized>(
&'a mut self,
a: &'a ICell<I::Id, T>,
b: &'a ICell<I::Id, U>,
c: &'a ICell<I::Id, V>,
) -> (&'a mut T, &'a mut U, &'a mut V) {
write_all!(self => a, b, c)
}
pub fn write_4<'a, T: ?Sized, U: ?Sized, V: ?Sized, W: ?Sized>(
&'a mut self,
a: &'a ICell<I::Id, T>,
b: &'a ICell<I::Id, U>,
c: &'a ICell<I::Id, V>,
d: &'a ICell<I::Id, W>,
) -> (&'a mut T, &'a mut U, &'a mut V, &'a mut W) {
write_all!(self => a, b, c, d)
}
#[doc(hidden)]
pub fn write_all<'a, C>(&'a mut self, cells: C) -> C::Output
where
C: GetMut<'a, I>,
{
cells.get_mut(&self.ident)
}
}
impl<Id, T> ICell<Id, T> {
pub const unsafe fn from_raw_parts(id: Id, value: T) -> Self {
Self {
id,
value: UnsafeCell::new(value),
}
}
pub fn retag<NewId>(self, new_id: NewId) -> ICell<NewId, T> {
ICell {
id: new_id,
value: self.value,
}
}
pub fn into_inner(self) -> T {
self.value.into_inner()
}
}
impl<Id, T: ?Sized> ICell<Id, T> {
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.value.get() }
}
pub fn as_ptr(&self) -> *mut T {
self.value.get()
}
pub const fn id(&self) -> &Id {
&self.id
}
}
impl<Id: Transparent, T> ICell<Id, T> {
pub fn new(value: T) -> Self {
assert_eq!(core::mem::size_of::<Id>(), 0);
// Safety
//
// this is safe because `Id: Transparent`, meaning there are no
// safety constraints on creating an `Id`
#[allow(deprecated)]
unsafe {
Self::from_raw_parts(core::mem::uninitialized(), value)
}
}
pub fn from_mut_slice(value: &mut [T]) -> &mut [Self] {
assert_eq!(core::mem::size_of::<Id>(), 0);
#[allow(clippy::transmute_ptr_to_ptr)]
unsafe {
core::mem::transmute(value)
}
}
}
impl<Id: Transparent, T: ?Sized> ICell<Id, T> {
pub fn from_mut(value: &mut T) -> &mut Self {
assert_eq!(core::mem::size_of::<Id>(), 0);
#[allow(clippy::transmute_ptr_to_ptr)]
unsafe {
core::mem::transmute(value)
}
}
}
impl<Id: Transparent, T> ICell<Id, [T]> {
pub fn transpose(value: &mut Self) -> &mut [ICell<Id, T>] {
assert_eq!(core::mem::size_of::<Id>(), 0);
#[allow(clippy::transmute_ptr_to_ptr)]
unsafe {
core::mem::transmute(value)
}
}
pub fn as_mut_slice(&mut self) -> &mut [T] {
assert_eq!(core::mem::size_of::<Id>(), 0);
#[allow(clippy::transmute_ptr_to_ptr)]
unsafe {
core::mem::transmute(self)
}
}
}
|
use macroquad::prelude::*;
pub const GAME_SIZE: Vec2 = const_vec2!([514., 256.]);
pub const GRAVITY: f32 = 30f32;
pub const MOVE_SPEED: f32 = 200f32;
pub const MAX_JUMP_STRENGTH: f32 = 12f32;
|
mod mem_map;
use sinks::*;
use self::mem_map::*;
// Docs claim the sample rate is 41.7khz, but my calculations indicate it should be 41666.66hz repeating
// (see SAMPLE_CLOCK_PERIOD calculation below), so we take the nearest whole-number sample rate to that.
// Note that the documentation rounds values in a lot of places, so that's probably what happened here.
pub const SAMPLE_RATE: usize = 41667;
// 20mhz / 41.7khz = ~480 clocks
const SAMPLE_CLOCK_PERIOD: usize = 480;
// 20mhz / 260.4hz = ~76805 clocks
const DURATION_CLOCK_PERIOD: usize = 76805;
// 20mhz / 65.1hz = ~307218 clocks
const ENVELOPE_CLOCK_PERIOD: usize = 307218;
// 20mhz / 5mhz = 4 clocks
const FREQUENCY_CLOCK_PERIOD: usize = 4;
// 20mhz / 1041.6hz = ~19200 clocks
const SWEEP_MOD_SMALL_PERIOD: usize = 19200;
// 20mhz / 130.2hz = ~153600 clocks
const SWEEP_MOD_LARGE_PERIOD: usize = 153600;
// 20mhz / 500khz = 40 clocks
const NOISE_CLOCK_PERIOD: usize = 40;
const NUM_WAVE_TABLE_WORDS: usize = 32;
const NUM_WAVE_TABLES: usize = 5;
const TOTAL_WAVE_TABLE_SIZE: usize = NUM_WAVE_TABLE_WORDS * NUM_WAVE_TABLES;
const NUM_MOD_TABLE_WORDS: usize = 32;
#[derive(Default)]
struct PlayControlReg {
enable: bool,
use_duration: bool,
duration: usize,
duration_counter: usize,
}
impl PlayControlReg {
fn write(&mut self, value: u8) {
self.enable = (value & 0x80) != 0;
self.use_duration = (value & 0x20) != 0;
self.duration = (value & 0x1f) as _;
if self.use_duration {
self.duration_counter = 0;
}
}
fn duration_clock(&mut self) {
if self.enable && self.use_duration {
self.duration_counter += 1;
if self.duration_counter > self.duration {
self.enable = false;
}
}
}
}
#[derive(Default)]
struct VolumeReg {
left: usize,
right: usize,
}
impl VolumeReg {
fn write(&mut self, value: u8) {
self.left = (value >> 4) as _;
self.right = (value & 0x0f) as _;
}
}
#[derive(Default)]
struct Envelope {
reg_data_reload: usize,
reg_data_direction: bool,
reg_data_step_interval: usize,
reg_control_repeat: bool,
reg_control_enable: bool,
level: usize,
envelope_counter: usize,
}
impl Envelope {
fn write_data_reg(&mut self, value: u8) {
self.reg_data_reload = (value >> 4) as _;
self.reg_data_direction = (value & 0x08) != 0;
self.reg_data_step_interval = (value & 0x07) as _;
self.level = self.reg_data_reload;
}
fn write_control_reg(&mut self, value: u8) {
self.reg_control_repeat = (value & 0x02) != 0;
self.reg_control_enable = (value & 0x01) != 0;
}
fn level(&self) -> usize {
self.level
}
fn envelope_clock(&mut self) {
if self.reg_control_enable {
self.envelope_counter += 1;
if self.envelope_counter > self.reg_data_step_interval {
self.envelope_counter = 0;
if self.reg_data_direction && self.level < 15 {
self.level += 1;
} else if !self.reg_data_direction && self.level > 0 {
self.level -= 1;
} else if self.reg_control_repeat {
self.level = self.reg_data_reload;
}
}
}
}
}
trait Voice {
fn reg_play_control(&self) -> &PlayControlReg;
fn reg_volume(&self) -> &VolumeReg;
fn envelope(&self) -> &Envelope;
}
#[derive(Default)]
struct StandardVoice {
reg_play_control: PlayControlReg,
reg_volume: VolumeReg,
reg_frequency_low: usize,
reg_frequency_high: usize,
envelope: Envelope,
reg_pcm_wave: usize,
frequency_counter: usize,
phase: usize,
}
impl StandardVoice {
fn write_play_control_reg(&mut self, value: u8) {
self.reg_play_control.write(value);
if self.reg_play_control.enable {
self.envelope.envelope_counter = 0;
self.frequency_counter = 0;
self.phase = 0;
}
}
fn write_volume_reg(&mut self, value: u8) {
self.reg_volume.write(value);
}
fn write_frequency_low_reg(&mut self, value: u8) {
self.reg_frequency_low = value as _;
}
fn write_frequency_high_reg(&mut self, value: u8) {
self.reg_frequency_high = (value & 0x07) as _;
}
fn write_envelope_data_reg(&mut self, value: u8) {
self.envelope.write_data_reg(value);
}
fn write_envelope_control_reg(&mut self, value: u8) {
self.envelope.write_control_reg(value);
}
fn write_pcm_wave_reg(&mut self, value: u8) {
self.reg_pcm_wave = (value & 0x07) as _;
}
fn frequency_clock(&mut self) {
self.frequency_counter += 1;
if self.frequency_counter >= 2048 - ((self.reg_frequency_high << 8) | self.reg_frequency_low) {
self.frequency_counter = 0;
self.phase = (self.phase + 1) & (NUM_WAVE_TABLE_WORDS - 1);
}
}
fn output(&self, wave_tables: &[u8]) -> usize {
if self.reg_pcm_wave > 4 {
return 0;
}
wave_tables[self.reg_pcm_wave * NUM_WAVE_TABLE_WORDS + self.phase] as _
}
}
impl Voice for StandardVoice {
fn reg_play_control(&self) -> &PlayControlReg {
&self.reg_play_control
}
fn reg_volume(&self) -> &VolumeReg {
&self.reg_volume
}
fn envelope(&self) -> &Envelope {
&self.envelope
}
}
#[derive(Default)]
struct SweepModVoice {
reg_play_control: PlayControlReg,
reg_volume: VolumeReg,
reg_frequency_low: usize,
reg_frequency_high: usize,
frequency_low: usize,
frequency_high: usize,
next_frequency_low: usize,
next_frequency_high: usize,
envelope: Envelope,
reg_sweep_mod_enable: bool,
reg_mod_repeat: bool,
reg_function: bool,
reg_sweep_mod_base_interval: bool,
reg_sweep_mod_interval: usize,
reg_sweep_direction: bool,
reg_sweep_shift_amount: usize,
reg_pcm_wave: usize,
frequency_counter: usize,
phase: usize,
sweep_mod_counter: usize,
mod_phase: usize,
}
impl SweepModVoice {
fn write_play_control_reg(&mut self, value: u8) {
self.reg_play_control.write(value);
if self.reg_play_control.enable {
self.envelope.envelope_counter = 0;
self.frequency_counter = 0;
self.phase = 0;
self.sweep_mod_counter = 0;
self.mod_phase = 0;
}
}
fn write_volume_reg(&mut self, value: u8) {
self.reg_volume.write(value);
}
fn write_frequency_low_reg(&mut self, value: u8) {
self.reg_frequency_low = value as _;
self.next_frequency_low = self.reg_frequency_low;
}
fn write_frequency_high_reg(&mut self, value: u8) {
self.reg_frequency_high = (value & 0x07) as _;
self.next_frequency_high = self.reg_frequency_high;
}
fn write_envelope_data_reg(&mut self, value: u8) {
self.envelope.write_data_reg(value);
}
fn write_envelope_sweep_mod_control_reg(&mut self, value: u8) {
self.envelope.write_control_reg(value);
self.reg_sweep_mod_enable = ((value >> 6) & 0x01) != 0;
self.reg_mod_repeat = ((value >> 5) & 0x01) != 0;
self.reg_function = ((value >> 4) & 0x01) != 0;
}
fn write_sweep_mod_data_reg(&mut self, value: u8) {
self.reg_sweep_mod_base_interval = ((value >> 7) & 0x01) != 0;
self.reg_sweep_mod_interval = ((value >> 4) & 0x07) as _;
self.reg_sweep_direction = ((value >> 3) & 0x01) != 0;
self.reg_sweep_shift_amount = (value & 0x07) as _;
}
fn write_pcm_wave_reg(&mut self, value: u8) {
self.reg_pcm_wave = (value & 0x07) as _;
}
fn frequency_clock(&mut self) {
self.frequency_counter += 1;
if self.frequency_counter >= 2048 - ((self.frequency_high << 8) | self.frequency_low) {
self.frequency_counter = 0;
self.phase = (self.phase + 1) & (NUM_WAVE_TABLE_WORDS - 1);
}
}
fn sweep_mod_clock(&mut self, mod_table: &[i8]) {
self.sweep_mod_counter += 1;
if self.sweep_mod_counter >= self.reg_sweep_mod_interval {
self.sweep_mod_counter = 0;
self.frequency_low = self.next_frequency_low;
self.frequency_high = self.next_frequency_high;
let mut freq = (self.frequency_high << 8) | self.frequency_low;
if freq >= 2048 {
self.reg_play_control.enable = false;
}
if !self.reg_play_control.enable || !self.reg_sweep_mod_enable || self.reg_sweep_mod_interval == 0 {
return;
}
match self.reg_function {
false => {
// Sweep
let sweep_value = freq >> self.reg_sweep_shift_amount;
freq = match self.reg_sweep_direction {
false => freq.wrapping_sub(sweep_value),
true => freq.wrapping_add(sweep_value)
};
}
true => {
// Mod
let reg_freq = (self.reg_frequency_high << 8) | self.reg_frequency_low;
freq = reg_freq.wrapping_add(mod_table[self.mod_phase] as _) & 0x07ff;
const MAX_MOD_PHASE: usize = NUM_MOD_TABLE_WORDS - 1;
self.mod_phase = match (self.reg_mod_repeat, self.mod_phase) {
(false, MAX_MOD_PHASE) => MAX_MOD_PHASE,
_ => (self.mod_phase + 1) & MAX_MOD_PHASE
};
}
}
self.next_frequency_low = freq & 0xff;
self.next_frequency_high = (freq >> 8) & 0x07;
}
}
fn output(&self, wave_tables: &[u8]) -> usize {
if self.reg_pcm_wave > 4 {
return 0;
}
wave_tables[self.reg_pcm_wave * NUM_WAVE_TABLE_WORDS + self.phase] as _
}
}
impl Voice for SweepModVoice {
fn reg_play_control(&self) -> &PlayControlReg {
&self.reg_play_control
}
fn reg_volume(&self) -> &VolumeReg {
&self.reg_volume
}
fn envelope(&self) -> &Envelope {
&self.envelope
}
}
#[derive(Default)]
struct NoiseVoice {
reg_play_control: PlayControlReg,
reg_volume: VolumeReg,
reg_frequency_low: usize,
reg_frequency_high: usize,
envelope: Envelope,
reg_noise_control: usize,
frequency_counter: usize,
shift: usize,
output: usize,
}
impl NoiseVoice {
fn write_play_control_reg(&mut self, value: u8) {
self.reg_play_control.write(value);
if self.reg_play_control.enable {
self.envelope.envelope_counter = 0;
self.frequency_counter = 0;
self.shift = 0x7fff;
}
}
fn write_volume_reg(&mut self, value: u8) {
self.reg_volume.write(value);
}
fn write_frequency_low_reg(&mut self, value: u8) {
self.reg_frequency_low = value as _;
}
fn write_frequency_high_reg(&mut self, value: u8) {
self.reg_frequency_high = (value & 0x07) as _;
}
fn write_envelope_data_reg(&mut self, value: u8) {
self.envelope.write_data_reg(value);
}
fn write_envelope_noise_control_reg(&mut self, value: u8) {
self.reg_noise_control = ((value >> 4) & 0x07) as _;
self.envelope.write_control_reg(value);
}
fn noise_clock(&mut self) {
self.frequency_counter += 1;
if self.frequency_counter >= 2048 - ((self.reg_frequency_high << 8) | self.reg_frequency_low) {
self.frequency_counter = 0;
let lhs = self.shift >> 7;
let rhs_bit_index = match self.reg_noise_control {
0 => 14,
1 => 10,
2 => 13,
3 => 4,
4 => 8,
5 => 6,
6 => 9,
_ => 11
};
let rhs = self.shift >> rhs_bit_index;
let xor_bit = (lhs ^ rhs) & 0x01;
self.shift = ((self.shift << 1) | xor_bit) & 0x7fff;
let output_bit = (!xor_bit) & 0x01;
self.output = match output_bit {
0 => 0,
_ => 0x3f
};
}
}
fn output(&self) -> usize {
self.output
}
}
impl Voice for NoiseVoice {
fn reg_play_control(&self) -> &PlayControlReg {
&self.reg_play_control
}
fn reg_volume(&self) -> &VolumeReg {
&self.reg_volume
}
fn envelope(&self) -> &Envelope {
&self.envelope
}
}
pub struct Vsu {
wave_tables: Box<[u8]>,
mod_table: Box<[i8]>,
voice1: StandardVoice,
voice2: StandardVoice,
voice3: StandardVoice,
voice4: StandardVoice,
voice5: SweepModVoice,
voice6: NoiseVoice,
duration_clock_counter: usize,
envelope_clock_counter: usize,
frequency_clock_counter: usize,
sweep_mod_clock_counter: usize,
noise_clock_counter: usize,
sample_clock_counter: usize,
}
impl Vsu {
pub fn new() -> Vsu {
Vsu {
wave_tables: vec![0; TOTAL_WAVE_TABLE_SIZE].into_boxed_slice(),
mod_table: vec![0; NUM_MOD_TABLE_WORDS].into_boxed_slice(),
voice1: StandardVoice::default(),
voice2: StandardVoice::default(),
voice3: StandardVoice::default(),
voice4: StandardVoice::default(),
voice5: SweepModVoice::default(),
voice6: NoiseVoice::default(),
duration_clock_counter: 0,
envelope_clock_counter: 0,
frequency_clock_counter: 0,
sweep_mod_clock_counter: 0,
noise_clock_counter: 0,
sample_clock_counter: 0,
}
}
pub fn read_byte(&self, addr: u32) -> u8 {
logln!(Log::Vsu, "WARNING: Attempted read byte from VSU (addr: 0x{:08x})", addr);
0
}
pub fn write_byte(&mut self, addr: u32, value: u8) {
match addr {
PCM_WAVE_TABLE_0_START ... PCM_WAVE_TABLE_0_END => {
if !self.are_channels_active() {
self.wave_tables[((addr - PCM_WAVE_TABLE_0_START) / 4 + 0x00) as usize] = value & 0x3f;
}
}
PCM_WAVE_TABLE_1_START ... PCM_WAVE_TABLE_1_END => {
if !self.are_channels_active() {
self.wave_tables[((addr - PCM_WAVE_TABLE_1_START) / 4 + 0x20) as usize] = value & 0x3f;
}
}
PCM_WAVE_TABLE_2_START ... PCM_WAVE_TABLE_2_END => {
if !self.are_channels_active() {
self.wave_tables[((addr - PCM_WAVE_TABLE_2_START) / 4 + 0x40) as usize] = value & 0x3f;
}
}
PCM_WAVE_TABLE_3_START ... PCM_WAVE_TABLE_3_END => {
if !self.are_channels_active() {
self.wave_tables[((addr - PCM_WAVE_TABLE_3_START) / 4 + 0x60) as usize] = value & 0x3f;
}
}
PCM_WAVE_TABLE_4_START ... PCM_WAVE_TABLE_4_END => {
if !self.are_channels_active() {
self.wave_tables[((addr - PCM_WAVE_TABLE_4_START) / 4 + 0x80) as usize] = value & 0x3f;
}
}
MOD_TABLE_START ... MOD_TABLE_END => {
if !self.voice5.reg_play_control.enable {
self.mod_table[((addr - MOD_TABLE_START) / 4) as usize] = value as _;
}
}
VOICE_1_PLAY_CONTROL => self.voice1.write_play_control_reg(value),
VOICE_1_VOLUME => self.voice1.write_volume_reg(value),
VOICE_1_FREQUENCY_LOW => self.voice1.write_frequency_low_reg(value),
VOICE_1_FREQUENCY_HIGH => self.voice1.write_frequency_high_reg(value),
VOICE_1_ENVELOPE_DATA => self.voice1.write_envelope_data_reg(value),
VOICE_1_ENVELOPE_CONTROL => self.voice1.write_envelope_control_reg(value),
VOICE_1_PCM_WAVE => self.voice1.write_pcm_wave_reg(value),
VOICE_2_PLAY_CONTROL => self.voice2.write_play_control_reg(value),
VOICE_2_VOLUME => self.voice2.write_volume_reg(value),
VOICE_2_FREQUENCY_LOW => self.voice2.write_frequency_low_reg(value),
VOICE_2_FREQUENCY_HIGH => self.voice2.write_frequency_high_reg(value),
VOICE_2_ENVELOPE_DATA => self.voice2.write_envelope_data_reg(value),
VOICE_2_ENVELOPE_CONTROL => self.voice2.write_envelope_control_reg(value),
VOICE_2_PCM_WAVE => self.voice2.write_pcm_wave_reg(value),
VOICE_3_PLAY_CONTROL => self.voice3.write_play_control_reg(value),
VOICE_3_VOLUME => self.voice3.write_volume_reg(value),
VOICE_3_FREQUENCY_LOW => self.voice3.write_frequency_low_reg(value),
VOICE_3_FREQUENCY_HIGH => self.voice3.write_frequency_high_reg(value),
VOICE_3_ENVELOPE_DATA => self.voice3.write_envelope_data_reg(value),
VOICE_3_ENVELOPE_CONTROL => self.voice3.write_envelope_control_reg(value),
VOICE_3_PCM_WAVE => self.voice3.write_pcm_wave_reg(value),
VOICE_4_PLAY_CONTROL => self.voice4.write_play_control_reg(value),
VOICE_4_VOLUME => self.voice4.write_volume_reg(value),
VOICE_4_FREQUENCY_LOW => self.voice4.write_frequency_low_reg(value),
VOICE_4_FREQUENCY_HIGH => self.voice4.write_frequency_high_reg(value),
VOICE_4_ENVELOPE_DATA => self.voice4.write_envelope_data_reg(value),
VOICE_4_ENVELOPE_CONTROL => self.voice4.write_envelope_control_reg(value),
VOICE_4_PCM_WAVE => self.voice4.write_pcm_wave_reg(value),
VOICE_5_PLAY_CONTROL => self.voice5.write_play_control_reg(value),
VOICE_5_VOLUME => self.voice5.write_volume_reg(value),
VOICE_5_FREQUENCY_LOW => self.voice5.write_frequency_low_reg(value),
VOICE_5_FREQUENCY_HIGH => self.voice5.write_frequency_high_reg(value),
VOICE_5_ENVELOPE_DATA => self.voice5.write_envelope_data_reg(value),
VOICE_5_ENVELOPE_SWEEP_MOD_CONTROL => self.voice5.write_envelope_sweep_mod_control_reg(value),
VOICE_5_SWEEP_MOD_DATA => self.voice5.write_sweep_mod_data_reg(value),
VOICE_5_PCM_WAVE => self.voice5.write_pcm_wave_reg(value),
VOICE_6_PLAY_CONTROL => self.voice6.write_play_control_reg(value),
VOICE_6_VOLUME => self.voice6.write_volume_reg(value),
VOICE_6_FREQUENCY_LOW => self.voice6.write_frequency_low_reg(value),
VOICE_6_FREQUENCY_HIGH => self.voice6.write_frequency_high_reg(value),
VOICE_6_ENVELOPE_DATA => self.voice6.write_envelope_data_reg(value),
VOICE_6_ENVELOPE_NOISE_CONTROL => self.voice6.write_envelope_noise_control_reg(value),
SOUND_DISABLE_REG => {
if (value & 0x01) != 0 {
self.voice1.reg_play_control.enable = false;
self.voice2.reg_play_control.enable = false;
self.voice3.reg_play_control.enable = false;
self.voice4.reg_play_control.enable = false;
self.voice5.reg_play_control.enable = false;
self.voice6.reg_play_control.enable = false;
}
}
_ => logln!(Log::Vsu, "VSU write byte not yet implemented (addr: 0x{:08x}, value: 0x{:04x})", addr, value)
}
}
pub fn read_halfword(&self, addr: u32) -> u16 {
logln!(Log::Vsu, "WARNING: Attempted read halfword from VSU (addr: 0x{:08x})", addr);
0
}
pub fn write_halfword(&mut self, addr: u32, value: u16) {
let addr = addr & 0xfffffffe;
self.write_byte(addr, value as _);
}
pub fn cycles(&mut self, num_cycles: usize, audio_frame_sink: &mut Sink<AudioFrame>) {
for _ in 0..num_cycles {
self.duration_clock_counter += 1;
if self.duration_clock_counter >= DURATION_CLOCK_PERIOD {
self.duration_clock_counter = 0;
self.voice1.reg_play_control.duration_clock();
self.voice2.reg_play_control.duration_clock();
self.voice3.reg_play_control.duration_clock();
self.voice4.reg_play_control.duration_clock();
self.voice5.reg_play_control.duration_clock();
self.voice6.reg_play_control.duration_clock();
}
self.envelope_clock_counter += 1;
if self.envelope_clock_counter >= ENVELOPE_CLOCK_PERIOD {
self.envelope_clock_counter = 0;
self.voice1.envelope.envelope_clock();
self.voice2.envelope.envelope_clock();
self.voice3.envelope.envelope_clock();
self.voice4.envelope.envelope_clock();
self.voice5.envelope.envelope_clock();
self.voice6.envelope.envelope_clock();
}
self.frequency_clock_counter += 1;
if self.frequency_clock_counter >= FREQUENCY_CLOCK_PERIOD {
self.frequency_clock_counter = 0;
self.voice1.frequency_clock();
self.voice2.frequency_clock();
self.voice3.frequency_clock();
self.voice4.frequency_clock();
self.voice5.frequency_clock();
}
self.sweep_mod_clock_counter += 1;
let sweep_mod_clock_period = match self.voice5.reg_sweep_mod_base_interval {
false => SWEEP_MOD_SMALL_PERIOD,
true => SWEEP_MOD_LARGE_PERIOD
};
if self.sweep_mod_clock_counter >= sweep_mod_clock_period {
self.sweep_mod_clock_counter = 0;
self.voice5.sweep_mod_clock(&self.mod_table);
}
self.noise_clock_counter += 1;
if self.noise_clock_counter >= NOISE_CLOCK_PERIOD {
self.noise_clock_counter = 0;
self.voice6.noise_clock();
}
self.sample_clock_counter += 1;
if self.sample_clock_counter >= SAMPLE_CLOCK_PERIOD {
self.sample_clock_counter = 0;
self.sample_clock(audio_frame_sink);
}
}
}
fn sample_clock(&mut self, audio_frame_sink: &mut Sink<AudioFrame>) {
let mut acc_left = 0;
let mut acc_right = 0;
fn mix_sample<V: Voice>(acc_left: &mut usize, acc_right: &mut usize, voice: &V, voice_output: usize) {
let (left, right) = if voice.reg_play_control().enable {
let envelope_level = voice.envelope().level();
let left_level = if voice.reg_volume().left == 0 || envelope_level == 0 {
0
} else {
((voice.reg_volume().left * envelope_level) >> 3) + 1
};
let right_level = if voice.reg_volume().right == 0 || envelope_level == 0 {
0
} else {
((voice.reg_volume().right * envelope_level) >> 3) + 1
};
let output_left = (voice_output * left_level) >> 1;
let output_right = (voice_output * right_level) >> 1;
(output_left, output_right)
} else {
(0, 0)
};
*acc_left += left;
*acc_right += right;
}
mix_sample(&mut acc_left, &mut acc_right, &self.voice1, self.voice1.output(&self.wave_tables));
mix_sample(&mut acc_left, &mut acc_right, &self.voice2, self.voice2.output(&self.wave_tables));
mix_sample(&mut acc_left, &mut acc_right, &self.voice3, self.voice3.output(&self.wave_tables));
mix_sample(&mut acc_left, &mut acc_right, &self.voice4, self.voice4.output(&self.wave_tables));
mix_sample(&mut acc_left, &mut acc_right, &self.voice5, self.voice5.output(&self.wave_tables));
mix_sample(&mut acc_left, &mut acc_right, &self.voice6, self.voice6.output());
let output_left = ((acc_left & 0xfff8) << 2) as i16;
let output_right = ((acc_right & 0xfff8) << 2) as i16;
audio_frame_sink.append((output_left, output_right));
}
fn are_channels_active(&self) -> bool {
self.voice1.reg_play_control.enable ||
self.voice2.reg_play_control.enable ||
self.voice3.reg_play_control.enable ||
self.voice4.reg_play_control.enable ||
self.voice5.reg_play_control.enable ||
self.voice6.reg_play_control.enable
}
}
|
use std::io;
use std::io::Write;
pub fn solution(){
let mut name: String = String::new();
let mut age: String = String::new();
let mut reddit_name: String = String::new();
print!("What is your name? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut name).unwrap();
print!("What is your age(years)? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut age).unwrap();
print!("What is your reddit name? ");
io::stdout().flush().unwrap();
io::stdin().read_line(&mut reddit_name).unwrap();
println!("your name is {}, you are {} years old, and your username is {}",name.trim(),age.trim(),reddit_name.trim());
} |
use nom::{
error::{ErrorKind, ParseError},
Compare, CompareResult, Err, ExtendInto, FindSubstring, FindToken, IResult, InputIter,
InputLength, InputTake, InputTakeAtPosition, Needed, Offset, Slice,
};
use std::convert::TryInto;
use std::ops;
use std::str::{CharIndices, Chars};
use std::u32;
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Serialize)]
pub struct Position {
line: u32,
character: u32,
}
impl Position {
pub fn new(line: u32, character: u32) -> Position {
Position { line, character }
}
pub fn translate(&self, line_delta: u32, character_delta: u32) -> Position {
Position {
line: self.line + line_delta,
character: self.character + character_delta,
}
}
pub fn max() -> Position {
Position {
line: u32::MAX,
character: u32::MAX,
}
}
pub fn get_line(&self) -> u32 {
self.line
}
pub fn get_character(&self) -> u32 {
self.character
}
}
#[derive(Debug, PartialEq, Clone, Copy, Serialize)]
pub struct StrRange {
pub start: Position,
pub end: Position,
}
impl StrRange {
pub fn new(start: Position, end: Position) -> StrRange {
StrRange { start, end }
}
pub fn new_empty() -> StrRange {
StrRange::new(Position::new(0, 0), Position::max())
}
pub fn from_input(input: &Input) -> StrRange {
StrRange {
start: input.start,
end: input.end,
}
}
pub fn from_start<'a>(src: &'a str, start: Position) -> StrRange {
let (line_count, end_col) = Input::get_line_col(src);
let end = if line_count == 1 {
Position::new(start.line, end_col + start.character)
} else {
Position::new(start.line + line_count - 1, end_col)
};
StrRange::new(start, end)
}
pub fn contain(&self, pos: Position) -> bool {
self.start <= pos && pos <= self.end
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Input<'a> {
pub src: &'a str,
pub start: Position,
pub end: Position,
}
impl<'a> Input<'a> {
pub fn new(src: &'a str, start: Position, end: Position) -> Input<'a> {
Input { src, start, end }
}
pub fn new_u32(
src: &'a str,
start_line: u32,
start_ch: u32,
end_line: u32,
end_ch: u32,
) -> Input<'a> {
Input {
src,
start: Position::new(start_line, start_ch),
end: Position::new(end_line, end_ch),
}
}
pub fn new_with_str(src: &'a str) -> Input<'a> {
Input {
src,
start: Position::new(0, 0),
end: Position::new(u32::MAX, u32::MAX),
}
}
pub fn new_with_start(src: &'a str, start: Position) -> Input<'a> {
let (line_count, end_col) = Self::get_line_col(src);
let end = if line_count == 1 {
Position::new(start.line, end_col + start.character)
} else {
Position::new(start.line + line_count - 1, end_col)
};
Input::new(src, start, end)
}
pub fn new_empty() -> Input<'a> {
Input::new("", Position::new(0, 0), Position::max())
}
pub fn len(&self) -> usize {
self.src.len()
}
pub fn forward(&self, delta: usize) -> Input<'a> {
let delta_str = &self.src[..delta];
let start_input = Self::new_with_start(delta_str, self.start);
Input::new(&self.src[delta..], start_input.end, self.end)
}
}
impl<'a> Input<'a> {
fn get_line_col(dest_str: &'a str) -> (u32, u32) {
let mut line_count = 0u32;
let mut last_line = "";
for line in dest_str.split('\n') {
line_count += 1;
last_line = line;
}
let end_col: u32 = last_line.chars().count().try_into().unwrap();
(line_count, end_col)
}
pub fn slice_start(&self, count: usize) -> Result<Self, Err<ErrorKind>> {
let dest_str = self.src.get(..count);
if dest_str.is_none() {
return Err(Err::Incomplete(Needed::Unknown));
}
let dest_str = dest_str.unwrap();
let start_input = Self::new_with_start(dest_str, self.start);
Ok(start_input)
}
pub fn slice_split(&self, count: usize) -> Result<(Self, Self), Err<ErrorKind>> {
let input = self.slice_start(count)?;
let second_str = self.src.get(count..);
if let Some(second_str) = second_str {
Ok((
Input::new(second_str, input.end, self.end),
Input::new(input.src, self.start, input.end),
))
} else {
Err(Err::Incomplete(Needed::Unknown))
}
}
}
const WHITESPACES: &str =
" $\n";
impl<'a> InputTake for Input<'a> {
fn take(&self, count: usize) -> Self {
let dest_str = self.src.get(..count).or(WHITESPACES.get(..count)).unwrap();
Self::new_with_start(dest_str, self.start)
}
fn take_split(&self, count: usize) -> (Self, Self) {
let input = self.take(count);
let second_str = self.src.get(count..).or(Some("")).unwrap();
(
Input::new(second_str, input.end, self.end),
Input::new(input.src, self.start, input.end),
)
}
}
impl<'a> InputLength for Input<'a> {
#[inline]
fn input_len(&self) -> usize {
self.src.len()
}
}
impl<'a> Offset for Input<'a> {
fn offset(&self, second: &Self) -> usize {
let fst = self.src.as_ptr();
let snd = second.src.as_ptr();
snd as usize - fst as usize
}
}
// impl<'a> AsBytes for Input<'a> {
// #[inline(always)]
// fn as_bytes(&self) -> &[u8] {
// <str as AsBytes>::as_bytes(self.src)
// }
// }
impl<'a> InputIter for Input<'a> {
type Item = char;
type Iter = CharIndices<'a>;
type IterElem = Chars<'a>;
#[inline]
fn iter_indices(&self) -> Self::Iter {
self.src.char_indices()
}
#[inline]
fn iter_elements(&self) -> Self::IterElem {
self.src.chars()
}
fn position<P>(&self, predicate: P) -> Option<usize>
where
P: Fn(Self::Item) -> bool,
{
self.src.position(predicate)
}
#[inline]
fn slice_index(&self, count: usize) -> Option<usize> {
self.src.slice_index(count)
}
}
impl<'a> InputTakeAtPosition for Input<'a> {
type Item = char;
fn split_at_position<P, E: ParseError<Self>>(&self, predicate: P) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.src.find(predicate) {
Some(i) => match self.slice_split(i) {
Ok(s) => Ok(s),
Err(_) => Err(Err::Incomplete(Needed::Unknown)),
},
None => Err(Err::Incomplete(Needed::Size(1))),
}
}
fn split_at_position1<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.src.find(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
Some(i) => match self.slice_split(i) {
Ok(s) => Ok(s),
Err(_) => Err(Err::Incomplete(Needed::Unknown)),
},
None => Err(Err::Incomplete(Needed::Size(1))),
}
}
fn split_at_position_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.src.find(predicate) {
Some(i) => match self.slice_split(i) {
Ok(s) => Ok(s),
Err(_) => Err(Err::Incomplete(Needed::Unknown)),
},
None => Ok(self.take_split(self.input_len())),
}
}
fn split_at_position1_complete<P, E: ParseError<Self>>(
&self,
predicate: P,
e: ErrorKind,
) -> IResult<Self, Self, E>
where
P: Fn(Self::Item) -> bool,
{
match self.src.find(predicate) {
Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),
Some(i) => match self.slice_split(i) {
Ok(s) => Ok(s),
Err(_) => Err(Err::Incomplete(Needed::Unknown)),
},
None => {
if self.src.len() == 0 {
Err(Err::Error(E::from_error_kind(self.clone(), e)))
} else {
Ok(self.take_split(self.input_len()))
}
}
}
}
}
impl<'a, 'b> Compare<Input<'b>> for Input<'a> {
fn compare(&self, t: Input<'b>) -> CompareResult {
self.src.compare(t.src)
}
fn compare_no_case(&self, t: Input<'b>) -> CompareResult {
self.src.compare_no_case(t.src)
}
}
impl<'a, 'b> Compare<&'b str> for Input<'a> {
fn compare(&self, t: &'b str) -> CompareResult {
self.src.compare(t)
}
fn compare_no_case(&self, t: &'b str) -> CompareResult {
self.src.compare_no_case(t)
}
}
impl<'a> FindToken<char> for Input<'a> {
fn find_token(&self, token: char) -> bool {
self.src.find_token(token)
}
}
impl<'a, 'b> FindSubstring<Input<'b>> for Input<'a> {
//returns byte index
fn find_substring(&self, substr: Input<'b>) -> Option<usize> {
self.src.find(substr.src)
}
}
impl<'a, 'b> FindSubstring<&'b str> for Input<'a> {
//returns byte index
fn find_substring(&self, substr: &'b str) -> Option<usize> {
self.src.find(substr)
}
}
impl<'a> ExtendInto for Input<'a> {
type Item = char;
type Extender = String;
#[inline]
fn new_builder(&self) -> String {
String::new()
}
#[inline]
fn extend_into(&self, acc: &mut String) {
acc.push_str(self.src);
}
}
impl<'a> Slice<ops::Range<usize>> for Input<'a> {
fn slice(&self, range: ops::Range<usize>) -> Self {
let pos = self.take(range.start);
let dest_str = self
.src
.get(range.clone())
.or(WHITESPACES.get(range))
.unwrap();
let (line, col) = Self::get_line_col(dest_str);
let end = Position::new(pos.end.line + line - 1, col);
Input::new(dest_str, pos.end, end)
}
}
impl<'a> Slice<ops::RangeTo<usize>> for Input<'a> {
fn slice(&self, range: ops::RangeTo<usize>) -> Self {
self.take(range.end)
}
}
impl<'a> Slice<ops::RangeFrom<usize>> for Input<'a> {
fn slice(&self, range: ops::RangeFrom<usize>) -> Self {
let pos = self.take(range.start);
let dest_str = self
.src
.get(range.clone())
.or(WHITESPACES.get(range))
.unwrap();
Input::new(dest_str, pos.end, self.end)
}
}
impl<'a> Slice<ops::RangeFull> for Input<'a> {
fn slice(&self, _range: ops::RangeFull) -> Self {
self.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use nom::error::VerboseError;
use std::u32;
#[test]
fn test_input_take() {
let s = "abcd123\n123456\n8900";
let s1 = Input::new(s, Position::new(0, 0), Position::new(u32::MAX, u32::MAX));
assert_eq!(
s1.take(7),
Input::new("abcd123", Position::new(0, 0), Position::new(0, 7))
);
assert_eq!(
s1.take(9),
Input::new("abcd123\n1", Position::new(0, 0), Position::new(1, 1))
);
assert_eq!(
s1.take(15),
Input::new(
"abcd123\n123456\n",
Position::new(0, 0),
Position::new(2, 0)
)
);
assert_eq!(
s1.take_split(15),
(
Input::new(
"8900",
Position::new(2, 0),
Position::new(u32::MAX, u32::MAX)
),
Input::new(
"abcd123\n123456\n",
Position::new(0, 0),
Position::new(2, 0)
),
)
);
assert_eq!(
s1.take_split(15),
(
Input::new(
"8900",
Position::new(2, 0),
Position::new(u32::MAX, u32::MAX)
),
Input::new(
"abcd123\n123456\n",
Position::new(0, 0),
Position::new(2, 0)
),
)
);
assert_eq!(
s1.take_split(20),
(
Input::new("", Position::new(0, 20), Position::new(u32::MAX, u32::MAX)),
Input::new(
" ".repeat(20).as_str(),
Position::new(0, 0),
Position::new(0, 20)
),
)
);
}
#[test]
fn test_split_at_position() {
let s = Input::new(
"abcd123\n123456\n8900",
Position::new(0, 0),
Position::new(u32::MAX, u32::MAX),
);
assert_eq!(
s.split_at_position(|s| s == 'd') as IResult<Input, Input, VerboseError<Input>>,
Ok((
Input::new(
"d123\n123456\n8900",
Position::new(0, 3),
Position::new(u32::MAX, u32::MAX)
),
Input::new("abc", Position::new(0, 0), Position::new(0, 3))
))
);
}
#[test]
fn get_line_col_test() {
assert_eq!(Input::get_line_col("hello\ndd\n"), (3, 0));
assert_eq!(
Input::new("hello\ndd\nm", Position::new(0, 2), Position::max()).slice_start(5),
Ok(Input::new(
"hello",
Position::new(0, 2),
Position::new(0, 7)
))
);
assert_eq!(
Input::new("hello\ndd\nm", Position::new(0, 2), Position::max()).slice_start(7),
Ok(Input::new(
"hello\nd",
Position::new(0, 2),
Position::new(1, 1)
))
);
assert_eq!(
Input::new("hello\ndd\nm", Position::new(0, 2), Position::max()).forward(5),
Input::new("\ndd\nm", Position::new(0, 7), Position::max())
);
assert_eq!(
Input::new("hello\ndd\nm", Position::new(0, 2), Position::max()).slice_split(5),
Ok((
Input::new("\ndd\nm", Position::new(0, 7), Position::max()),
Input::new("hello", Position::new(0, 2), Position::new(0, 7))
))
);
}
}
|
#[macro_use]
extern crate lazy_static;
use rand::Rng;
use std::io::Write;
mod vec3d;
use vec3d::Vec3d;
lazy_static! {
static ref ROOT_PARTICLES: Vec<Vec3d> = {
use std::f64::consts::PI;
let mut acc = Vec::new();
let n = 10;
for i in 0..n {
acc.push(Vec3d::new(
3. * (i as f64 / n as f64 * 2. * PI).cos(),
3. * (i as f64 / n as f64 * 2. * PI).sin(),
0.,
))
}
acc
};
}
#[derive(PartialEq)]
enum Model {
Classic,
Quantum,
}
const CUTOFF: f64 = 5.0e-4;
const TMAX: f64 = 30.;
const DIFFT: f64 = 0.001;
const RMAX: f64 = 10.;
const DIFFX: f64 = 0.001;
const N_TJR: usize = 30;
const MASS: f64 = 1.;
const HBAR: f64 = 1.;
// const Q_EL: f64 = 1.6e-19;
// const Q_EL: f64 = 4.803204673e-10;
const Q_EL: f64 = 1.;
fn u_c(r: Vec3d, r0: Vec3d) -> f64 {
let dist = r.distance(r0);
if { dist >= CUTOFF } {
-Q_EL * Q_EL / dist
} else {
-Q_EL * Q_EL / CUTOFF
}
}
fn u_q(r: Vec3d, r0: Vec3d) -> f64 {
let dist = r.distance(r0);
if { dist >= CUTOFF } {
(-0.5 * HBAR / MASS) * -2.0 * (-dist).exp() / dist
} else {
(-0.5 * HBAR / MASS) * -2.0 * (-CUTOFF).exp() / CUTOFF
}
}
fn apply_energy(func: impl Fn(Vec3d, Vec3d) -> f64) -> impl Fn(Vec3d) -> f64 {
move |r0| ROOT_PARTICLES.iter().map(|&r| func(r0, r)).sum()
}
fn gradient(func: impl Fn(Vec3d) -> f64, r: Vec3d) -> Vec3d {
let mut grad = [0f64; 3];
for i in 0..grad.len() {
let mut dr = [0f64; 3];
dr[i] = DIFFX;
let dr = Vec3d::from(dr);
grad[i] += (func(r + dr) - func(r - dr)) / (2. * DIFFX);
}
grad.into()
}
fn main() {
let mut model = Model::Quantum;
let center = Vec3d::new(0., 0., 0.);
let mut rng = rand::thread_rng();
let roots_size = ROOT_PARTICLES.len();
for _ in 0..2 {
for i in 0..N_TJR {
let name = match model {
Model::Quantum => format!("out2/bmd_{:05}.trj", i),
Model::Classic => format!("out2/cmd_{:05}.trj", i),
};
let mut file = std::io::BufWriter::new(std::fs::File::create(name).unwrap());
let mut r = random_spec_sphere(1.) + ROOT_PARTICLES[rng.gen_range(0, roots_size)];
let mut rprev = r + random_spec_sphere(DIFFX);
let mut t = 0.;
while t <= TMAX && r.distance(center) <= RMAX {
let mut force = -gradient(apply_energy(u_c), r);
if model == Model::Quantum {
force -= gradient(apply_energy(u_q), r);
}
let rnew = r * 2. - rprev + (force / MASS) * DIFFT * DIFFT;
rprev = r;
r = rnew;
file.write(&r.to_string().as_bytes()).unwrap();
t += DIFFT;
}
}
model = Model::Classic;
}
}
impl std::fmt::Display for Vec3d {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {} {}\n", self.x, self.y, self.z)
}
}
fn random_spec_sphere(r: f64) -> Vec3d {
let mut rng = rand::thread_rng();
let r = rng.gen_range(CUTOFF, r);
let phi = rng.gen_range(0., 2. * std::f64::consts::PI);
let theta = rng.gen_range(0., std::f64::consts::PI);
let x = r * (theta).sin() * (phi).cos();
let y = r * (theta).sin() * (phi).sin();
let z = r * (theta).cos();
Vec3d::new(x, y, z)
}
|
use tree_sitter::Node;
use crate::lint::core::{ValidationError, Validator};
use crate::lint::grammar::UNSAFE;
use crate::lint::rule::RULE_UNSAFE_CODE;
pub struct UnsafeCodeValidator;
impl Validator for UnsafeCodeValidator {
fn validate(&self, node: &Node, _source: &str) -> Result<(), ValidationError> {
if node.kind() == UNSAFE {
return Err(ValidationError::from_node(node, RULE_UNSAFE_CODE));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lint::filters::filter_nothing::NothingFilter;
use crate::lint::utils::{assert_source_ok, validate};
use crate::RuleCode;
#[test]
fn test_no_unsafe() {
let filter = NothingFilter;
let source_code = "fn test() -> usize { let a = [0]; 233 }";
assert_source_ok(source_code, Box::new(UnsafeCodeValidator), &filter);
}
#[test]
fn test_unsafe_block() {
let filter = NothingFilter;
let source_code = "fn test() -> usize { unsafe { 233 } }";
let res = validate(source_code, Box::new(UnsafeCodeValidator), &filter);
let err = assert_err!(res);
assert_eq!(err.rule.code, RuleCode::Unsafe);
}
#[test]
fn test_unsafe_func() {
let filter = NothingFilter;
let source_code = "unsafe async fn test() -> usize { 233 }";
let res = validate(source_code, Box::new(UnsafeCodeValidator), &filter);
let err = assert_err!(res);
assert_eq!(err.rule.code, RuleCode::Unsafe);
}
}
|
use std::collections::HashMap;
use std::fmt::Display;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::u64;
use anyhow::{bail, Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
use structopt::StructOpt;
const PRINT_EVERY_N_SECS: f32 = 3.;
const PRINT_TOP_N: usize = 10;
#[derive(Debug, StructOpt)]
struct Opt {
#[structopt(parse(from_os_str))]
input: PathBuf,
}
fn main() -> Result<()> {
let opt = Opt::from_args();
let reader = open_reader(opt.input);
process_input(reader)
}
fn open_reader(input: PathBuf) -> Box<dyn BufRead> {
if input.to_string_lossy() == "-" {
Box::new(BufReader::new(std::io::stdin()))
} else {
Box::new(BufReader::new(File::open(input).unwrap()))
}
}
#[derive(Debug)]
struct DiskIoRec {
timestamp: String,
call: String,
bytes: u64,
interval: f64,
process: String,
pid: u64,
}
#[derive(Debug, Default)]
struct Summary {
lines: u64,
parse_fails: u64,
call_time: HashMap<String, f64>,
call_entries: HashMap<String, u64>,
process_time: HashMap<String, f64>,
process_entries: HashMap<String, u64>,
}
impl Summary {
fn add(&mut self, rec: &DiskIoRec) {
*self.process_time.entry(rec.process.clone()).or_insert(0.) += rec.interval;
*self.process_entries.entry(rec.process.clone()).or_insert(0) += 1;
*self.call_time.entry(rec.call.clone()).or_insert(0.) += rec.interval;
*self.call_entries.entry(rec.call.clone()).or_insert(0) += 1;
}
}
impl Display for Summary {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt_top<K: Display, V: Display + PartialOrd>(hash: &HashMap<K, V>) -> String {
fmt_pairs(&top_values(hash, PRINT_TOP_N))
}
write!(
f,
"\n=> lines (fails): {} ({})\n\
=> top calls (time):\n{}\
=> top calls (entries):\n{}\
=> top processes (time):\n{}\
=> top processes (entries):\n{}",
self.lines,
self.parse_fails,
fmt_top(&self.call_time),
fmt_top(&self.call_entries),
fmt_top(&self.process_time),
fmt_top(&self.process_entries),
)
}
}
// TODO: um store in a better data structure to avoid this?
fn top_values<K, V: PartialOrd>(hash: &HashMap<K, V>, n: usize) -> Vec<(&K, &V)> {
let mut top = vec![];
let mut vals: Vec<(usize, &V)> = hash.values().enumerate().collect();
vals.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap());
let keys: Vec<&K> = hash.keys().collect();
for &(i, val) in vals.iter().take(n) {
top.push((keys[i], val));
}
top
}
fn fmt_pairs<K: Display, V: Display>(pairs: &Vec<(K, V)>) -> String {
let mut res = String::new();
for (k, v) in pairs {
// commands are max 16 chars
let entry = format!(" {:>16}: {:.1}\n", k, v);
res.push_str(&entry);
}
res
}
fn process_input(reader: Box<dyn BufRead>) -> Result<()> {
let mut summary = Summary::default();
let mut last_print = std::time::UNIX_EPOCH;
for line in reader.lines() {
let line = line?;
summary.lines += 1;
let rec = parse_line(&line);
match rec {
// Ok(rec) => { println!("{:?}", rec); summary.add(&rec) },
Ok(rec) => summary.add(&rec),
Err(e) => {
summary.parse_fails += 1;
// TODO: how to catch this case specifically to ignore it..?
let es = e.to_string();
if es != "(errno)" {
println!("{:?}", e);
}
}
}
let now = std::time::SystemTime::now();
match now.duration_since(last_print) {
Err(_) => last_print = now,
Ok(n) => {
if n.as_secs_f32() >= PRINT_EVERY_N_SECS {
println!("\n{}", summary);
last_print = now;
}
}
}
}
// reached end of input, print final summary
println!("\n{}", summary);
Ok(())
}
lazy_static! {
static ref LINE_RE: Regex = Regex::new(
r"(\d{2}:\d{2}:\d{2}.\d+) +([^ ]+) .* B=0x([[:xdigit:]]+) .* ([.\d]+) W (.+)\.(\d+)$"
)
.unwrap();
static ref ERRNO_RE: Regex = Regex::new(r" \[([ \d]+)\]").unwrap();
}
// TODO: way to make this more concise?
fn parse_line(s: &str) -> Result<DiskIoRec> {
let cap = LINE_RE.captures(s);
if cap.is_none() {
if !ERRNO_RE.is_match(s) {
bail!("unexpected parse, no bytes or errno: {}", s);
}
bail!("(errno)");
}
let cap = cap.context("regex match failed on line")?;
Ok(DiskIoRec {
timestamp: cap.get(1).context("timestamp")?.as_str().into(),
call: cap.get(2).context("call")?.as_str().to_string(),
bytes: u64::from_str_radix(cap.get(3).context("bytes")?.as_str(), 16)?,
interval: cap.get(4).context("interval")?.as_str().parse()?,
process: cap.get(5).context("process")?.as_str().into(),
pid: cap.get(6).context("pid")?.as_str().parse()?,
})
}
|
use std::fmt;
use std::num::NonZeroUsize;
/// An opaque identifier that is associated with AST items.
///
/// The default implementation for an identifier is empty, meaning it does not
/// hold any value, and attempting to perform lookups over it will fail with an
/// error indicating that it's empty with the string `Id(*)`.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Id(NonZeroUsize);
impl Id {
/// Construct the initial (non-empty) id.
pub fn initial() -> Self {
Id(NonZeroUsize::new(1).unwrap())
}
/// Construct a new opaque identifier.
pub fn new(index: usize) -> Option<Id> {
NonZeroUsize::new(index).map(Self)
}
/// Get the next id.
pub fn next(self) -> Option<Id> {
let n = self.0.get().checked_add(1)?;
let n = NonZeroUsize::new(n)?;
Some(Self(n))
}
}
impl Default for Id {
fn default() -> Self {
Self::initial()
}
}
impl fmt::Debug for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Id({})", self.0.get())
}
}
|
/// Floating point values can not be ordered / hashed in Rust by default
/// (which is the correct thing to do but annoying if you want dynamically
/// typed sets and hashtables!).
/// This module provides a very lightweight wrapper around f64s that
/// implements ordering and hashing which is `good enough` for PICL.
use std::cmp::Ordering;
use std::fmt;
/// LF64 is a Lisp float64 where NaN is larger than anything else.
/// The underlying f64 value needs to be extracted as follows:
///
/// # Examples
/// ```
/// let my_float = LF64(4.2);
/// println!("{}", 5.1 + my_float.0);
/// ```
#[derive(Clone, Copy, Default, Debug, Hash)]
pub struct LF64(pub f64);
impl PartialEq for LF64 {
fn eq(&self, other: &LF64) -> bool {
match (self.0.is_nan(), other.0.is_nan()) {
(false, false) => self.0 == other.0,
(true, true) => true,
_ => false,
}
}
}
impl Eq for LF64 {}
impl PartialOrd for LF64 {
fn partial_cmp(&self, other: &LF64) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LF64 {
fn cmp(&self, other: &LF64) -> Ordering {
match (self.0.is_nan(), other.0.is_nan()) {
(false, false) => {
if self.0 < other.0 {
Ordering::Less
} else if self.0 > other.0 {
Ordering::Greater
} else {
Ordering::Equal
}
}
(false, true) => Ordering::Less,
(true, false) => Ordering::Greater,
(true, true) => Ordering::Equal,
}
}
}
impl fmt::Display for LF64 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
|
use models::error::RuntimeError;
use std::time::Instant;
use tokio::prelude::*;
use utils::stream::connect;
pub fn new() -> (
impl Sink<SinkItem = Instant, SinkError = RuntimeError>,
impl Stream<Item = String, Error = RuntimeError>,
) {
let (input, output) = connect::<Instant>();
(
input,
output.map({
let mut count = 0u32;
move |_| {
count = count + 1;
format!("count: {}", count)
}
}),
)
}
|
use stackable_kafka_crd::KafkaCluster;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
println!("{}", serde_yaml::to_string(&KafkaCluster::crd())?);
Ok(())
}
|
use std::env;
fn main() {
let my_input = env::var("INPUT_MYINPUT").unwrap_or_default();
let output = format!("Hello {}", my_input);
println!("::set-output name=myOutput::{}", output);
}
|
mod error;
mod play_flag;
use crate::play_flag::{GstPlayFlags, GST_PLAY_FLAG_VIS};
use gstreamer::prelude::*;
use gstreamer::*;
/* Return TRUE if this is a Visualization element */
fn filter_vis_features(feature: &PluginFeature) -> bool {
match feature.downcast_ref::<ElementFactory>() {
Some(factory) => factory.klass() == "Visualization",
None => false,
}
}
fn main() -> Result<(), error::Error> {
/* Initialize GStreamer */
gstreamer::init()?;
/* Get a list of all visualization plugins */
let list = Registry::get().features_filtered(filter_vis_features, false);
/* Print their names */
println!("Available visualization plugins:");
let mut selected_factory = None;
for walk in list {
let factory = walk.downcast::<ElementFactory>().unwrap();
let name = factory.longname();
println!(" {}", name);
if selected_factory.is_none() || name.starts_with("GOOM") {
selected_factory = Some(factory);
}
}
/* Don't use the factory if it's still empty */
/* e.g. no visualization plugins found */
if selected_factory.is_none() {
println!("No visualization plugins found!");
panic!();
}
let selected_factory = selected_factory.unwrap();
/* We have now selected a factory for the visualization element */
println!("Selected '{}'", selected_factory.longname());
let vis_plugin = selected_factory.create().build()?;
/* Build the pipeline */
let pipeline = parse_launch("playbin uri=http://radio.hbr1.com:19800/ambient.ogg").unwrap();
/* Set the visualization flag */
let mut flags = unsafe {
use gstreamer::glib::translate::{ToGlibPtr, ToGlibPtrMut};
let mut flags = 0.to_value();
glib::gobject_ffi::g_object_get_property(
pipeline.as_object_ref().to_glib_none().0,
"flags\0".as_ptr() as *const _,
flags.to_glib_none_mut().0,
);
flags.get::<GstPlayFlags>().unwrap()
};
flags |= GST_PLAY_FLAG_VIS;
let flags = flags.to_value();
unsafe {
use gstreamer::glib::translate::ToGlibPtr;
glib::gobject_ffi::g_object_set_property(
pipeline.as_object_ref().to_glib_none().0,
"flags\0".as_ptr() as *const _,
flags.to_glib_none().0,
);
}
/* set vis plugin for playbin */
pipeline.set_property("vis-plugin", vis_plugin);
/* Start playing */
let _ = pipeline.set_state(State::Playing);
/* Wait until error or EOS */
let bus = pipeline.bus().unwrap();
let _msg = bus.timed_pop_filtered(ClockTime::NONE, &[MessageType::Error, MessageType::Eos]);
/* Free resources */
let _ = pipeline.set_state(State::Null);
Ok(())
}
|
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use freetype::{FT_Char, FT_UShort, FT_Short, FT_ULong, FT_Byte};
#[repr(C)]
pub struct TT_OS2 {
pub version: FT_UShort,
pub xAvgCharWidth: FT_Short,
pub usWeightClass: FT_UShort,
pub usWidthClass: FT_UShort,
pub fsType: FT_Short,
pub ySubscriptXSize: FT_Short,
pub ySubscriptYSize: FT_Short,
pub ySubscriptXOffset: FT_Short,
pub ySubscriptYOffset: FT_Short,
pub ySuperscriptXSize: FT_Short,
pub ySuperscriptYSize: FT_Short,
pub ySuperscriptXOffset: FT_Short,
pub ySuperscriptYOffset: FT_Short,
pub yStrikeoutSize: FT_Short,
pub yStrikeoutPosition: FT_Short,
pub sFamilyClass: FT_Short,
pub panose: [FT_Byte; 10],
pub ulUnicodeRange1: FT_ULong, /* Bits 0-31 */
pub ulUnicodeRange2: FT_ULong, /* Bits 32-63 */
pub ulUnicodeRange3: FT_ULong, /* Bits 64-95 */
pub ulUnicodeRange4: FT_ULong, /* Bits 96-127 */
pub achVendID: [FT_Char; 4],
pub fsSelection: FT_UShort,
pub usFirstCharIndex: FT_UShort,
pub usLastCharIndex: FT_UShort,
pub sTypoAscender: FT_Short,
pub sTypoDescender: FT_Short,
pub sTypoLineGap: FT_Short,
pub usWinAscent: FT_UShort,
pub usWinDescent: FT_UShort,
/* only version 1 tables */
pub ulCodePageRange1: FT_ULong, /* Bits 0-31 */
pub ulCodePageRange2: FT_ULong, /* Bits 32-63 */
/* only version 2 tables */
pub sxHeight: FT_Short,
pub sCapHeight: FT_Short,
pub usDefaultChar: FT_UShort,
pub usBreakChar: FT_UShort,
pub usMaxContext: FT_UShort,
}
|
// 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::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use common_arrow::arrow::datatypes::DataType as ArrowDataType;
use common_arrow::arrow::datatypes::Field as ArrowField;
use common_arrow::arrow::datatypes::Schema as ArrowSchema;
use common_arrow::arrow::datatypes::TimeUnit;
use common_exception::ErrorCode;
use common_exception::Result;
use itertools::Itertools;
use serde::Deserialize;
use serde::Serialize;
use crate::types::decimal::DecimalDataType;
use crate::types::decimal::DecimalSize;
use crate::types::DataType;
use crate::types::NumberDataType;
use crate::with_number_type;
use crate::Scalar;
use crate::ARROW_EXT_TYPE_EMPTY_ARRAY;
use crate::ARROW_EXT_TYPE_EMPTY_MAP;
use crate::ARROW_EXT_TYPE_VARIANT;
// Column id of TableField
pub type ColumnId = u32;
// Index of TableSchema.fields array
pub type FieldIndex = usize;
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct DataSchema {
pub(crate) fields: Vec<DataField>,
pub(crate) metadata: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct DataField {
name: String,
default_expr: Option<String>,
data_type: DataType,
}
fn uninit_column_id() -> ColumnId {
0
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct TableSchema {
pub(crate) fields: Vec<TableField>,
pub(crate) metadata: BTreeMap<String, String>,
// next column id that assign to TableField.column_id
#[serde(default = "uninit_column_id")]
pub(crate) next_column_id: ColumnId,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct TableField {
name: String,
default_expr: Option<String>,
data_type: TableDataType,
#[serde(default = "uninit_column_id")]
column_id: ColumnId,
}
/// DataType with more information that is only available for table field, e.g, the
/// tuple field name, or the scale of decimal.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum TableDataType {
Null,
EmptyArray,
EmptyMap,
Boolean,
String,
Number(NumberDataType),
Decimal(DecimalDataType),
Timestamp,
Date,
Nullable(Box<TableDataType>),
Array(Box<TableDataType>),
Map(Box<TableDataType>),
Tuple {
fields_name: Vec<String>,
fields_type: Vec<TableDataType>,
},
Variant,
}
impl DataSchema {
pub fn empty() -> Self {
Self {
fields: vec![],
metadata: BTreeMap::new(),
}
}
pub fn new(fields: Vec<DataField>) -> Self {
Self {
fields,
metadata: BTreeMap::new(),
}
}
pub fn new_from(fields: Vec<DataField>, metadata: BTreeMap<String, String>) -> Self {
Self { fields, metadata }
}
/// Returns an immutable reference of the vector of `Field` instances.
#[inline]
pub const fn fields(&self) -> &Vec<DataField> {
&self.fields
}
#[inline]
pub fn num_fields(&self) -> usize {
self.fields.len()
}
#[inline]
pub fn has_field(&self, name: &str) -> bool {
for i in 0..self.fields.len() {
if self.fields[i].name() == name {
return true;
}
}
false
}
pub fn fields_map(&self) -> BTreeMap<FieldIndex, DataField> {
let x = self.fields().iter().cloned().enumerate();
x.collect::<BTreeMap<_, _>>()
}
/// Returns an immutable reference of a specific `Field` instance selected using an
/// offset within the internal `fields` vector.
pub fn field(&self, i: FieldIndex) -> &DataField {
&self.fields[i]
}
/// Returns an immutable reference of a specific `Field` instance selected by name.
pub fn field_with_name(&self, name: &str) -> Result<&DataField> {
Ok(&self.fields[self.index_of(name)?])
}
/// Returns an immutable reference to field `metadata`.
#[inline]
pub const fn meta(&self) -> &BTreeMap<String, String> {
&self.metadata
}
/// Find the index of the column with the given name.
pub fn index_of(&self, name: &str) -> Result<FieldIndex> {
for i in (0..self.fields.len()).rev() {
// Use `rev` is because unnest columns will be attached to end of schema,
// but their names are the same as the original column.
if self.fields[i].name() == name {
return Ok(i);
}
}
let valid_fields: Vec<String> = self.fields.iter().map(|f| f.name().clone()).collect();
Err(ErrorCode::BadArguments(format!(
"Unable to get field named \"{}\". Valid fields: {:?}",
name, valid_fields
)))
}
/// Look up a column by name and return a immutable reference to the column along with
/// its index.
pub fn column_with_name(&self, name: &str) -> Option<(FieldIndex, &DataField)> {
self.fields
.iter()
.enumerate()
.find(|&(_, c)| c.name() == name)
}
/// Check to see if `self` is a superset of `other` schema. Here are the comparison rules:
pub fn contains(&self, other: &DataSchema) -> bool {
if self.fields.len() != other.fields.len() {
return false;
}
for (i, field) in other.fields.iter().enumerate() {
if &self.fields[i] != field {
return false;
}
}
true
}
/// project will do column pruning.
#[must_use]
pub fn project(&self, projection: &[FieldIndex]) -> Self {
let fields = projection
.iter()
.map(|idx| self.fields()[*idx].clone())
.collect();
Self::new_from(fields, self.meta().clone())
}
/// project will do column pruning.
#[must_use]
pub fn project_by_fields(&self, fields: Vec<DataField>) -> Self {
Self::new_from(fields, self.meta().clone())
}
pub fn to_arrow(&self) -> ArrowSchema {
let fields = self.fields().iter().map(|f| f.into()).collect::<Vec<_>>();
ArrowSchema::from(fields).with_metadata(self.metadata.clone())
}
}
impl TableSchema {
pub fn empty() -> Self {
Self {
fields: vec![],
metadata: BTreeMap::new(),
next_column_id: 0,
}
}
pub fn init_if_need(data_schema: TableSchema) -> Self {
// If next_column_id is 0, it is an old version needs to compatibility
if data_schema.next_column_id == 0 {
Self::new_from(data_schema.fields, data_schema.metadata)
} else {
data_schema
}
}
fn build_members_from_fields(
fields: Vec<TableField>,
next_column_id: ColumnId,
) -> (u32, Vec<TableField>) {
if next_column_id > 0 {
// make sure that field column id has been inited.
if fields.len() > 1 {
assert!(fields[1].column_id() > 0);
}
return (next_column_id, fields);
}
let mut new_next_column_id = 0;
let mut new_fields = Vec::with_capacity(fields.len());
for field in fields {
let new_field = field.build_column_id(&mut new_next_column_id);
// check next_column_id value cannot fallback
assert!(new_next_column_id >= new_field.column_id());
new_fields.push(new_field);
}
// check next_column_id value cannot fallback
assert!(new_next_column_id >= next_column_id);
(new_next_column_id, new_fields)
}
pub fn new(fields: Vec<TableField>) -> Self {
let (next_column_id, new_fields) = Self::build_members_from_fields(fields, 0);
Self {
fields: new_fields,
metadata: BTreeMap::new(),
next_column_id,
}
}
pub fn new_from(fields: Vec<TableField>, metadata: BTreeMap<String, String>) -> Self {
let (next_column_id, new_fields) = Self::build_members_from_fields(fields, 0);
Self {
fields: new_fields,
metadata,
next_column_id,
}
}
pub fn new_from_column_ids(
fields: Vec<TableField>,
metadata: BTreeMap<String, String>,
next_column_id: ColumnId,
) -> Self {
let (next_column_id, new_fields) = Self::build_members_from_fields(fields, next_column_id);
Self {
fields: new_fields,
metadata,
next_column_id,
}
}
#[inline]
pub fn next_column_id(&self) -> ColumnId {
self.next_column_id
}
pub fn column_id_of_index(&self, i: FieldIndex) -> Result<ColumnId> {
Ok(self.fields[i].column_id())
}
pub fn column_id_of(&self, name: &str) -> Result<ColumnId> {
let i = self.index_of(name)?;
Ok(self.fields[i].column_id())
}
pub fn is_column_deleted(&self, column_id: ColumnId) -> bool {
for field in &self.fields {
if field.contain_column_id(column_id) {
return false;
}
}
true
}
pub fn add_columns(&mut self, fields: &[TableField]) -> Result<()> {
for f in fields {
if self.index_of(f.name()).is_ok() {
return Err(ErrorCode::AddColumnExistError(format!(
"add column {} already exist",
f.name(),
)));
}
let field = f.build_column_id(&mut self.next_column_id);
self.fields.push(field);
}
Ok(())
}
// Every internal column has constant column id, no need to generate column id of internal columns.
pub fn add_internal_column(
&mut self,
name: &str,
data_type: TableDataType,
column_id: ColumnId,
) {
let field = TableField::new_from_column_id(name, data_type, column_id);
self.fields.push(field);
}
pub fn drop_column(&mut self, column: &str) -> Result<()> {
if self.fields.len() == 1 {
return Err(ErrorCode::DropColumnEmptyError(
"cannot drop table column to empty",
));
}
let i = self.index_of(column)?;
self.fields.remove(i);
Ok(())
}
pub fn to_leaf_column_id_set(&self) -> HashSet<ColumnId> {
HashSet::from_iter(self.to_leaf_column_ids().iter().cloned())
}
pub fn to_column_ids(&self) -> Vec<ColumnId> {
let mut column_ids = Vec::with_capacity(self.fields.len());
self.fields.iter().for_each(|f| {
column_ids.extend(f.column_ids());
});
column_ids
}
pub fn to_leaf_column_ids(&self) -> Vec<ColumnId> {
let mut column_ids = Vec::with_capacity(self.fields.len());
self.fields.iter().for_each(|f| {
column_ids.extend(f.leaf_column_ids());
});
column_ids
}
/// Returns an immutable reference of the vector of `Field` instances.
#[inline]
pub const fn fields(&self) -> &Vec<TableField> {
&self.fields
}
#[inline]
pub fn field_column_ids(&self) -> Vec<Vec<ColumnId>> {
let mut field_column_ids = Vec::with_capacity(self.fields.len());
self.fields.iter().for_each(|f| {
field_column_ids.push(f.column_ids());
});
field_column_ids
}
#[inline]
pub fn field_leaf_column_ids(&self) -> Vec<Vec<ColumnId>> {
let mut field_column_ids = Vec::with_capacity(self.fields.len());
self.fields.iter().for_each(|f| {
field_column_ids.push(f.leaf_column_ids());
});
field_column_ids
}
pub fn field_leaf_default_values(
&self,
default_values: &[Scalar],
) -> HashMap<ColumnId, Scalar> {
fn collect_leaf_default_values(
default_value: &Scalar,
column_ids: &[ColumnId],
index: &mut usize,
leaf_default_values: &mut HashMap<ColumnId, Scalar>,
) {
match default_value {
Scalar::Tuple(s) => {
s.iter().for_each(|default_val| {
collect_leaf_default_values(
default_val,
column_ids,
index,
leaf_default_values,
)
});
}
_ => {
leaf_default_values.insert(column_ids[*index], default_value.to_owned());
*index += 1;
}
}
}
let mut leaf_default_values = HashMap::with_capacity(self.num_fields());
let leaf_field_column_ids = self.field_leaf_column_ids();
for (default_value, field_column_ids) in default_values.iter().zip_eq(leaf_field_column_ids)
{
let mut index = 0;
collect_leaf_default_values(
default_value,
&field_column_ids,
&mut index,
&mut leaf_default_values,
);
}
leaf_default_values
}
#[inline]
pub fn num_fields(&self) -> usize {
self.fields.len()
}
#[inline]
pub fn has_field(&self, name: &str) -> bool {
for i in 0..self.fields.len() {
if self.fields[i].name == name {
return true;
}
}
false
}
pub fn fields_map(&self) -> BTreeMap<FieldIndex, TableField> {
let x = self.fields().iter().cloned().enumerate();
x.collect::<BTreeMap<_, _>>()
}
/// Returns an immutable reference of a specific `Field` instance selected using an
/// offset within the internal `fields` vector.
pub fn field(&self, i: FieldIndex) -> &TableField {
&self.fields[i]
}
/// Returns an immutable reference of a specific `Field` instance selected by name.
pub fn field_with_name(&self, name: &str) -> Result<&TableField> {
Ok(&self.fields[self.index_of(name)?])
}
/// Returns an immutable reference to field `metadata`.
#[inline]
pub const fn meta(&self) -> &BTreeMap<String, String> {
&self.metadata
}
/// Find the index of the column with the given name.
pub fn index_of(&self, name: &str) -> Result<FieldIndex> {
for i in 0..self.fields.len() {
if self.fields[i].name == name {
return Ok(i);
}
}
let valid_fields: Vec<String> = self.fields.iter().map(|f| f.name.clone()).collect();
Err(ErrorCode::BadArguments(format!(
"Unable to get field named \"{}\". Valid fields: {:?}",
name, valid_fields
)))
}
/// Look up a column by name and return a immutable reference to the column along with
/// its index.
pub fn column_with_name(&self, name: &str) -> Option<(FieldIndex, &TableField)> {
self.fields
.iter()
.enumerate()
.find(|&(_, c)| c.name == name)
}
/// Check to see if `self` is a superset of `other` schema. Here are the comparison rules:
pub fn contains(&self, other: &TableSchema) -> bool {
if self.fields.len() != other.fields.len() {
return false;
}
for (i, field) in other.fields.iter().enumerate() {
if &self.fields[i] != field {
return false;
}
}
true
}
/// project will do column pruning.
#[must_use]
pub fn project(&self, projection: &[FieldIndex]) -> Self {
let mut fields = Vec::with_capacity(projection.len());
for idx in projection {
fields.push(self.fields[*idx].clone());
}
Self {
fields,
metadata: self.metadata.clone(),
next_column_id: self.next_column_id,
}
}
/// project with inner columns by path.
pub fn inner_project(&self, path_indices: &BTreeMap<FieldIndex, Vec<FieldIndex>>) -> Self {
let paths: Vec<Vec<usize>> = path_indices.values().cloned().collect();
let schema_fields = self.fields();
let column_ids = self.to_column_ids();
let fields = paths
.iter()
.map(|path| Self::traverse_paths(schema_fields, path, &column_ids).unwrap())
.collect();
Self {
fields,
metadata: self.metadata.clone(),
next_column_id: self.next_column_id,
}
}
// Returns all inner column ids of the given column, including itself,
// only tuple columns may have inner fields, like `a.1`, `a:b`.
pub fn leaf_columns_of(&self, col_name: &String) -> Vec<ColumnId> {
fn collect_inner_column_ids(
col_name: &String,
field_name: &String,
data_type: &TableDataType,
column_ids: &mut Vec<ColumnId>,
next_column_id: &mut ColumnId,
) -> bool {
if col_name == field_name {
let n = data_type.num_leaf_columns();
for i in 0..n {
column_ids.push(*next_column_id + i as u32);
}
return true;
}
if let TableDataType::Tuple {
fields_name,
fields_type,
} = data_type
{
if col_name.starts_with(field_name) {
for ((i, inner_field_name), inner_field_type) in
fields_name.iter().enumerate().zip(fields_type.iter())
{
let inner_name = format!("{}:{}", field_name, inner_field_name);
if col_name.starts_with(&inner_name) {
return collect_inner_column_ids(
col_name,
&inner_name,
inner_field_type,
column_ids,
next_column_id,
);
}
let inner_name = format!("{}:{}", field_name, i + 1);
if col_name.starts_with(&inner_name) {
return collect_inner_column_ids(
col_name,
&inner_name,
inner_field_type,
column_ids,
next_column_id,
);
}
*next_column_id += inner_field_type.num_leaf_columns() as u32;
}
}
}
false
}
let mut column_ids = Vec::new();
for field in self.fields() {
let mut next_column_id = field.column_id;
if collect_inner_column_ids(
col_name,
&field.name,
&field.data_type,
&mut column_ids,
&mut next_column_id,
) {
break;
}
}
column_ids
}
fn traverse_paths(
fields: &[TableField],
path: &[FieldIndex],
column_ids: &[ColumnId],
) -> Result<TableField> {
if path.is_empty() {
return Err(ErrorCode::BadArguments(
"path should not be empty".to_string(),
));
}
let index = path[0];
let field = &fields[index];
if path.len() == 1 {
return Ok(field.clone());
}
// If the data type is Tuple, we can read the innner columns directly.
// For example, `select t:a from table`, we can only read column t:a.
// So we can project the inner field as a independent field (`inner_project` and `traverse_paths` will be called).
//
// For more complex type, such as Array(Tuple), and sql `select array[0]:field from table`,
// we can't do inner project, because get field from these types will turn into calling `get` method. (Use `EXPLAIN ...` to see the plan.)
// When calling `get` method, the whole outer column will be read,
// so `inner_project` and `traverse_paths` methods will not be called (`project` is called instead).
//
// Although `inner_project` and `traverse_paths` methods will not be called for complex types like Array(Tuple),
// when constructing column leaves (for reading parquet) for these types, we still need to dfs the inner fields.
// See comments in `common_storage::ColumnNodes::traverse_fields_dfs` for more details.
if let TableDataType::Tuple {
fields_name,
fields_type,
} = &field.data_type
{
let field_name = field.name();
let mut next_column_id = column_ids[1 + index];
let fields = fields_name
.iter()
.zip(fields_type)
.map(|(name, ty)| {
let inner_name = format!("{}:{}", field_name, name.to_lowercase());
let field = TableField::new(&inner_name, ty.clone());
field.build_column_id(&mut next_column_id)
})
.collect::<Vec<_>>();
return Self::traverse_paths(&fields, &path[1..], &column_ids[index + 1..]);
}
let valid_fields: Vec<String> = fields.iter().map(|f| f.name.clone()).collect();
Err(ErrorCode::BadArguments(format!(
"Unable to get field paths. Valid fields: {:?}",
valid_fields
)))
}
// return leaf fields with column id
pub fn leaf_fields(&self) -> Vec<TableField> {
fn collect_in_field(
field: &TableField,
fields: &mut Vec<TableField>,
next_column_id: &mut ColumnId,
) {
match field.data_type() {
TableDataType::Tuple {
fields_type,
fields_name,
} => {
for (name, ty) in fields_name.iter().zip(fields_type) {
collect_in_field(
&TableField::new_from_column_id(name, ty.clone(), *next_column_id),
fields,
next_column_id,
);
}
}
TableDataType::Array(ty) => {
collect_in_field(
&TableField::new_from_column_id(
&format!("{}:0", field.name()),
ty.as_ref().to_owned(),
*next_column_id,
),
fields,
next_column_id,
);
}
TableDataType::Map(ty) => {
collect_in_field(
&TableField::new_from_column_id(
field.name(),
ty.as_ref().to_owned(),
*next_column_id,
),
fields,
next_column_id,
);
}
_ => {
*next_column_id += 1;
fields.push(field.clone())
}
}
}
let mut fields = Vec::new();
for field in self.fields() {
let mut next_column_id = field.column_id;
collect_in_field(field, &mut fields, &mut next_column_id);
}
fields
}
/// project will do column pruning.
#[must_use]
pub fn project_by_fields(&self, fields: &BTreeMap<FieldIndex, TableField>) -> Self {
let column_ids = self.to_column_ids();
let mut new_fields = Vec::with_capacity(fields.len());
for (index, f) in fields.iter() {
let mut column_id = column_ids[*index];
let field = f.build_column_id(&mut column_id);
new_fields.push(field);
}
Self {
fields: new_fields,
metadata: self.metadata.clone(),
next_column_id: self.next_column_id,
}
}
pub fn to_arrow(&self) -> ArrowSchema {
let fields = self.fields().iter().map(|f| f.into()).collect::<Vec<_>>();
ArrowSchema::from(fields).with_metadata(self.metadata.clone())
}
}
impl DataField {
pub fn new(name: &str, data_type: DataType) -> Self {
DataField {
name: name.to_string(),
default_expr: None,
data_type,
}
}
pub fn new_nullable(name: &str, data_type: DataType) -> Self {
DataField {
name: name.to_string(),
default_expr: None,
data_type: DataType::Nullable(Box::new(data_type)),
}
}
#[must_use]
pub fn with_default_expr(mut self, default_expr: Option<String>) -> Self {
self.default_expr = default_expr;
self
}
pub fn name(&self) -> &String {
&self.name
}
pub fn data_type(&self) -> &DataType {
&self.data_type
}
pub fn default_expr(&self) -> Option<&String> {
self.default_expr.as_ref()
}
#[inline]
pub fn is_nullable(&self) -> bool {
self.data_type.is_nullable()
}
#[inline]
pub fn is_nullable_or_null(&self) -> bool {
self.data_type.is_nullable_or_null()
}
}
impl TableField {
pub fn new(name: &str, data_type: TableDataType) -> Self {
TableField {
name: name.to_string(),
default_expr: None,
data_type,
column_id: 0,
}
}
pub fn new_from_column_id(name: &str, data_type: TableDataType, column_id: ColumnId) -> Self {
TableField {
name: name.to_string(),
default_expr: None,
data_type,
column_id,
}
}
fn build_column_ids_from_data_type(
data_type: &TableDataType,
column_ids: &mut Vec<ColumnId>,
next_column_id: &mut ColumnId,
) {
column_ids.push(*next_column_id);
match data_type.remove_nullable() {
TableDataType::Tuple {
fields_name: _,
ref fields_type,
} => {
for inner_type in fields_type {
Self::build_column_ids_from_data_type(inner_type, column_ids, next_column_id);
}
}
TableDataType::Array(a) => {
Self::build_column_ids_from_data_type(a.as_ref(), column_ids, next_column_id);
}
TableDataType::Map(a) => {
Self::build_column_ids_from_data_type(a.as_ref(), column_ids, next_column_id);
}
_ => {
*next_column_id += 1;
}
}
}
pub fn build_column_id(&self, next_column_id: &mut ColumnId) -> Self {
let data_type = self.data_type();
let column_id = *next_column_id;
let mut new_next_column_id = *next_column_id;
let mut column_ids = vec![];
Self::build_column_ids_from_data_type(data_type, &mut column_ids, &mut new_next_column_id);
*next_column_id = new_next_column_id;
Self {
name: self.name.clone(),
default_expr: self.default_expr.clone(),
data_type: self.data_type.clone(),
column_id,
}
}
pub fn contain_column_id(&self, column_id: ColumnId) -> bool {
self.column_ids().contains(&column_id)
}
// `leaf_column_ids` return only the child column id.
// if field is Tuple(t1, t2), it will return a column id vector of 2 column id.
pub fn leaf_column_ids(&self) -> Vec<ColumnId> {
let h: BTreeSet<u32> = BTreeSet::from_iter(self.column_ids().iter().cloned());
h.into_iter().sorted().collect()
}
// `column_ids` contains nest-type parent column id,
// if field is Tuple(t1, t2), it will return a column id vector of 3 column id.
pub fn column_ids(&self) -> Vec<ColumnId> {
let mut column_ids = vec![];
let mut new_next_column_id = self.column_id;
Self::build_column_ids_from_data_type(
self.data_type(),
&mut column_ids,
&mut new_next_column_id,
);
column_ids
}
pub fn column_id(&self) -> ColumnId {
self.column_id
}
#[must_use]
pub fn with_default_expr(mut self, default_expr: Option<String>) -> Self {
self.default_expr = default_expr;
self
}
pub fn name(&self) -> &String {
&self.name
}
pub fn data_type(&self) -> &TableDataType {
&self.data_type
}
pub fn default_expr(&self) -> Option<&String> {
self.default_expr.as_ref()
}
#[inline]
pub fn is_nullable(&self) -> bool {
self.data_type.is_nullable()
}
#[inline]
pub fn is_nullable_or_null(&self) -> bool {
self.data_type.is_nullable_or_null()
}
}
impl From<&TableDataType> for DataType {
fn from(data_type: &TableDataType) -> DataType {
match data_type {
TableDataType::Null => DataType::Null,
TableDataType::EmptyArray => DataType::EmptyArray,
TableDataType::EmptyMap => DataType::EmptyMap,
TableDataType::Boolean => DataType::Boolean,
TableDataType::String => DataType::String,
TableDataType::Number(ty) => DataType::Number(*ty),
TableDataType::Decimal(ty) => DataType::Decimal(*ty),
TableDataType::Timestamp => DataType::Timestamp,
TableDataType::Date => DataType::Date,
TableDataType::Nullable(ty) => DataType::Nullable(Box::new((&**ty).into())),
TableDataType::Array(ty) => DataType::Array(Box::new((&**ty).into())),
TableDataType::Map(ty) => DataType::Map(Box::new((&**ty).into())),
TableDataType::Tuple { fields_type, .. } => {
DataType::Tuple(fields_type.iter().map(Into::into).collect())
}
TableDataType::Variant => DataType::Variant,
}
}
}
impl TableDataType {
pub fn wrap_nullable(&self) -> Self {
match self {
TableDataType::Nullable(_) => self.clone(),
_ => Self::Nullable(Box::new(self.clone())),
}
}
pub fn is_nullable(&self) -> bool {
matches!(self, &TableDataType::Nullable(_))
}
pub fn is_nullable_or_null(&self) -> bool {
matches!(self, &TableDataType::Nullable(_) | &TableDataType::Null)
}
pub fn can_inside_nullable(&self) -> bool {
!self.is_nullable_or_null()
}
pub fn remove_nullable(&self) -> Self {
match self {
TableDataType::Nullable(ty) => (**ty).clone(),
_ => self.clone(),
}
}
pub fn remove_recursive_nullable(&self) -> Self {
match self {
TableDataType::Nullable(ty) => ty.as_ref().remove_recursive_nullable(),
TableDataType::Tuple {
fields_name,
fields_type,
} => {
let mut new_fields_type = vec![];
for ty in fields_type {
new_fields_type.push(ty.remove_recursive_nullable());
}
TableDataType::Tuple {
fields_name: fields_name.clone(),
fields_type: new_fields_type,
}
}
TableDataType::Array(ty) => {
TableDataType::Array(Box::new(ty.as_ref().remove_recursive_nullable()))
}
TableDataType::Map(ty) => {
TableDataType::Map(Box::new(ty.as_ref().remove_recursive_nullable()))
}
_ => self.clone(),
}
}
pub fn wrapped_display(&self) -> String {
match self {
TableDataType::Nullable(inner_ty) => {
format!("Nullable({})", inner_ty.wrapped_display())
}
TableDataType::Tuple { fields_type, .. } => {
format!(
"Tuple({})",
fields_type.iter().map(|ty| ty.wrapped_display()).join(", ")
)
}
TableDataType::Array(inner_ty) => {
format!("Array({})", inner_ty.wrapped_display())
}
TableDataType::Map(inner_ty) => match *inner_ty.clone() {
TableDataType::Tuple {
fields_name: _fields_name,
fields_type,
} => {
format!(
"Map({}, {})",
fields_type[0].wrapped_display(),
fields_type[1].wrapped_display()
)
}
_ => unreachable!(),
},
_ => format!("{}", self),
}
}
pub fn sql_name(&self) -> String {
match self {
TableDataType::Number(num_ty) => match num_ty {
NumberDataType::UInt8 => "TINYINT UNSIGNED".to_string(),
NumberDataType::UInt16 => "SMALLINT UNSIGNED".to_string(),
NumberDataType::UInt32 => "INT UNSIGNED".to_string(),
NumberDataType::UInt64 => "BIGINT UNSIGNED".to_string(),
NumberDataType::Int8 => "TINYINT".to_string(),
NumberDataType::Int16 => "SMALLINT".to_string(),
NumberDataType::Int32 => "INT".to_string(),
NumberDataType::Int64 => "BIGINT".to_string(),
NumberDataType::Float32 => "FLOAT".to_string(),
NumberDataType::Float64 => "DOUBLE".to_string(),
},
TableDataType::String => "VARCHAR".to_string(),
TableDataType::Nullable(inner_ty) => format!("{} NULL", inner_ty.sql_name()),
_ => self.to_string().to_uppercase(),
}
}
// Returns the number of leaf columns of the TableDataType
pub fn num_leaf_columns(&self) -> usize {
match self {
TableDataType::Nullable(box inner_ty)
| TableDataType::Array(box inner_ty)
| TableDataType::Map(box inner_ty) => inner_ty.num_leaf_columns(),
TableDataType::Tuple { fields_type, .. } => fields_type
.iter()
.map(|inner_ty| inner_ty.num_leaf_columns())
.sum(),
_ => 1,
}
}
}
pub type DataSchemaRef = Arc<DataSchema>;
pub type TableSchemaRef = Arc<TableSchema>;
pub struct DataSchemaRefExt;
pub struct TableSchemaRefExt;
impl DataSchemaRefExt {
pub fn create(fields: Vec<DataField>) -> DataSchemaRef {
Arc::new(DataSchema::new(fields))
}
}
impl TableSchemaRefExt {
pub fn create(fields: Vec<TableField>) -> TableSchemaRef {
Arc::new(TableSchema::new(fields))
}
}
impl From<&ArrowSchema> for TableSchema {
fn from(a_schema: &ArrowSchema) -> Self {
let fields = a_schema
.fields
.iter()
.map(|arrow_f| arrow_f.into())
.collect::<Vec<_>>();
TableSchema::new(fields)
}
}
impl From<&TableField> for DataField {
fn from(f: &TableField) -> Self {
let data_type = f.data_type.clone();
let name = f.name.clone();
DataField::new(&name, DataType::from(&data_type)).with_default_expr(f.default_expr.clone())
}
}
impl<T: AsRef<TableSchema>> From<T> for DataSchema {
fn from(t_schema: T) -> Self {
let fields = t_schema
.as_ref()
.fields()
.iter()
.map(|t_f| t_f.into())
.collect::<Vec<_>>();
DataSchema::new(fields)
}
}
impl AsRef<TableSchema> for &TableSchema {
fn as_ref(&self) -> &TableSchema {
self
}
}
// conversions code
// =========================
impl From<&ArrowField> for TableField {
fn from(f: &ArrowField) -> Self {
Self {
name: f.name.clone(),
data_type: f.into(),
default_expr: None,
column_id: 0,
}
}
}
impl From<&ArrowField> for DataField {
fn from(f: &ArrowField) -> Self {
Self {
name: f.name.clone(),
data_type: DataType::from(&TableDataType::from(f)),
default_expr: None,
}
}
}
// ArrowType can't map to DataType, we don't know the nullable flag
impl From<&ArrowField> for TableDataType {
fn from(f: &ArrowField) -> Self {
let ty = with_number_type!(|TYPE| match f.data_type() {
ArrowDataType::TYPE => TableDataType::Number(NumberDataType::TYPE),
ArrowDataType::Decimal(precision, scale) =>
TableDataType::Decimal(DecimalDataType::Decimal128(DecimalSize {
precision: *precision as u8,
scale: *scale as u8,
})),
ArrowDataType::Decimal256(precision, scale) =>
TableDataType::Decimal(DecimalDataType::Decimal256(DecimalSize {
precision: *precision as u8,
scale: *scale as u8,
})),
ArrowDataType::Null => return TableDataType::Null,
ArrowDataType::Boolean => TableDataType::Boolean,
ArrowDataType::List(f)
| ArrowDataType::LargeList(f)
| ArrowDataType::FixedSizeList(f, _) =>
TableDataType::Array(Box::new(f.as_ref().into())),
ArrowDataType::Binary
| ArrowDataType::LargeBinary
| ArrowDataType::Utf8
| ArrowDataType::LargeUtf8 => TableDataType::String,
ArrowDataType::Timestamp(_, _) => TableDataType::Timestamp,
ArrowDataType::Date32 | ArrowDataType::Date64 => TableDataType::Date,
ArrowDataType::Map(f, _) => {
let inner_ty = f.as_ref().into();
TableDataType::Map(Box::new(inner_ty))
}
ArrowDataType::Struct(fields) => {
let (fields_name, fields_type) =
fields.iter().map(|f| (f.name.clone(), f.into())).unzip();
TableDataType::Tuple {
fields_name,
fields_type,
}
}
ArrowDataType::Extension(custom_name, _, _) => match custom_name.as_str() {
ARROW_EXT_TYPE_VARIANT => TableDataType::Variant,
ARROW_EXT_TYPE_EMPTY_ARRAY => TableDataType::EmptyArray,
ARROW_EXT_TYPE_EMPTY_MAP => TableDataType::EmptyMap,
_ => unimplemented!("data_type: {:?}", f.data_type()),
},
// this is safe, because we define the datatype firstly
_ => {
unimplemented!("data_type: {:?}", f.data_type())
}
});
if f.is_nullable {
TableDataType::Nullable(Box::new(ty))
} else {
ty
}
}
}
impl From<&DataField> for ArrowField {
fn from(f: &DataField) -> Self {
let ty = f.data_type().into();
match ty {
ArrowDataType::Struct(_) if f.is_nullable() => {
let ty = set_nullable(&ty);
ArrowField::new(f.name(), ty, f.is_nullable())
}
_ => ArrowField::new(f.name(), ty, f.is_nullable()),
}
}
}
impl From<&TableField> for ArrowField {
fn from(f: &TableField) -> Self {
let ty = f.data_type().into();
match ty {
ArrowDataType::Struct(_) if f.is_nullable() => {
let ty = set_nullable(&ty);
ArrowField::new(f.name(), ty, f.is_nullable())
}
_ => ArrowField::new(f.name(), ty, f.is_nullable()),
}
}
}
fn set_nullable(ty: &ArrowDataType) -> ArrowDataType {
// if the struct type is nullable, need to set inner fields as nullable
match ty {
ArrowDataType::Struct(fields) => {
let fields = fields
.iter()
.map(|f| {
let data_type = set_nullable(&f.data_type);
ArrowField::new(f.name.clone(), data_type, true)
})
.collect();
ArrowDataType::Struct(fields)
}
_ => ty.clone(),
}
}
impl From<&DataType> for ArrowDataType {
fn from(ty: &DataType) -> Self {
match ty {
DataType::Null => ArrowDataType::Null,
DataType::EmptyArray => ArrowDataType::Extension(
ARROW_EXT_TYPE_EMPTY_ARRAY.to_string(),
Box::new(ArrowDataType::Null),
None,
),
DataType::EmptyMap => ArrowDataType::Extension(
ARROW_EXT_TYPE_EMPTY_MAP.to_string(),
Box::new(ArrowDataType::Null),
None,
),
DataType::Boolean => ArrowDataType::Boolean,
DataType::String => ArrowDataType::LargeBinary,
DataType::Number(ty) => with_number_type!(|TYPE| match ty {
NumberDataType::TYPE => ArrowDataType::TYPE,
}),
DataType::Decimal(DecimalDataType::Decimal128(s)) => {
ArrowDataType::Decimal(s.precision.into(), s.scale.into())
}
DataType::Decimal(DecimalDataType::Decimal256(s)) => {
ArrowDataType::Decimal256(s.precision.into(), s.scale.into())
}
DataType::Timestamp => ArrowDataType::Timestamp(TimeUnit::Microsecond, None),
DataType::Date => ArrowDataType::Date32,
DataType::Nullable(ty) => ty.as_ref().into(),
DataType::Array(ty) => {
let arrow_ty = ty.as_ref().into();
ArrowDataType::LargeList(Box::new(ArrowField::new(
"_array",
arrow_ty,
ty.is_nullable(),
)))
}
DataType::Map(ty) => {
let inner_ty = match ty.as_ref() {
DataType::Tuple(tys) => {
let key_ty = ArrowDataType::from(&tys[0]);
let val_ty = ArrowDataType::from(&tys[1]);
let key_field = ArrowField::new("key", key_ty, tys[0].is_nullable());
let val_field = ArrowField::new("value", val_ty, tys[1].is_nullable());
ArrowDataType::Struct(vec![key_field, val_field])
}
_ => unreachable!(),
};
ArrowDataType::Map(
Box::new(ArrowField::new("entries", inner_ty, ty.is_nullable())),
false,
)
}
DataType::Tuple(types) => {
let fields = types
.iter()
.enumerate()
.map(|(index, ty)| {
let index = index + 1;
let name = format!("{index}");
ArrowField::new(name.as_str(), ty.into(), ty.is_nullable())
})
.collect();
ArrowDataType::Struct(fields)
}
DataType::Variant => ArrowDataType::Extension(
ARROW_EXT_TYPE_VARIANT.to_string(),
Box::new(ArrowDataType::LargeBinary),
None,
),
_ => unreachable!(),
}
}
}
impl From<&TableDataType> for ArrowDataType {
fn from(ty: &TableDataType) -> Self {
match ty {
TableDataType::Null => ArrowDataType::Null,
TableDataType::EmptyArray => ArrowDataType::Extension(
ARROW_EXT_TYPE_EMPTY_ARRAY.to_string(),
Box::new(ArrowDataType::Null),
None,
),
TableDataType::EmptyMap => ArrowDataType::Extension(
ARROW_EXT_TYPE_EMPTY_MAP.to_string(),
Box::new(ArrowDataType::Null),
None,
),
TableDataType::Boolean => ArrowDataType::Boolean,
TableDataType::String => ArrowDataType::LargeBinary,
TableDataType::Number(ty) => with_number_type!(|TYPE| match ty {
NumberDataType::TYPE => ArrowDataType::TYPE,
}),
TableDataType::Decimal(DecimalDataType::Decimal128(size)) => {
ArrowDataType::Decimal(size.precision as usize, size.scale as usize)
}
TableDataType::Decimal(DecimalDataType::Decimal256(size)) => {
ArrowDataType::Decimal256(size.precision as usize, size.scale as usize)
}
TableDataType::Timestamp => ArrowDataType::Timestamp(TimeUnit::Microsecond, None),
TableDataType::Date => ArrowDataType::Date32,
TableDataType::Nullable(ty) => ty.as_ref().into(),
TableDataType::Array(ty) => {
let arrow_ty = ty.as_ref().into();
ArrowDataType::LargeList(Box::new(ArrowField::new(
"_array",
arrow_ty,
ty.is_nullable(),
)))
}
TableDataType::Map(ty) => {
let inner_ty = match ty.as_ref() {
TableDataType::Tuple {
fields_name: _fields_name,
fields_type,
} => {
let key_ty = ArrowDataType::from(&fields_type[0]);
let val_ty = ArrowDataType::from(&fields_type[1]);
let key_field =
ArrowField::new("key", key_ty, fields_type[0].is_nullable());
let val_field =
ArrowField::new("value", val_ty, fields_type[1].is_nullable());
ArrowDataType::Struct(vec![key_field, val_field])
}
_ => unreachable!(),
};
ArrowDataType::Map(
Box::new(ArrowField::new("entries", inner_ty, ty.is_nullable())),
false,
)
}
TableDataType::Tuple {
fields_name,
fields_type,
} => {
let fields = fields_name
.iter()
.zip(fields_type)
.map(|(name, ty)| ArrowField::new(name.as_str(), ty.into(), ty.is_nullable()))
.collect();
ArrowDataType::Struct(fields)
}
TableDataType::Variant => ArrowDataType::Extension(
ARROW_EXT_TYPE_VARIANT.to_string(),
Box::new(ArrowDataType::LargeBinary),
None,
),
}
}
}
/// Convert a `DataType` to `TableDataType`.
/// Generally, we don't allow to convert `DataType` to `TableDataType` directly.
/// But for some special cases, for example creating table from a query without specifying
/// the schema. Then we need to infer the corresponding `TableDataType` from `DataType`, and
/// this function may report an error if the conversion is not allowed.
///
/// Do not use this function in other places.
pub fn infer_schema_type(data_type: &DataType) -> Result<TableDataType> {
match data_type {
DataType::Null => Ok(TableDataType::Null),
DataType::Boolean => Ok(TableDataType::Boolean),
DataType::EmptyArray => Ok(TableDataType::EmptyArray),
DataType::EmptyMap => Ok(TableDataType::EmptyMap),
DataType::String => Ok(TableDataType::String),
DataType::Number(number_type) => Ok(TableDataType::Number(*number_type)),
DataType::Timestamp => Ok(TableDataType::Timestamp),
DataType::Decimal(x) => Ok(TableDataType::Decimal(*x)),
DataType::Date => Ok(TableDataType::Date),
DataType::Nullable(inner_type) => Ok(TableDataType::Nullable(Box::new(infer_schema_type(
inner_type,
)?))),
DataType::Array(elem_type) => Ok(TableDataType::Array(Box::new(infer_schema_type(
elem_type,
)?))),
DataType::Map(inner_type) => {
Ok(TableDataType::Map(Box::new(infer_schema_type(inner_type)?)))
}
DataType::Variant => Ok(TableDataType::Variant),
DataType::Tuple(fields) => {
let fields_type = fields
.iter()
.map(infer_schema_type)
.collect::<Result<Vec<_>>>()?;
let fields_name = fields
.iter()
.enumerate()
.map(|(idx, _)| (idx + 1).to_string())
.collect::<Vec<_>>();
Ok(TableDataType::Tuple {
fields_name,
fields_type,
})
}
DataType::Generic(_) => Err(ErrorCode::SemanticError(format!(
"Cannot create table with type: {}",
data_type
))),
}
}
/// Infer TableSchema from DataSchema, this is useful when creating table from a query.
pub fn infer_table_schema(data_schema: &DataSchemaRef) -> Result<TableSchemaRef> {
let mut fields = Vec::with_capacity(data_schema.fields().len());
for field in data_schema.fields() {
let field_type = infer_schema_type(field.data_type())?;
fields.push(TableField::new(field.name(), field_type));
}
Ok(TableSchemaRefExt::create(fields))
}
// a complex schema to cover all data types tests.
pub fn create_test_complex_schema() -> TableSchema {
let child_field11 = TableDataType::Number(NumberDataType::UInt64);
let child_field12 = TableDataType::Number(NumberDataType::UInt64);
let child_field22 = TableDataType::Number(NumberDataType::UInt64);
let s = TableDataType::Tuple {
fields_name: vec!["0".to_string(), "1".to_string()],
fields_type: vec![child_field11, child_field12],
};
let tuple = TableDataType::Tuple {
fields_name: vec!["0".to_string(), "1".to_string()],
fields_type: vec![s.clone(), TableDataType::Array(Box::new(child_field22))],
};
let array = TableDataType::Array(Box::new(s));
let nullarray = TableDataType::Nullable(Box::new(TableDataType::Array(Box::new(
TableDataType::Number(NumberDataType::UInt64),
))));
let maparray = TableDataType::Map(Box::new(TableDataType::Tuple {
fields_name: vec!["key".to_string(), "value".to_string()],
fields_type: vec![
TableDataType::Number(NumberDataType::UInt64),
TableDataType::String,
],
}));
let field1 = TableField::new("u64", TableDataType::Number(NumberDataType::UInt64));
let field2 = TableField::new("tuplearray", tuple);
let field3 = TableField::new("arraytuple", array);
let field4 = TableField::new("nullarray", nullarray);
let field5 = TableField::new("maparray", maparray);
let field6 = TableField::new(
"nullu64",
TableDataType::Nullable(Box::new(TableDataType::Number(NumberDataType::UInt64))),
);
let field7 = TableField::new(
"u64array",
TableDataType::Array(Box::new(TableDataType::Number(NumberDataType::UInt64))),
);
let field8 = TableField::new("tuplesimple", TableDataType::Tuple {
fields_name: vec!["a".to_string(), "b".to_string()],
fields_type: vec![
TableDataType::Number(NumberDataType::Int32),
TableDataType::Number(NumberDataType::Int32),
],
});
TableSchema::new(vec![
field1, field2, field3, field4, field5, field6, field7, field8,
])
}
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
mod cluster;
pub mod config;
pub mod filters;
pub(crate) mod metrics;
pub mod proxy;
pub mod runner;
pub mod test_utils;
pub(crate) mod utils;
pub(crate) mod xds;
pub use quilkin_macros::{filter, include_proto};
/// Run tests in our external documentation. This is only available in
/// nightly at the moment, but is stable on nightly and will be available in
/// 1.54.0. To run them locally run e.g `cargo +nightly test --doc`.
#[cfg(doctest)]
mod external_doc_tests {
// HACK(XAMPPRocky): This is hidden inside a macro, because the right hand
// side of `include_str!` is parsed before the `cfg` predicate currently.
// https://github.com/rust-lang/rust/issues/85882
macro_rules! hide {
() => {
#[doc = include_str!("../docs/extensions/filters/filters.md")]
#[doc = include_str!("../docs/extensions/filters/writing_custom_filters.md")]
#[doc = include_str!("../docs/extensions/filters/load_balancer.md")]
#[doc = include_str!("../docs/extensions/filters/local_rate_limit.md")]
#[doc = include_str!("../docs/extensions/filters/debug.md")]
#[doc = include_str!("../docs/extensions/filters/concatenate_bytes.md")]
#[doc = include_str!("../docs/extensions/filters/capture_bytes.md")]
#[doc = include_str!("../docs/extensions/filters/token_router.md")]
#[doc = include_str!("../docs/extensions/filters/compress.md")]
mod tests {}
};
}
hide!();
}
|
// 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.
#![allow(clippy::uninlined_format_args)]
#![feature(try_blocks)]
mod local;
use std::env;
use common_base::mem_allocator::GlobalAllocator;
use common_base::runtime::Runtime;
use common_base::runtime::GLOBAL_MEM_STAT;
use common_base::set_alloc_error_hook;
use common_config::InnerConfig;
use common_config::DATABEND_COMMIT_VERSION;
use common_config::QUERY_SEMVER;
use common_exception::ErrorCode;
use common_exception::Result;
use common_meta_client::MIN_METASRV_SEMVER;
use common_metrics::init_default_metrics_recorder;
use common_tracing::set_panic_hook;
use databend_query::api::HttpService;
use databend_query::api::RpcService;
use databend_query::clusters::ClusterDiscovery;
use databend_query::metrics::MetricService;
use databend_query::servers::FlightSQLServer;
use databend_query::servers::HttpHandler;
use databend_query::servers::HttpHandlerKind;
use databend_query::servers::MySQLHandler;
use databend_query::servers::Server;
use databend_query::servers::ShutdownHandle;
use databend_query::GlobalServices;
use tracing::info;
#[global_allocator]
pub static GLOBAL_ALLOCATOR: GlobalAllocator = GlobalAllocator;
fn main() {
match Runtime::with_default_worker_threads() {
Err(cause) => {
eprintln!("Databend Query start failure, cause: {:?}", cause);
std::process::exit(cause.code() as i32);
}
Ok(rt) => {
if let Err(cause) = rt.block_on(main_entrypoint()) {
eprintln!("Databend Query start failure, cause: {:?}", cause);
std::process::exit(cause.code() as i32);
}
}
}
}
async fn main_entrypoint() -> Result<()> {
let conf: InnerConfig = InnerConfig::load()?;
if run_cmd(&conf).await? {
return Ok(());
}
init_default_metrics_recorder();
set_panic_hook();
set_alloc_error_hook();
#[cfg(target_arch = "x86_64")]
{
if !std::is_x86_feature_detected!("sse4.2") {
println!(
"Current pre-built binary is typically compiled for x86_64 and leverage SSE 4.2 instruction set, you can build your own binary from source"
);
return Ok(());
}
}
if conf.meta.is_embedded_meta()? {
return Err(ErrorCode::Unimplemented(
"Embedded meta is an deployment method and will not be supported since March 2023.",
));
}
// Make sure global services have been inited.
GlobalServices::init(conf.clone()).await?;
if conf.query.max_memory_limit_enabled {
let size = conf.query.max_server_memory_usage as i64;
info!("Set memory limit: {}", size);
GLOBAL_MEM_STAT.set_limit(size);
}
let tenant = conf.query.tenant_id.clone();
let cluster_id = conf.query.cluster_id.clone();
let flight_addr = conf.query.flight_api_address.clone();
let mut _sentry_guard = None;
let bend_sentry_env = env::var("DATABEND_SENTRY_DSN").unwrap_or_else(|_| "".to_string());
if !bend_sentry_env.is_empty() {
// NOTE: `traces_sample_rate` is 0.0 by default, which disable sentry tracing.
let traces_sample_rate = env::var("SENTRY_TRACES_SAMPLE_RATE").ok().map_or(0.0, |s| {
s.parse()
.unwrap_or_else(|_| panic!("`{}` was defined but could not be parsed", s))
});
_sentry_guard = Some(sentry::init((bend_sentry_env, sentry::ClientOptions {
release: common_tracing::databend_semver!(),
traces_sample_rate,
..Default::default()
})));
sentry::configure_scope(|scope| scope.set_tag("tenant", tenant));
sentry::configure_scope(|scope| scope.set_tag("cluster_id", cluster_id));
sentry::configure_scope(|scope| scope.set_tag("address", flight_addr));
}
#[cfg(not(target_os = "macos"))]
check_max_open_files();
let mut shutdown_handle = ShutdownHandle::create()?;
info!("Databend Query start with config: {:?}", conf);
// MySQL handler.
{
let hostname = conf.query.mysql_handler_host.clone();
let listening = format!("{}:{}", hostname, conf.query.mysql_handler_port);
let tcp_keepalive_timeout_secs = conf.query.mysql_handler_tcp_keepalive_timeout_secs;
let mut handler = MySQLHandler::create(tcp_keepalive_timeout_secs)?;
let listening = handler.start(listening.parse()?).await?;
shutdown_handle.add_service(handler);
info!(
"Listening for MySQL compatibility protocol: {}, Usage: mysql -uroot -h{} -P{}",
listening,
listening.ip(),
listening.port(),
);
}
// ClickHouse HTTP handler.
{
let hostname = conf.query.clickhouse_http_handler_host.clone();
let listening = format!("{}:{}", hostname, conf.query.clickhouse_http_handler_port);
let mut srv = HttpHandler::create(HttpHandlerKind::Clickhouse);
let listening = srv.start(listening.parse()?).await?;
shutdown_handle.add_service(srv);
let http_handler_usage = HttpHandlerKind::Clickhouse.usage(listening);
info!(
"Listening for ClickHouse compatibility http protocol: {}, Usage: {}",
listening, http_handler_usage
);
}
// Databend HTTP handler.
{
let hostname = conf.query.http_handler_host.clone();
let listening = format!("{}:{}", hostname, conf.query.http_handler_port);
let mut srv = HttpHandler::create(HttpHandlerKind::Query);
let listening = srv.start(listening.parse()?).await?;
shutdown_handle.add_service(srv);
let http_handler_usage = HttpHandlerKind::Query.usage(listening);
info!(
"Listening for Databend HTTP API: {}, Usage: {}",
listening, http_handler_usage
);
}
// Metric API service.
{
let address = conf.query.metric_api_address.clone();
let mut srv = MetricService::create();
let listening = srv.start(address.parse()?).await?;
shutdown_handle.add_service(srv);
info!("Listening for Metric API: {}/metrics", listening);
}
// Admin HTTP API service.
{
let address = conf.query.admin_api_address.clone();
let mut srv = HttpService::create(&conf);
let listening = srv.start(address.parse()?).await?;
shutdown_handle.add_service(srv);
info!("Listening for Admin HTTP API: {}", listening);
}
// FlightSQL API service.
{
let address = format!(
"{}:{}",
conf.query.flight_sql_handler_host, conf.query.flight_sql_handler_port
);
let mut srv = FlightSQLServer::create(conf.clone())?;
let listening = srv.start(address.parse()?).await?;
shutdown_handle.add_service(srv);
info!("Listening for FlightSQL API: {}", listening);
}
// RPC API service.
{
let address = conf.query.flight_api_address.clone();
let mut srv = RpcService::create(conf.clone())?;
let listening = srv.start(address.parse()?).await?;
shutdown_handle.add_service(srv);
info!("Listening for RPC API (interserver): {}", listening);
}
// Cluster register.
{
ClusterDiscovery::instance()
.register_to_metastore(&conf)
.await?;
info!(
"Databend query has been registered:{:?} to metasrv:{:?}.",
conf.query.cluster_id, conf.meta.endpoints
);
}
// Print information to users.
println!("Databend Query");
println!();
println!("Version: {}", *DATABEND_COMMIT_VERSION);
println!();
println!("Logging:");
println!(" file: {}", conf.log.file);
println!(" stderr: {}", conf.log.stderr);
println!(
"Meta: {}",
if conf.meta.is_embedded_meta()? {
format!("embedded at {}", conf.meta.embedded_dir)
} else {
format!("connected to endpoints {:#?}", conf.meta.endpoints)
}
);
println!("Memory:");
println!(" limit: {}", {
if conf.query.max_memory_limit_enabled {
format!(
"Memory: server memory limit to {} (bytes)",
conf.query.max_server_memory_usage
)
} else {
"unlimited".to_string()
}
});
println!(" allocator: {}", GlobalAllocator::name());
println!(" config: {}", GlobalAllocator::conf());
println!("Cluster: {}", {
let cluster = ClusterDiscovery::instance().discover(&conf).await?;
let nodes = cluster.nodes.len();
if nodes > 1 {
format!("[{}] nodes", nodes)
} else {
"standalone".to_string()
}
});
println!("Storage: {}", conf.storage.params);
println!("Cache: {}", conf.cache.data_cache_storage.to_string());
println!(
"Builtin users: {}",
conf.query
.idm
.users
.keys()
.map(|name| name.to_string())
.collect::<Vec<_>>()
.join(", ")
);
println!();
println!("Admin");
println!(" listened at {}", conf.query.admin_api_address);
println!("MySQL");
println!(
" listened at {}:{}",
conf.query.mysql_handler_host, conf.query.mysql_handler_port
);
println!(
" connect via: mysql -uroot -h{} -P{}",
conf.query.mysql_handler_host, conf.query.mysql_handler_port
);
println!("Clickhouse(http)");
println!(
" listened at {}:{}",
conf.query.clickhouse_http_handler_host, conf.query.clickhouse_http_handler_port
);
println!(
" usage: {}",
HttpHandlerKind::Clickhouse.usage(
format!(
"{}:{}",
conf.query.clickhouse_http_handler_host, conf.query.clickhouse_http_handler_port
)
.parse()?
)
);
println!("Databend HTTP");
println!(
" listened at {}:{}",
conf.query.http_handler_host, conf.query.http_handler_port
);
println!(
" usage: {}",
HttpHandlerKind::Query.usage(
format!(
"{}:{}",
conf.query.http_handler_host, conf.query.http_handler_port
)
.parse()?
)
);
info!("Ready for connections.");
shutdown_handle.wait_for_termination_request().await;
info!("Shutdown server.");
Ok(())
}
async fn run_cmd(conf: &InnerConfig) -> Result<bool> {
if conf.cmd.is_empty() {
return Ok(false);
}
match conf.cmd.as_str() {
"ver" => {
println!("version: {}", *QUERY_SEMVER);
println!("min-compatible-metasrv-version: {}", MIN_METASRV_SEMVER);
}
"local" => {
println!("exec local query: {}", conf.local.sql);
local::query_local(conf).await?
}
_ => {
eprintln!("Invalid cmd: {}", conf.cmd);
eprintln!("Available cmds:");
eprintln!(" --cmd ver");
eprintln!(" Print version and the min compatible databend-meta version");
}
}
Ok(true)
}
#[cfg(not(target_os = "macos"))]
fn check_max_open_files() {
let limits = match limits_rs::get_own_limits() {
Ok(limits) => limits,
Err(err) => {
tracing::warn!("get system limit of databend-query failed: {:?}", err);
return;
}
};
let max_open_files_limit = limits.max_open_files.soft;
if let Some(max_open_files) = max_open_files_limit {
if max_open_files < 65535 {
tracing::warn!(
"The open file limit is too low for the databend-query. Please consider increase it by running `ulimit -n 65535`"
);
}
}
}
|
use crate::base::data::inverse_fields_map::INVERSE_FIELDS_MAP;
use crate::base::serialize::serialized_type::*;
//TypeObjBulder usage.
//let type_obj = TypeObjBuilder::new("key").build();
//println!("type_obj: {:?}", type_obj);
//header
pub trait SerializeHeader {
fn serialize_header(&self, so: &mut Vec<u8>);
}
#[derive(Debug)]
pub struct TypeObj {
pub type_tag: u8,
pub type_bits: u8 ,
pub field_bits: u8,
}
impl TypeObj {
pub fn new(type_tag: u8, type_bits: u8, field_bits: u8) -> Self {
TypeObj {
type_tag: type_tag,
type_bits: type_bits,
field_bits: field_bits,
}
}
}
impl SerializeHeader for TypeObj {
fn serialize_header(&self, so: &mut Vec<u8>) {
let mut s8 = STInt8::serialize(self.type_tag);
so.append(&mut s8);
if self.type_bits >= 16 {
let mut s = STInt8::serialize(self.type_bits);
so.append(&mut s);
}
if self.field_bits >= 16 {
let mut x = STInt8::serialize(self.field_bits);
so.append(&mut x);
}
}
}
pub struct TypeObjBuilder {
pub key: &'static str,
//inner status
type_bits: Option<u8>,
field_bits: Option<u8>,
type_tag: Option<u8>,
}
impl TypeObjBuilder {
pub fn new(key: &'static str) -> Self {
TypeObjBuilder {
key: key,
type_bits: None,
field_bits: None,
type_tag: None,
}
}
pub fn build(&mut self) -> Option<TypeObj> {
//type_bits
self.calc_type_bits();
//field_bits
self.calc_field_bits();
//type_tag
self.calc_type_tag();
//New TypeObj
Some(TypeObj::new(self.type_tag.unwrap(), self.type_bits.unwrap(), self.field_bits.unwrap()))
}
//Inner methods
fn calc_type_bits(&mut self) {
let field_coordinates = INVERSE_FIELDS_MAP.get(self.key).unwrap();
self.type_bits = Some(field_coordinates[0]);
}
fn calc_field_bits(&mut self) {
let field_coordinates = INVERSE_FIELDS_MAP.get(self.key).unwrap();
self.field_bits = Some(field_coordinates[1]);
}
fn calc_type_tag(&mut self) {
let left = if self.type_bits.unwrap() < 16 { self.type_bits.unwrap() << 4 } else { 0 };
let right = if self.field_bits.unwrap() < 16 { self.field_bits.unwrap() } else { 0 };
self.type_tag = Some(left | right);
}
}
|
#[derive(Debug)]
enum Participant {
CAR,
TRAIN
}
#[derive(Debug)]
enum ParticipantCommand {
GO,
STOP
}
fn move_barriers_mediator(p: &Participant, c: ParticipantCommand) {
println!("Mediation!");
match *p {
Participant::CAR => {
match c {
ParticipantCommand::GO => {
println!("Opening barrier {:?} {:?}", c, p);
}
ParticipantCommand::STOP => {
println!("Closing barrier {:?} {:?}", c, p);
}
}
}
Participant::TRAIN => {
match c {
ParticipantCommand::GO => {
println!("Closing barrier {:?} {:?}", c, p);
}
ParticipantCommand::STOP => {
println!("Opening barrier {:?} {:?}", c, p);
}
}
}
}
}
fn participant<F>(p: Participant, mediator: F) -> Box<Fn(ParticipantCommand)>
where F: Fn(&Participant, ParticipantCommand) + 'static {
Box::new(
move |action: ParticipantCommand| {
match action {
ParticipantCommand::GO => {
mediator(&p, action);
println!("{:?} passing!", p);
}
ParticipantCommand::STOP => {
mediator(&p, action);
println!("{:?} waiting!", p);
}
}
}
)
}
pub fn run() {
println!("-------------------- {} --------------------", file!());
let car = participant(Participant::CAR, move_barriers_mediator);
let train = participant(Participant::TRAIN, move_barriers_mediator);
car(ParticipantCommand::GO);
train(ParticipantCommand::GO);
car(ParticipantCommand::STOP);
train(ParticipantCommand::STOP);
} |
// Copyright 2018 Steve Smith (tarkasteve@gmail.com). See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io;
// Borrowed from std::fs::unix.
pub trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
macro_rules! impl_is_minus_one {
($($t:ident)*) => ($(impl IsMinusOne for $t {
fn is_minus_one(&self) -> bool {
*self == -1
}
})*)
}
impl_is_minus_one! { i8 i16 i32 i64 isize }
pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
if t.is_minus_one() {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where T: IsMinusOne,
F: FnMut() -> T
{
loop {
match cvt(f()) {
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
other => return other,
}
}
}
|
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use super::{Statement, StatementParser};
use crate::lexer::lexer::{Lexer, LocToken, Token};
use crate::lexer::preprocessor::context::PreprocContext;
use crate::parser::attributes::Attributes;
use crate::parser::declarations::{TypeDeclarator, TypeDeclaratorParser};
#[derive(Clone, Debug, PartialEq)]
pub struct Try {
pub attributes: Option<Attributes>,
pub body: Box<Statement>,
pub clause: Option<TypeDeclarator>,
pub handler: Box<Statement>,
}
pub struct TryStmtParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> TryStmtParser<'a, 'b, PC> {
pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(super) fn parse(self, attributes: Option<Attributes>) -> (Option<LocToken>, Option<Try>) {
let sp = StatementParser::new(self.lexer);
let (tok, body) = sp.parse(None);
let body = if let Some(body) = body {
body
} else {
unreachable!("Invalid token in try: {:?}", tok);
};
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
if tok.tok != Token::Catch {
unreachable!("Catch expected after body in try statement");
}
let tok = self.lexer.next_useful();
if tok.tok != Token::LeftParen {
unreachable!("Invalid token in catch clause: {:?}", tok);
}
let tok = self.lexer.next_useful();
let (tok, clause) = if tok.tok == Token::Ellipsis {
(None, None)
} else {
let tp = TypeDeclaratorParser::new(self.lexer);
let (tok, typ) = tp.parse(Some(tok), None);
if typ.is_some() {
(tok, typ)
} else {
unreachable!("Invalid token in catch clause: {:?}", tok);
}
};
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
if tok.tok != Token::RightParen {
unreachable!("Invalid token in catch clause: {:?}", tok);
}
let sp = StatementParser::new(self.lexer);
let (tok, handler) = sp.parse(None);
let handler = if let Some(handler) = handler {
handler
} else {
unreachable!("Invalid token in try handler: {:?}", tok);
};
(
tok,
Some(Try {
attributes,
body: Box::new(body),
clause,
handler: Box::new(handler),
}),
)
}
}
|
// Copyright 2016 Sascha Haeberling
//
// 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::HashSet;
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn read_file() -> Result<String, io::Error> {
let mut f = try!(File::open("../data/aoc/2016/day1.txt"));
let mut s = String::new();
try!(f.read_to_string(&mut s));
Ok(s)
}
fn process(content: String) {
let split: Vec<&str> = content.split(", ").collect();
println!("Item num: {}", split.len());
let mut pos_x:i32 = 0;
let mut pos_y:i32= 0;
let mut dir_x = 0;
let mut dir_y = 1;
let mut visited_location = HashSet::new();
let mut solution_b :i32 = -1;
for cmd in &split {
let direction = &cmd[..1];
if dir_x == 0 {
dir_x = dir_y * (if direction == "L" { -1 } else { 1 });
dir_y = 0;
} else {
dir_y = dir_x * (if direction == "L" { 1 } else { -1 });
dir_x = 0;
}
let amount = &cmd[1..].parse::<i32>().unwrap();
let mut x :i32 = 0;
loop {
pos_x += dir_x;
pos_y += dir_y;
let pos_str = format!("{},{}", pos_x, pos_y);
if solution_b == -1 && visited_location.contains(&pos_str) {
solution_b = pos_x.abs() + pos_y.abs();
}
visited_location.insert(pos_str);
x += 1;
if &x == amount {
break;
}
}
}
println!("Solution A: {}, Solution B: {}", pos_x.abs() + pos_y.abs(), solution_b);
}
fn main() {
println!("AOC Puzzle 1");
let file_result = read_file();
match file_result {
Ok(file) => process(file),
Err(e) => {
println!("Ooops. {}", e);
return ();
},
};
}
|
use once_cell::sync::OnceCell;
use tauri_api::cli::Matches;
static MATCHES: OnceCell<Matches> = OnceCell::new();
pub(crate) fn set_matches(matches: Matches) -> crate::Result<()> {
MATCHES
.set(matches)
.map_err(|_| anyhow::anyhow!("failed to set once_cell matches"))
}
pub fn get_matches() -> Option<&'static Matches> {
MATCHES.get()
}
|
pub fn compress<T: Copy + PartialEq>(li: &Vec<T>) -> Vec<T> {
if li.is_empty() {
vec![]
} else {
let mut res = vec![li[0]];
for i in 1..li.len() {
if li.get(i) != res.last() {
res.push(*li.get(i).unwrap());
}
}
res
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compress() {
let li = vec![
'a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e',
];
assert_eq!(compress(&li), vec!['a', 'b', 'c', 'a', 'd', 'e']);
}
#[test]
fn test_compress_empty() {
let li: Vec<i32> = vec![];
assert_eq!(compress(&li), vec![]);
}
}
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:issue-50061.rs
// ignore-stage1
#![feature(proc_macro_path_invoc, decl_macro)]
extern crate issue_50061;
macro inner(any_token $v: tt) {
$v
}
macro outer($v: tt) {
inner!(any_token $v)
}
#[issue_50061::check]
fn main() {
//! this doc comment forces roundtrip through a string
let checkit = 0;
outer!(checkit);
}
|
mod printing {
pub mod math{
pub fn table(data:u32){
println!("Calcuations");
for count in 1..=3{
println!("{}*{}={}", data,count,data*count);
}
}
}
}
pub mod lib;
use std::io;
fn main() {
loop {
println!("Please input your number:");
let mut input1= String::new();
io::stdin().read_line(&mut input1)
.expect("failed to read line");
// let input1:u32= input1.trim().parse().unwrap();
let input1: u32 = match input1.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You Entered: {}",input1);
crate::printing::math::table(input1);
printing::math::table(input1);
lib::table(input1);
break;
}
} |
use std::time::{Duration, SystemTime};
use std::fs::File;
use pcap_file::PcapWriter;
use super::options::*;
pub fn do_command<T, I, E>(radio: &mut T, operation: Operation) -> Result<(), E>
where
T: radio::Transmit<Error=E> + radio::Power<Error=E> + radio::Receive<Info=I, Error=E> + radio::Rssi<Error=E> + radio::Power<Error=E>,
I: Default + std::fmt::Debug,
E: std::fmt::Debug,
{
// TODO: the rest
match operation {
Operation::Transmit(config) => {
do_transmit(radio, config.data.as_bytes(), config.power, config.continuous, *config.period, *config.poll_interval)
.expect("Transmit error")
},
Operation::Receive(config) => {
let mut buff = [0u8; 255];
let mut info = I::default();
do_receive(radio, &mut buff, &mut info, config.continuous, *config.poll_interval, config.pcap_file)
.expect("Receive error");
},
Operation::Repeat(config) => {
let mut buff = [0u8; 255];
let mut info = I::default();
do_repeat(radio, &mut buff, &mut info, config.power, config.continuous, *config.delay, *config.poll_interval)
.expect("Repeat error");
}
Operation::Rssi(config) => {
do_rssi(radio, config.continuous, *config.period)
.expect("RSSI error");
},
//_ => warn!("unsuppored command: {:?}", opts.command),
}
Ok(())
}
fn do_transmit<T, E>(radio: &mut T, data: &[u8], power: Option<i8>, continuous: bool, period: Duration, poll_interval: Duration) -> Result<(), E>
where
T: radio::Transmit<Error=E> + radio::Power<Error=E>
{
// Set output power if specified
if let Some(p) = power {
radio.set_power(p)?;
}
loop {
radio.start_transmit(data)?;
loop {
if radio.check_transmit()? {
debug!("Send complete");
break;
}
std::thread::sleep(poll_interval);
}
if !continuous { break; }
std::thread::sleep(period);
}
Ok(())
}
fn do_receive<T, I, E>(radio: &mut T, mut buff: &mut [u8], mut info: &mut I, continuous: bool, poll_interval: Duration, pcap_file: Option<String>) -> Result<usize, E>
where
T: radio::Receive<Info=I, Error=E>,
I: std::fmt::Debug,
{
// Load PCAP file
let mut pcap = match pcap_file {
Some(n) => {
let f = File::create(n).expect("Error creating PCAP file");
let w = PcapWriter::new(f).expect("Error writing to PCAP file");
Some(w)
},
None => None,
};
let t = SystemTime::now();
// Start receive mode
radio.start_receive()?;
loop {
if radio.check_receive(true)? {
let n = radio.get_received(&mut info, &mut buff)?;
match std::str::from_utf8(&buff[0..n as usize]) {
Ok(s) => info!("Received: '{}' info: {:?}", s, info),
Err(_) => info!("Received: '{:?}' info: {:?}", &buff[0..n as usize], info),
}
if let Some(p) = &mut pcap {
let d = t.elapsed().unwrap();
p.write(d.as_secs() as u32, d.as_nanos() as u32 % 1_000_000, &buff[0..n], n as u32).expect("Error writing pcap file");
}
if !continuous {
return Ok(n)
}
radio.start_receive()?;
}
std::thread::sleep(poll_interval);
}
}
fn do_rssi<T, I, E>(radio: &mut T, continuous: bool, period: Duration) -> Result<(), E>
where
T: radio::Receive<Info=I, Error=E> + radio::Rssi<Error=E>,
I: std::fmt::Debug,
{
// Enter receive mode
radio.start_receive()?;
// Poll for RSSI
loop {
let rssi = radio.poll_rssi()?;
info!("rssi: {}", rssi);
radio.check_receive(true)?;
std::thread::sleep(period);
if !continuous {
break
}
}
Ok(())
}
fn do_repeat<T, I, E>(radio: &mut T, mut buff: &mut [u8], mut info: &mut I, power: Option<i8>, continuous: bool, delay: Duration, poll_interval: Duration) -> Result<usize, E>
where
T: radio::Receive<Info=I, Error=E> + radio::Transmit<Error=E> + radio::Power<Error=E>,
I: std::fmt::Debug,
{
// Set output power if specified
if let Some(p) = power {
radio.set_power(p)?;
}
// Start receive mode
radio.start_receive()?;
loop {
if radio.check_receive(true)? {
let n = radio.get_received(&mut info, &mut buff)?;
match std::str::from_utf8(&buff[0..n as usize]) {
Ok(s) => info!("Received: '{}' info: {:?}", s, info),
Err(_) => info!("Received: '{:?}' info: {:?}", &buff[0..n as usize], info),
}
std::thread::sleep(delay);
radio.start_transmit(&buff[..n])?;
loop {
if radio.check_transmit()? {
debug!("Send complete");
break;
}
std::thread::sleep(poll_interval);
}
if !continuous { return Ok(n) }
}
std::thread::sleep(poll_interval);
}
}
|
use crate::{
builder::{
self, session_setup_authenticate_request::build_default_session_setup_authenticate_request,
session_setup_negotiate_request::build_default_session_setup_negotiate_request,
},
format,
fuzzer::{self, FuzzingStrategy},
ntlmssp::MessageType,
smb2::{
header,
requests::{
self, close::Close, create::Create, echo::Echo, negotiate::Negotiate,
query_info::QueryInfo, tree_connect::TreeConnect, RequestType,
},
responses,
},
};
/// Builds the negotiate packet according to the fuzzing strategy if given.
/// Otherwise the default negotiate packet is built.
pub fn prepare_negotiate_packet(fuzzing_strategy: Option<FuzzingStrategy>) -> Vec<u8> {
let mut negotiate_request: (Option<header::SyncHeader>, Option<Negotiate>) = (None, None);
if let Some(strategy) = fuzzing_strategy {
negotiate_request.0 = Some(builder::build_sync_header(
header::Commands::Negotiate,
0,
0,
None,
None,
0,
));
negotiate_request.1 = Some(match strategy {
FuzzingStrategy::Predefined => {
fuzzer::handshake::negotiate_fuzzer::fuzz_negotiate_with_predefined_values()
}
FuzzingStrategy::RandomFields => {
fuzzer::handshake::negotiate_fuzzer::fuzz_negotiate_with_random_fields()
}
FuzzingStrategy::CompletelyRandom => {
fuzzer::handshake::negotiate_fuzzer::fuzz_negotiate_completely_random()
}
});
} else {
negotiate_request = builder::negotiate_request::build_default_negotiate_request();
}
if let (Some(head), Some(body)) = (negotiate_request.0, negotiate_request.1) {
format::encoder::serialize_request(&head, &RequestType::Negotiate(body))
} else {
panic!("Could not populate negotiate packet.")
}
}
/// Builds the first session setup packet according to the fuzzing strategy if given.
/// Otherwise the default session setup 1 packet is built.
pub fn prepare_session_setup_negotiate_packet(
fuzzing_strategy: Option<FuzzingStrategy>,
) -> Vec<u8> {
let mut session_setup_request: (
Option<header::SyncHeader>,
Option<requests::session_setup::SessionSetup>,
) = (None, None);
if let Some(strategy) = fuzzing_strategy {
session_setup_request.0 = Some(builder::build_sync_header(
header::Commands::SessionSetup,
1,
8192,
None,
None,
1,
));
session_setup_request.1 = Some(
match strategy {
FuzzingStrategy::Predefined => fuzzer::handshake::session_setup_fuzzer::fuzz_session_setup_negotiate_with_predefined_values(),
FuzzingStrategy::RandomFields => fuzzer::handshake::session_setup_fuzzer::fuzz_session_setup_with_random_fields(),
FuzzingStrategy::CompletelyRandom => fuzzer::handshake::session_setup_fuzzer::fuzz_session_setup_completely_random(),
}
);
} else {
session_setup_request = build_default_session_setup_negotiate_request();
}
if let (Some(head), Some(body)) = session_setup_request {
format::encoder::serialize_request(&head, &RequestType::SessionSetupNeg(body))
} else {
panic!("Could not populate session setup 1 packet.")
}
}
/// Builds the second session setup packet according to the fuzzing strategy if given.
/// Otherwise the default session setup 2 packet is built.
pub fn prepare_session_setup_authenticate_packet(
fuzzing_strategy: Option<FuzzingStrategy>,
session_id: Vec<u8>,
session_setup_response_body: responses::session_setup::SessionSetup,
) -> Vec<u8> {
let mut session_setup_request: (
Option<header::SyncHeader>,
Option<requests::session_setup::SessionSetup>,
) = (None, None);
let challenge_struct = match format::decoder::security_blob_decoder::decode_security_response(
session_setup_response_body.buffer,
)
.message
.unwrap()
{
MessageType::Challenge(challenge) => challenge,
_ => panic!("Invalid message type in server response."),
};
if let Some(strategy) = fuzzing_strategy {
session_setup_request.0 = Some(builder::build_sync_header(
header::Commands::SessionSetup,
1,
8192,
None,
Some(session_id),
2,
));
session_setup_request.1 = Some(
match strategy {
FuzzingStrategy::Predefined => fuzzer::handshake::session_setup_fuzzer::fuzz_session_setup_authenticate_with_predefined_values(challenge_struct),
FuzzingStrategy::RandomFields => fuzzer::handshake::session_setup_fuzzer::fuzz_session_setup_with_random_fields(),
FuzzingStrategy::CompletelyRandom => fuzzer::handshake::session_setup_fuzzer::fuzz_session_setup_completely_random(),
}
);
} else {
session_setup_request =
build_default_session_setup_authenticate_request(session_id, challenge_struct);
}
if let (Some(head), Some(body)) = session_setup_request {
format::encoder::serialize_request(&head, &RequestType::SessionSetupAuth(body))
} else {
panic!("Could not populate session setup 2 packet.")
}
}
/// Builds the tree connect packet according to the fuzzing strategy if given.
/// Otherwise the default tree connect packet is built.
pub fn prepare_tree_connect_packet(
fuzzing_strategy: Option<FuzzingStrategy>,
session_id: Vec<u8>,
) -> Vec<u8> {
let mut tree_connect_request: (Option<header::SyncHeader>, Option<TreeConnect>) = (None, None);
if let Some(strategy) = fuzzing_strategy {
tree_connect_request.0 = Some(builder::build_sync_header(
header::Commands::TreeConnect,
1,
8064,
None,
Some(session_id),
3,
));
tree_connect_request.1 = Some(match strategy {
FuzzingStrategy::Predefined => {
fuzzer::handshake::tree_connect_fuzzer::fuzz_tree_connect_with_predefined_values()
}
FuzzingStrategy::RandomFields => {
fuzzer::handshake::tree_connect_fuzzer::fuzz_tree_connect_with_random_fields()
}
FuzzingStrategy::CompletelyRandom => {
fuzzer::handshake::tree_connect_fuzzer::fuzz_tree_connect_completely_random()
}
});
} else {
tree_connect_request =
builder::tree_connect_request::build_default_tree_connect_request(session_id);
}
if let (Some(head), Some(body)) = tree_connect_request {
format::encoder::serialize_request(&head, &RequestType::TreeConnect(body))
} else {
panic!("Could not populate tree connect packet.")
}
}
/// Builds the create packet according to the fuzzing strategy if given.
/// Otherwise the default create packet is built.
pub fn prepare_create_packet(
fuzzing_strategy: Option<FuzzingStrategy>,
session_id: Vec<u8>,
tree_id: Vec<u8>,
) -> Vec<u8> {
let mut create_request: (Option<header::SyncHeader>, Option<Create>) = (None, None);
if let Some(strategy) = fuzzing_strategy {
create_request.0 = Some(builder::build_sync_header(
header::Commands::Create,
1,
7968,
Some(tree_id),
Some(session_id),
4,
));
create_request.1 = Some(match strategy {
FuzzingStrategy::Predefined => {
fuzzer::create_fuzzer::fuzz_create_with_predefined_values()
}
FuzzingStrategy::RandomFields => {
fuzzer::create_fuzzer::fuzz_create_with_random_fields()
}
FuzzingStrategy::CompletelyRandom => {
fuzzer::create_fuzzer::fuzz_create_completely_random()
}
});
} else {
create_request = builder::create_request::build_default_create_request(tree_id, session_id);
}
if let (Some(head), Some(body)) = create_request {
format::encoder::serialize_request(&head, &RequestType::Create(body))
} else {
panic!("Could not populate create packet.")
}
}
/// Builds the query info packet according to the fuzzing strategy if given.
/// Otherwise the default query info packet is built.
pub fn prepare_query_info_packet(
fuzzing_strategy: Option<FuzzingStrategy>,
session_id: Vec<u8>,
tree_id: Vec<u8>,
file_id: Vec<u8>,
) -> Vec<u8> {
let mut query_info_request: (Option<header::SyncHeader>, Option<QueryInfo>) = (None, None);
if let Some(strategy) = fuzzing_strategy {
query_info_request.0 = Some(builder::build_sync_header(
header::Commands::QueryInfo,
1,
7936,
Some(tree_id),
Some(session_id),
5,
));
query_info_request.1 = Some(match strategy {
FuzzingStrategy::Predefined => {
fuzzer::query_info_fuzzer::fuzz_query_info_with_predefined_values(file_id)
}
FuzzingStrategy::RandomFields => {
fuzzer::query_info_fuzzer::fuzz_query_info_with_random_fields()
}
FuzzingStrategy::CompletelyRandom => {
fuzzer::query_info_fuzzer::fuzz_query_info_completely_random()
}
});
} else {
query_info_request = builder::query_info_request::build_default_query_info_request(
tree_id, session_id, file_id,
);
}
if let (Some(head), Some(body)) = query_info_request {
format::encoder::serialize_request(&head, &RequestType::QueryInfo(body))
} else {
panic!("Could not populate query info packet.")
}
}
/// Builds the echo packet according to the fuzzing strategy if given.
/// Otherwise the default echo packet is built.
pub fn prepare_echo_packet(fuzzing_strategy: Option<FuzzingStrategy>) -> Vec<u8> {
let mut echo_request: (Option<header::SyncHeader>, Option<Echo>) = (None, None);
if let Some(strategy) = fuzzing_strategy {
echo_request.0 = Some(builder::build_sync_header(
header::Commands::Echo,
1,
7968,
None,
None,
6,
));
echo_request.1 = Some(match strategy {
FuzzingStrategy::Predefined => fuzzer::fuzz_echo_with_predefined_values(),
FuzzingStrategy::RandomFields => fuzzer::fuzz_echo_with_random_fields(),
FuzzingStrategy::CompletelyRandom => fuzzer::fuzz_echo_completely_random(),
});
} else {
echo_request = builder::build_default_echo_request();
}
if let (Some(head), Some(body)) = echo_request {
format::encoder::serialize_request(&head, &RequestType::Echo(body))
} else {
panic!("Could not populate echo request.")
}
}
/// Builds the close packet according to the fuzzing strategy if given.
/// Otherwise the default close packet is built.
pub fn prepare_close_packet(
fuzzing_strategy: Option<FuzzingStrategy>,
session_id: Vec<u8>,
tree_id: Vec<u8>,
file_id: Vec<u8>,
) -> Vec<u8> {
let mut close_request: (Option<header::SyncHeader>, Option<Close>) = (None, None);
if let Some(strategy) = fuzzing_strategy {
close_request.0 = Some(builder::build_sync_header(
header::Commands::Close,
1,
7872,
Some(tree_id),
Some(session_id),
7,
));
close_request.1 = Some(match strategy {
FuzzingStrategy::Predefined => {
fuzzer::close_fuzzer::fuzz_close_with_predefined_values()
}
FuzzingStrategy::RandomFields => fuzzer::close_fuzzer::fuzz_close_with_random_fields(),
FuzzingStrategy::CompletelyRandom => {
fuzzer::close_fuzzer::fuzz_close_completely_random()
}
});
} else {
close_request = builder::build_close_request(tree_id, session_id, file_id);
}
if let (Some(head), Some(body)) = close_request {
format::encoder::serialize_request(&head, &RequestType::Close(body))
} else {
panic!("Could not populate close request.")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_prepare_negotiate_packet() {
let (expected_default_header, expected_default_body) =
builder::negotiate_request::build_default_negotiate_request();
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::Negotiate(expected_default_body.unwrap()),
);
assert_eq!(expected_default_request, prepare_negotiate_packet(None));
}
#[test]
fn test_prepare_session_setup_negotiate_packet() {
let (expected_default_header, expected_default_body) =
builder::session_setup_negotiate_request::build_default_session_setup_negotiate_request(
);
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::SessionSetupNeg(expected_default_body.unwrap()),
);
assert_eq!(
expected_default_request,
prepare_session_setup_negotiate_packet(None)
);
}
#[test]
fn test_prepare_session_setup_authenticate_packet() {
let security_buffer = b"\xa1\x81\xce\x30\x81\xcb\xa0\x03\x0a\x01\x01\xa1\x0c\x06\x0a\x2b\
\x06\x01\x04\x01\x82\x37\x02\x02\x0a\xa2\x81\xb5\x04\x81\xb2\x4e\
\x54\x4c\x4d\x53\x53\x50\x00\x02\x00\x00\x00\x16\x00\x16\x00\x38\
\x00\x00\x00\x15\x82\x8a\x62\x8d\x51\x0b\x30\x2d\x45\x71\xe0\x00\
\x00\x00\x00\x00\x00\x00\x00\x64\x00\x64\x00\x4e\x00\x00\x00\x06\
\x01\x00\x00\x00\x00\x00\x0f\x52\x00\x41\x00\x53\x00\x50\x00\x42\
\x00\x45\x00\x52\x00\x52\x00\x59\x00\x50\x00\x49\x00\x02\x00\x16\
\x00\x52\x00\x41\x00\x53\x00\x50\x00\x42\x00\x45\x00\x52\x00\x52\
\x00\x59\x00\x50\x00\x49\x00\x01\x00\x16\x00\x52\x00\x41\x00\x53\
\x00\x50\x00\x42\x00\x45\x00\x52\x00\x52\x00\x59\x00\x50\x00\x49\
\x00\x04\x00\x02\x00\x00\x00\x03\x00\x16\x00\x72\x00\x61\x00\x73\
\x00\x70\x00\x62\x00\x65\x00\x72\x00\x72\x00\x79\x00\x70\x00\x69\
\x00\x07\x00\x08\x00\x60\x16\xad\x6d\x47\x21\xd7\x01\x00\x00\x00\
\x00".to_vec();
let mut session_setup_response = responses::session_setup::SessionSetup::default();
session_setup_response.buffer = security_buffer;
let challenge_struct =
match format::decoder::security_blob_decoder::decode_security_response(
session_setup_response.buffer.clone(),
)
.message
.unwrap()
{
MessageType::Challenge(challenge) => challenge,
_ => panic!("Invalid message type in server response."),
};
let (expected_default_header, expected_default_body) =
builder::session_setup_authenticate_request::build_default_session_setup_authenticate_request(
vec![0, 1, 2, 3, 4, 5, 6, 7],
challenge_struct,
);
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::SessionSetupAuth(expected_default_body.unwrap()),
);
assert_eq!(
expected_default_request,
prepare_session_setup_authenticate_packet(
None,
vec![0, 1, 2, 3, 4, 5, 6, 7],
session_setup_response
)
);
}
#[test]
fn test_prepare_tree_connect_packet() {
let (expected_default_header, expected_default_body) =
builder::tree_connect_request::build_default_tree_connect_request(vec![
0, 1, 2, 3, 4, 5, 6, 7,
]);
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::TreeConnect(expected_default_body.unwrap()),
);
assert_eq!(
expected_default_request,
prepare_tree_connect_packet(None, vec![0, 1, 2, 3, 4, 5, 6, 7])
);
}
#[test]
fn test_prepare_create_packet() {
let (expected_default_header, expected_default_body) =
builder::create_request::build_default_create_request(
vec![0, 1, 2, 3],
vec![0, 1, 2, 3, 4, 5, 6, 7],
);
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::Create(expected_default_body.unwrap()),
);
assert_eq!(
expected_default_request,
prepare_create_packet(None, vec![0, 1, 2, 3, 4, 5, 6, 7], vec![0, 1, 2, 3])
);
}
#[test]
fn test_prepare_query_info_packet() {
let (expected_default_header, expected_default_body) =
builder::query_info_request::build_default_query_info_request(
vec![0, 1, 2, 3],
vec![0, 1, 2, 3, 4, 5, 6, 7],
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
);
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::QueryInfo(expected_default_body.unwrap()),
);
assert_eq!(
expected_default_request,
prepare_query_info_packet(
None,
vec![0, 1, 2, 3, 4, 5, 6, 7],
vec![0, 1, 2, 3],
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
)
);
}
#[test]
fn test_prepare_echo_packet() {
let (expected_default_header, expected_default_body) =
builder::build_default_echo_request();
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::Echo(expected_default_body.unwrap()),
);
assert_eq!(expected_default_request, prepare_echo_packet(None));
}
#[test]
fn test_prepare_close_packet() {
let (expected_default_header, expected_default_body) = builder::build_close_request(
vec![0, 1, 2, 3],
vec![0, 1, 2, 3, 4, 5, 6, 7],
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
);
let expected_default_request = format::encoder::serialize_request(
&expected_default_header.unwrap(),
&RequestType::Close(expected_default_body.unwrap()),
);
assert_eq!(
expected_default_request,
prepare_close_packet(
None,
vec![0, 1, 2, 3, 4, 5, 6, 7],
vec![0, 1, 2, 3],
vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
)
);
}
}
|
//! Helpers concerning [`object_store`](::object_store) interaction.
pub mod ignore_writes;
pub mod metrics;
|
mod stop_signs;
mod traffic_signals;
use crate::common::CommonState;
use crate::debug::DebugMode;
use crate::game::{State, Transition, WizardState};
use crate::helpers::{ColorScheme, ID};
use crate::render::{
DrawCtx, DrawIntersection, DrawLane, DrawMap, DrawOptions, DrawTurn, Renderable,
MIN_ZOOM_FOR_DETAIL,
};
use crate::sandbox::SandboxMode;
use crate::ui::{PerMapUI, ShowEverything, UI};
use abstutil::Timer;
use ezgui::{hotkey, lctrl, Choice, Color, EventCtx, GfxCtx, Key, Line, ModalMenu, Text, Wizard};
use map_model::{
IntersectionID, Lane, LaneID, LaneType, Map, MapEdits, Road, RoadID, TurnID, TurnType,
};
use std::collections::{BTreeSet, HashMap};
pub struct EditMode {
common: CommonState,
menu: ModalMenu,
}
impl EditMode {
pub fn new(ctx: &EventCtx, ui: &mut UI) -> EditMode {
// TODO Warn first?
ui.primary.reset_sim();
EditMode {
common: CommonState::new(),
menu: ModalMenu::new(
"Map Edit Mode",
vec![
vec![
(hotkey(Key::S), "save edits"),
(hotkey(Key::L), "load different edits"),
],
vec![
(hotkey(Key::Escape), "quit"),
(lctrl(Key::S), "sandbox mode"),
(lctrl(Key::D), "debug mode"),
(hotkey(Key::J), "warp"),
(hotkey(Key::K), "navigate"),
(hotkey(Key::SingleQuote), "shortcuts"),
(hotkey(Key::F1), "take a screenshot"),
],
],
ctx,
),
}
}
}
impl State for EditMode {
fn event(&mut self, ctx: &mut EventCtx, ui: &mut UI) -> Transition {
// The .clone() is probably not that expensive, and it makes later code a bit
// easier to read. :)
let orig_edits = ui.primary.map.get_edits().clone();
let mut txt = Text::prompt("Map Edit Mode");
{
txt.add(Line(&orig_edits.edits_name));
txt.add(Line(format!("{} lanes", orig_edits.lane_overrides.len())));
txt.add(Line(format!(
"{} stop signs ",
orig_edits.stop_sign_overrides.len()
)));
txt.add(Line(format!(
"{} traffic signals",
orig_edits.traffic_signal_overrides.len()
)));
txt.add(Line("Right-click a lane or intersection to start editing"));
}
self.menu.handle_event(ctx, Some(txt));
ctx.canvas.handle_event(ctx.input);
// TODO Reset when transitioning in/out of this state? Or maybe we just don't draw
// the effects of it. Or eventually, the Option<ID> itself will live in here
// directly.
// TODO Only mouseover lanes and intersections?
if ctx.redo_mouseover() {
ui.recalculate_current_selection(ctx);
}
if let Some(t) = self.common.event(ctx, ui, &mut self.menu) {
return t;
}
if self.menu.action("quit") {
return Transition::Pop;
}
if self.menu.action("sandbox mode") {
return Transition::Replace(Box::new(SandboxMode::new(ctx)));
}
if self.menu.action("debug mode") {
return Transition::Push(Box::new(DebugMode::new(ctx, ui)));
}
// TODO Only if current edits are unsaved
if self.menu.action("save edits") {
return Transition::Push(WizardState::new(Box::new(save_edits)));
} else if self.menu.action("load different edits") {
return Transition::Push(WizardState::new(Box::new(load_edits)));
}
if let Some(ID::Lane(id)) = ui.primary.current_selection {
// TODO Urgh, borrow checker.
{
let lane = ui.primary.map.get_l(id);
let road = ui.primary.map.get_r(lane.parent);
if lane.lane_type != LaneType::Sidewalk {
if let Some(new_type) = next_valid_type(road, lane, &ui.primary.map) {
if ctx
.input
.contextual_action(Key::Space, format!("toggle to {:?}", new_type))
{
let mut new_edits = orig_edits.clone();
new_edits.lane_overrides.insert(lane.id, new_type);
apply_map_edits(&mut ui.primary, &ui.cs, ctx, new_edits);
}
}
}
}
{
let lane = ui.primary.map.get_l(id);
let road = ui.primary.map.get_r(lane.parent);
if lane.lane_type != LaneType::Sidewalk {
for (lt, name, key) in &[
(LaneType::Driving, "driving", Key::D),
(LaneType::Parking, "parking", Key::P),
(LaneType::Biking, "biking", Key::B),
(LaneType::Bus, "bus", Key::T),
] {
if can_change_lane_type(road, lane, *lt, &ui.primary.map)
&& ctx
.input
.contextual_action(*key, format!("change to {} lane", name))
{
let mut new_edits = orig_edits.clone();
new_edits.lane_overrides.insert(lane.id, *lt);
apply_map_edits(&mut ui.primary, &ui.cs, ctx, new_edits);
break;
}
}
}
}
if ctx
.input
.contextual_action(Key::U, "bulk edit lanes on this road")
{
return Transition::Push(make_bulk_edit_lanes(ui.primary.map.get_l(id).parent));
} else if orig_edits.lane_overrides.contains_key(&id)
&& ctx.input.contextual_action(Key::R, "revert")
{
let mut new_edits = orig_edits.clone();
new_edits.lane_overrides.remove(&id);
apply_map_edits(&mut ui.primary, &ui.cs, ctx, new_edits);
}
}
if let Some(ID::Intersection(id)) = ui.primary.current_selection {
if ui.primary.map.maybe_get_stop_sign(id).is_some() {
if ctx
.input
.contextual_action(Key::E, format!("edit stop signs for {}", id))
{
return Transition::Push(Box::new(stop_signs::StopSignEditor::new(
id, ctx, ui,
)));
} else if orig_edits.stop_sign_overrides.contains_key(&id)
&& ctx.input.contextual_action(Key::R, "revert")
{
let mut new_edits = orig_edits.clone();
new_edits.stop_sign_overrides.remove(&id);
apply_map_edits(&mut ui.primary, &ui.cs, ctx, new_edits);
}
}
if ui.primary.map.maybe_get_traffic_signal(id).is_some() {
if ctx
.input
.contextual_action(Key::E, format!("edit traffic signal for {}", id))
{
return Transition::Push(Box::new(traffic_signals::TrafficSignalEditor::new(
id, ctx, ui,
)));
} else if orig_edits.traffic_signal_overrides.contains_key(&id)
&& ctx.input.contextual_action(Key::R, "revert")
{
let mut new_edits = orig_edits.clone();
new_edits.traffic_signal_overrides.remove(&id);
apply_map_edits(&mut ui.primary, &ui.cs, ctx, new_edits);
}
}
}
Transition::Keep
}
fn draw_default_ui(&self) -> bool {
false
}
fn draw(&self, g: &mut GfxCtx, ui: &UI) {
ui.draw(
g,
self.common.draw_options(ui),
&ui.primary.sim,
&ShowEverything::new(),
);
// More generally we might want to show the diff between two edits, but for now,
// just show diff relative to basemap.
let edits = ui.primary.map.get_edits();
let ctx = DrawCtx {
cs: &ui.cs,
map: &ui.primary.map,
draw_map: &ui.primary.draw_map,
sim: &ui.primary.sim,
};
let mut opts = DrawOptions::new();
// TODO Similar to drawing areas with traffic or not -- would be convenient to just
// supply a set of things to highlight and have something else take care of drawing
// with detail or not.
if g.canvas.cam_zoom >= MIN_ZOOM_FOR_DETAIL {
for l in edits.lane_overrides.keys() {
opts.override_colors.insert(ID::Lane(*l), Color::Hatching);
ctx.draw_map.get_l(*l).draw(g, &opts, &ctx);
}
for i in edits
.stop_sign_overrides
.keys()
.chain(edits.traffic_signal_overrides.keys())
{
opts.override_colors
.insert(ID::Intersection(*i), Color::Hatching);
ctx.draw_map.get_i(*i).draw(g, &opts, &ctx);
}
// The hatching covers up the selection outline, so redraw it.
match ui.primary.current_selection {
Some(ID::Lane(l)) => {
g.draw_polygon(
ui.cs.get("selected"),
&ctx.draw_map.get_l(l).get_outline(&ctx.map),
);
}
Some(ID::Intersection(i)) => {
g.draw_polygon(
ui.cs.get("selected"),
&ctx.draw_map.get_i(i).get_outline(&ctx.map),
);
}
_ => {}
}
} else {
let color = ui.cs.get_def("unzoomed map diffs", Color::RED);
for l in edits.lane_overrides.keys() {
g.draw_polygon(color, &ctx.map.get_parent(*l).get_thick_polygon().unwrap());
}
for i in edits
.stop_sign_overrides
.keys()
.chain(edits.traffic_signal_overrides.keys())
{
opts.override_colors.insert(ID::Intersection(*i), color);
ctx.draw_map.get_i(*i).draw(g, &opts, &ctx);
}
}
self.common.draw(g, ui);
self.menu.draw(g);
}
fn on_destroy(&mut self, _: &mut EventCtx, ui: &mut UI) {
// TODO Warn about unsaved edits
// TODO Maybe put a loading screen around these.
ui.primary
.map
.recalculate_pathfinding_after_edits(&mut Timer::new("apply pending map edits"));
// Parking state might've changed
ui.primary.reset_sim();
}
}
fn save_edits(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {
let map = &mut ui.primary.map;
let mut wizard = wiz.wrap(ctx);
let rename = if map.get_edits().edits_name == "no_edits" {
Some(wizard.input_string("Name these map edits")?)
} else {
None
};
// TODO Do it this weird way to avoid saving edits on every event. :P
let save = "save edits";
let cancel = "cancel";
if wizard
.choose_string("Overwrite edits?", || vec![save, cancel])?
.as_str()
== save
{
if let Some(name) = rename {
let mut edits = map.get_edits().clone();
edits.edits_name = name;
map.apply_edits(edits, &mut Timer::new("name map edits"));
}
map.get_edits().save();
}
Some(Transition::Pop)
}
fn load_edits(wiz: &mut Wizard, ctx: &mut EventCtx, ui: &mut UI) -> Option<Transition> {
let map = &mut ui.primary.map;
let mut wizard = wiz.wrap(ctx);
// TODO Exclude current
let map_name = map.get_name().to_string();
let (_, new_edits) = wizard.choose("Load which map edits?", || {
let mut list = Choice::from(abstutil::load_all_objects("edits", &map_name));
list.push(Choice::new("no_edits", MapEdits::new(map_name.clone())));
list
})?;
apply_map_edits(&mut ui.primary, &ui.cs, ctx, new_edits);
Some(Transition::Pop)
}
// For lane editing
fn next_valid_type(r: &Road, l: &Lane, map: &Map) -> Option<LaneType> {
let mut new_type = next_type(l.lane_type);
while new_type != l.lane_type {
if can_change_lane_type(r, l, new_type, map) {
return Some(new_type);
}
new_type = next_type(new_type);
}
None
}
fn next_type(lt: LaneType) -> LaneType {
match lt {
LaneType::Driving => LaneType::Parking,
LaneType::Parking => LaneType::Biking,
LaneType::Biking => LaneType::Bus,
LaneType::Bus => LaneType::Driving,
LaneType::Sidewalk => unreachable!(),
}
}
fn can_change_lane_type(r: &Road, l: &Lane, new_lt: LaneType, map: &Map) -> bool {
let (fwds, idx) = r.dir_and_offset(l.id);
let mut proposed_lts = if fwds {
r.get_lane_types().0
} else {
r.get_lane_types().1
};
proposed_lts[idx] = new_lt;
// No-op change
if l.lane_type == new_lt {
return false;
}
// Only one parking lane per side.
if proposed_lts
.iter()
.filter(|lt| **lt == LaneType::Parking)
.count()
> 1
{
return false;
}
// Two adjacent bike lanes is unnecessary.
for pair in proposed_lts.windows(2) {
if pair[0] == LaneType::Biking && pair[1] == LaneType::Biking {
return false;
}
}
// Don't let players orphan a bus stop.
if !r.all_bus_stops(map).is_empty()
&& (new_lt == LaneType::Parking || new_lt == LaneType::Biking)
{
// Is this the last one?
let mut other_bus_lane = false;
for id in r.all_lanes() {
if l.id != id {
let other_lt = map.get_l(id).lane_type;
if other_lt == LaneType::Driving || other_lt == LaneType::Bus {
other_bus_lane = true;
break;
}
}
}
if !other_bus_lane {
return false;
}
}
// A parking lane must have a driving lane on the same side of the road.
if proposed_lts.contains(&LaneType::Parking) && !proposed_lts.contains(&LaneType::Driving) {
return false;
}
true
}
pub fn apply_map_edits(
bundle: &mut PerMapUI,
cs: &ColorScheme,
ctx: &mut EventCtx,
edits: MapEdits,
) {
let mut timer = Timer::new("apply map edits");
let (lanes_changed, turns_deleted, turns_added) = bundle.map.apply_edits(edits, &mut timer);
for l in lanes_changed {
bundle.draw_map.lanes[l.0] = DrawLane::new(
bundle.map.get_l(l),
&bundle.map,
bundle.current_flags.draw_lane_markings,
cs,
&mut timer,
)
.finish(ctx.prerender);
}
let mut modified_intersections: BTreeSet<IntersectionID> = BTreeSet::new();
let mut lanes_of_modified_turns: BTreeSet<LaneID> = BTreeSet::new();
for t in turns_deleted {
bundle.draw_map.turns.remove(&t);
lanes_of_modified_turns.insert(t.src);
modified_intersections.insert(t.parent);
}
for t in &turns_added {
lanes_of_modified_turns.insert(t.src);
modified_intersections.insert(t.parent);
}
let mut turn_to_lane_offset: HashMap<TurnID, usize> = HashMap::new();
for l in lanes_of_modified_turns {
DrawMap::compute_turn_to_lane_offset(
&mut turn_to_lane_offset,
bundle.map.get_l(l),
&bundle.map,
);
}
for t in turns_added {
let turn = bundle.map.get_t(t);
if turn.turn_type != TurnType::SharedSidewalkCorner {
bundle
.draw_map
.turns
.insert(t, DrawTurn::new(&bundle.map, turn, turn_to_lane_offset[&t]));
}
}
for i in modified_intersections {
bundle.draw_map.intersections[i.0] = DrawIntersection::new(
bundle.map.get_i(i),
&bundle.map,
cs,
ctx.prerender,
&mut timer,
);
}
// Do this after fixing up all the state above.
bundle.map.simplify_edits(&mut timer);
}
fn make_bulk_edit_lanes(road: RoadID) -> Box<dyn State> {
WizardState::new(Box::new(move |wiz, ctx, ui| {
let mut wizard = wiz.wrap(ctx);
let (_, from) = wizard.choose("Change all lanes of type...", || {
vec![
Choice::new("driving", LaneType::Driving),
Choice::new("parking", LaneType::Parking),
Choice::new("biking", LaneType::Biking),
Choice::new("bus", LaneType::Bus),
]
})?;
let (_, to) = wizard.choose("Change to all lanes of type...", || {
vec![
Choice::new("driving", LaneType::Driving),
Choice::new("parking", LaneType::Parking),
Choice::new("biking", LaneType::Biking),
Choice::new("bus", LaneType::Bus),
]
.into_iter()
.filter(|c| c.data != from)
.collect()
})?;
// Do the dirty deed. Match by road name; OSM way ID changes a fair bit.
let map = &ui.primary.map;
let road_name = map.get_r(road).get_name();
let mut edits = map.get_edits().clone();
let mut cnt = 0;
for l in map.all_lanes() {
if l.lane_type != from {
continue;
}
let parent = map.get_parent(l.id);
if parent.get_name() != road_name {
continue;
}
// TODO This looks at the original state of the map, not with all the edits applied so far!
if can_change_lane_type(parent, l, to, map) {
edits.lane_overrides.insert(l.id, to);
cnt += 1;
}
}
// TODO pop this up. warn about road names changing and being weird. :)
println!(
"Changed {} {:?} lanes to {:?} lanes on {}",
cnt, from, to, road_name
);
apply_map_edits(&mut ui.primary, &ui.cs, ctx, edits);
Some(Transition::Pop)
}))
}
|
use std::io;
use std::io::Read;
use regex::Regex;
fn matches_rule(val: u16, rule: (u16, u16, u16, u16)) -> bool {
(rule.0 <= val && val <= rule.1) || (rule.2 <= val && val <= rule.3)
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let re_rule = Regex::new(r"(?m)^[a-z ]+: (\d+)-(\d+) or (\d+)-(\d+)$").unwrap();
let re_nearby_tickets = Regex::new(r"(?m)^nearby tickets:\n((?:\d+[,\n])*\d+)$").unwrap();
let rules: Vec<(u16, u16, u16, u16)> = re_rule.captures_iter(&input).map(|rule| {
(rule[1].parse().unwrap(), rule[2].parse().unwrap(), rule[3].parse().unwrap(), rule[4].parse().unwrap())
}).collect();
println!("{}", re_nearby_tickets.captures(&input).unwrap()[1].lines().filter_map(|x| {
x.split(',').map(|y| y.parse().unwrap()).find(|&y| {
!rules.iter().any(|&z| matches_rule(y, z))
}).map(|x| x as u32)
}).sum::<u32>());
}
|
use std::{error, fmt};
/// Error's that originate from the client or server;
#[derive(Debug)]
pub struct Error(crate::Error);
impl Error {
pub(crate) fn from_source(source: impl Into<crate::Error>) -> Self {
Self(source.into())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
self.0.source()
}
}
|
//! linux_raw syscalls supporting `rustix::event`.
//!
//! # Safety
//!
//! See the `rustix::backend` module documentation for details.
#![allow(unsafe_code)]
#![allow(clippy::undocumented_unsafe_blocks)]
use crate::backend::c;
use crate::backend::conv::{
by_ref, c_int, c_uint, pass_usize, raw_fd, ret, ret_owned_fd, ret_usize, slice_mut, zero,
};
use crate::event::{epoll, EventfdFlags, PollFd};
use crate::fd::{BorrowedFd, OwnedFd};
use crate::io;
use linux_raw_sys::general::{EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD};
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
use {
crate::backend::conv::{opt_ref, size_of},
linux_raw_sys::general::{__kernel_timespec, kernel_sigset_t},
};
#[inline]
pub(crate) fn poll(fds: &mut [PollFd<'_>], timeout: c::c_int) -> io::Result<usize> {
let (fds_addr_mut, fds_len) = slice_mut(fds);
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
unsafe {
let timeout = if timeout >= 0 {
Some(__kernel_timespec {
tv_sec: (timeout as i64) / 1000,
tv_nsec: (timeout as i64) % 1000 * 1_000_000,
})
} else {
None
};
ret_usize(syscall!(
__NR_ppoll,
fds_addr_mut,
fds_len,
opt_ref(timeout.as_ref()),
zero(),
size_of::<kernel_sigset_t, _>()
))
}
#[cfg(not(any(target_arch = "aarch64", target_arch = "riscv64")))]
unsafe {
ret_usize(syscall!(__NR_poll, fds_addr_mut, fds_len, c_int(timeout)))
}
}
#[inline]
pub(crate) fn epoll_create(flags: epoll::CreateFlags) -> io::Result<OwnedFd> {
unsafe { ret_owned_fd(syscall_readonly!(__NR_epoll_create1, flags)) }
}
#[inline]
pub(crate) unsafe fn epoll_add(
epfd: BorrowedFd<'_>,
fd: c::c_int,
event: &epoll::Event,
) -> io::Result<()> {
ret(syscall_readonly!(
__NR_epoll_ctl,
epfd,
c_uint(EPOLL_CTL_ADD),
raw_fd(fd),
by_ref(event)
))
}
#[inline]
pub(crate) unsafe fn epoll_mod(
epfd: BorrowedFd<'_>,
fd: c::c_int,
event: &epoll::Event,
) -> io::Result<()> {
ret(syscall_readonly!(
__NR_epoll_ctl,
epfd,
c_uint(EPOLL_CTL_MOD),
raw_fd(fd),
by_ref(event)
))
}
#[inline]
pub(crate) unsafe fn epoll_del(epfd: BorrowedFd<'_>, fd: c::c_int) -> io::Result<()> {
ret(syscall_readonly!(
__NR_epoll_ctl,
epfd,
c_uint(EPOLL_CTL_DEL),
raw_fd(fd),
zero()
))
}
#[inline]
pub(crate) fn epoll_wait(
epfd: BorrowedFd<'_>,
events: *mut epoll::Event,
num_events: usize,
timeout: c::c_int,
) -> io::Result<usize> {
#[cfg(not(any(target_arch = "aarch64", target_arch = "riscv64")))]
unsafe {
ret_usize(syscall!(
__NR_epoll_wait,
epfd,
events,
pass_usize(num_events),
c_int(timeout)
))
}
#[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
unsafe {
ret_usize(syscall!(
__NR_epoll_pwait,
epfd,
events,
pass_usize(num_events),
c_int(timeout),
zero()
))
}
}
#[inline]
pub(crate) fn eventfd(initval: u32, flags: EventfdFlags) -> io::Result<OwnedFd> {
unsafe { ret_owned_fd(syscall_readonly!(__NR_eventfd2, c_uint(initval), flags)) }
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::_3_FLTSRC1 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP0R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP0W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP0W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP1R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP1W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP2R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP2W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP2W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP3R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP3W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP4R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP4R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP4W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP4W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 4);
self.w.bits |= ((value as u32) & 1) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP5R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP5R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP5W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP5W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP6R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP6R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP6W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP6W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_3_FLTSRC1_DCMP7R {
bits: bool,
}
impl PWM_3_FLTSRC1_DCMP7R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _PWM_3_FLTSRC1_DCMP7W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_3_FLTSRC1_DCMP7W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Digital Comparator 0"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp0(&self) -> PWM_3_FLTSRC1_DCMP0R {
let bits = ((self.bits >> 0) & 1) != 0;
PWM_3_FLTSRC1_DCMP0R { bits }
}
#[doc = "Bit 1 - Digital Comparator 1"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp1(&self) -> PWM_3_FLTSRC1_DCMP1R {
let bits = ((self.bits >> 1) & 1) != 0;
PWM_3_FLTSRC1_DCMP1R { bits }
}
#[doc = "Bit 2 - Digital Comparator 2"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp2(&self) -> PWM_3_FLTSRC1_DCMP2R {
let bits = ((self.bits >> 2) & 1) != 0;
PWM_3_FLTSRC1_DCMP2R { bits }
}
#[doc = "Bit 3 - Digital Comparator 3"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp3(&self) -> PWM_3_FLTSRC1_DCMP3R {
let bits = ((self.bits >> 3) & 1) != 0;
PWM_3_FLTSRC1_DCMP3R { bits }
}
#[doc = "Bit 4 - Digital Comparator 4"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp4(&self) -> PWM_3_FLTSRC1_DCMP4R {
let bits = ((self.bits >> 4) & 1) != 0;
PWM_3_FLTSRC1_DCMP4R { bits }
}
#[doc = "Bit 5 - Digital Comparator 5"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp5(&self) -> PWM_3_FLTSRC1_DCMP5R {
let bits = ((self.bits >> 5) & 1) != 0;
PWM_3_FLTSRC1_DCMP5R { bits }
}
#[doc = "Bit 6 - Digital Comparator 6"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp6(&self) -> PWM_3_FLTSRC1_DCMP6R {
let bits = ((self.bits >> 6) & 1) != 0;
PWM_3_FLTSRC1_DCMP6R { bits }
}
#[doc = "Bit 7 - Digital Comparator 7"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp7(&self) -> PWM_3_FLTSRC1_DCMP7R {
let bits = ((self.bits >> 7) & 1) != 0;
PWM_3_FLTSRC1_DCMP7R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Digital Comparator 0"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp0(&mut self) -> _PWM_3_FLTSRC1_DCMP0W {
_PWM_3_FLTSRC1_DCMP0W { w: self }
}
#[doc = "Bit 1 - Digital Comparator 1"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp1(&mut self) -> _PWM_3_FLTSRC1_DCMP1W {
_PWM_3_FLTSRC1_DCMP1W { w: self }
}
#[doc = "Bit 2 - Digital Comparator 2"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp2(&mut self) -> _PWM_3_FLTSRC1_DCMP2W {
_PWM_3_FLTSRC1_DCMP2W { w: self }
}
#[doc = "Bit 3 - Digital Comparator 3"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp3(&mut self) -> _PWM_3_FLTSRC1_DCMP3W {
_PWM_3_FLTSRC1_DCMP3W { w: self }
}
#[doc = "Bit 4 - Digital Comparator 4"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp4(&mut self) -> _PWM_3_FLTSRC1_DCMP4W {
_PWM_3_FLTSRC1_DCMP4W { w: self }
}
#[doc = "Bit 5 - Digital Comparator 5"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp5(&mut self) -> _PWM_3_FLTSRC1_DCMP5W {
_PWM_3_FLTSRC1_DCMP5W { w: self }
}
#[doc = "Bit 6 - Digital Comparator 6"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp6(&mut self) -> _PWM_3_FLTSRC1_DCMP6W {
_PWM_3_FLTSRC1_DCMP6W { w: self }
}
#[doc = "Bit 7 - Digital Comparator 7"]
#[inline(always)]
pub fn pwm_3_fltsrc1_dcmp7(&mut self) -> _PWM_3_FLTSRC1_DCMP7W {
_PWM_3_FLTSRC1_DCMP7W { w: self }
}
}
|
//! A BeachMap is just a SlotMap, a data structure used to store elements and access them with an id.
//! # Example:
//! ```
//! use beach_map::BeachMap;
//!
//! let mut beach = BeachMap::default();
//! let id1 = beach.insert(1);
//! let id2 = beach.insert(2);
//!
//! assert_eq!(beach.len(), 2);
//! assert_eq!(beach[id1], 1);
//!
//! assert_eq!(beach.remove(id2), Some(2));
//! assert_eq!(beach.get(id2), None);
//! assert_eq!(beach.len(), 1);
//!
//! beach[id1] = 7;
//! assert_eq!(beach[id1], 7);
//!
//! beach.extend(1..4);
//!
//! assert_eq!(beach.data(), [7, 1, 2, 3]);
//! ```
//! You shouldn't assume the order of the elements as any removing operation will shuffle them.
//!
//! # Rayon
//! To use rayon with beach_map, you need rayon in your dependencies and add the parallel feature to beach_map.
//! ## Example:
//! ```
//! use beach_map::BeachMap;
//! # #[cfg(feature = "parallel")]
//! use rayon::prelude::*;
//!
//! let mut beach = BeachMap::default();
//! let ids = beach.extend(0..500);
//!
//! # #[cfg(feature = "parallel")]
//! beach.par_iter_mut().for_each(|x| {
//! *x *= 2;
//! });
//!
//! # #[cfg(feature = "parallel")]
//! for i in 0..ids.len() {
//! assert_eq!(beach[ids[i]], i * 2);
//! }
//! ```
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
extern crate alloc;
mod id;
pub use id::ID;
pub type DefaultVersion = u32;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[derive(Copy, Clone, Debug, PartialEq)]
struct LinkedList {
head: usize,
tail: usize,
}
impl LinkedList {
#[inline]
fn is_last(&self) -> bool {
self.tail == self.head
}
}
// V is the type of the version
// T is the type of the item stored
pub struct BeachMap<T, V = DefaultVersion> {
// ID.index is either a data index or the index of the next available id in ids
ids: Vec<ID<V>>,
// ids index of every elements in data
slots: Vec<usize>,
data: Vec<T>,
// linked list inside ids
// the list use ids[index].index to point to the next node
// head is older than tail
available_ids: Option<LinkedList>,
}
impl<T> Default for BeachMap<T, DefaultVersion> {
fn default() -> Self {
BeachMap {
ids: Vec::new(),
slots: Vec::new(),
data: Vec::new(),
available_ids: None,
}
}
}
impl<T> BeachMap<T, DefaultVersion> {
/// Constructs a new, empty BeachMap with the specified capacity and the default version type (u32).
/// # Exemple:
/// ```
/// # use beach_map::BeachMap;
/// let beach = BeachMap::<i32>::with_capacity(5);
/// assert_eq!(beach.len(), 0);
/// // or if T can be inferred
/// let mut beach = BeachMap::with_capacity(5);
/// beach.insert(10);
/// ```
pub fn with_capacity(capacity: usize) -> BeachMap<T> {
BeachMap {
ids: Vec::with_capacity(capacity),
slots: Vec::with_capacity(capacity),
data: Vec::with_capacity(capacity),
available_ids: None,
}
}
/// Constructs a new, empty BeachMap with a custom version type.
/// # Exemple:
/// ```
/// # use beach_map::BeachMap;
/// let beach = BeachMap::<i32>::with_version::<u8>();
/// // or if T can be inferred
/// let mut beach = BeachMap::with_version::<u8>();
/// beach.insert(5);
/// ```
pub fn with_version<V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>>(
) -> BeachMap<T, V> {
BeachMap {
ids: Vec::new(),
slots: Vec::new(),
data: Vec::new(),
available_ids: None,
}
}
/// Constructs a new, empty BeachMap with the given capacity and a custom version type.
/// # Exemple:
/// ```
/// # use beach_map::BeachMap;
/// let beach = BeachMap::<i32>::with_version_and_capacity::<u8>(5);
/// // or if T can be inferred
/// let mut beach = BeachMap::with_version_and_capacity::<u8>(5);
/// beach.insert(10);
/// ```
pub fn with_version_and_capacity<
V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>,
>(
capacity: usize,
) -> BeachMap<T, V> {
BeachMap {
ids: Vec::with_capacity(capacity),
slots: Vec::with_capacity(capacity),
data: Vec::with_capacity(capacity),
available_ids: None,
}
}
}
impl<V, T> BeachMap<T, V> {
/// Construct a new, empty BeachMap with a custom version type.
/// # Exemple:
/// ```
/// # use beach_map::BeachMap;
/// let beach = BeachMap::<u8, i32>::new();
/// ```
#[allow(clippy::new_ret_no_self)]
#[inline]
pub fn new() -> BeachMap<T, DefaultVersion> {
BeachMap {
ids: Vec::new(),
slots: Vec::new(),
data: Vec::new(),
available_ids: None,
}
}
/// Returns a reference to an element without checking if the versions match.
/// # Safety
/// Should only be used if index is less that ids.len() and the versions match.
#[inline]
pub unsafe fn get_unchecked(&self, id: ID<V>) -> &T {
self.data
.get_unchecked(self.ids.get_unchecked(id.index).index)
}
/// Returns a mutable reference to an element without checking if the versions match.
/// # Safety
/// Should only be used if index is less than ids.len() and the versions match.
#[inline]
pub unsafe fn get_unchecked_mut(&mut self, id: ID<V>) -> &mut T {
self.data
.get_unchecked_mut(self.ids.get_unchecked(id.index).index)
}
/// Returns an iterator visiting all values in the BeachMap.
#[inline]
pub fn iter(&self) -> core::slice::Iter<T> {
self.data.iter()
}
/// Returns an iterator visiting all values in the BeachMap and let you mutate them.
#[inline]
pub fn iter_mut(&mut self) -> core::slice::IterMut<T> {
self.data.iter_mut()
}
/// Returns an iterator visiting all values in the BeachMap and their ID.
pub fn iter_with_id(&self) -> IterID<T, V> {
IterID {
beach: self,
index: 0,
}
}
/// Returns an iterator visiting all values in the BeachMap and their ID, values being mutable.
pub fn iter_mut_with_id(&mut self) -> IterMutID<T, V> {
IterMutID {
index: 0,
ids: &self.ids,
slots: &self.slots,
data: self.data.as_mut_ptr(),
_phantom: core::marker::PhantomData,
}
}
/// Returns the number of elements the BeachMap can hold without reallocating slots or data.
pub fn capacity(&self) -> usize {
self.data.capacity()
}
/// Returns the number of elements in the BeachMap.
#[inline]
pub fn len(&self) -> usize {
self.data.len()
}
/// Returns true is the BeachMap contains no elements.
#[inline]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Reserves capacity for at least `additional` more elements.\
/// The function will reserve space regardless of vacant slots.\
/// Meaning some times slots and data may not allocate new space while ids does.
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.ids.reserve(additional);
self.slots.reserve(additional);
self.data.reserve(additional);
}
/// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the given BeachMap.\
/// The function will reserve space regardless of vacant slots.\
/// Meaning some times slots and data may not allocate new space while ids does.
pub fn reserve_exact(&mut self, additional: usize) {
self.ids.reserve_exact(additional);
self.slots.reserve_exact(additional);
self.data.reserve_exact(additional);
}
/// Shrinks the capacity of the BeachMap as much as possible.
pub fn shrink_to_fit(&mut self) {
self.ids.shrink_to_fit();
self.slots.shrink_to_fit();
self.data.shrink_to_fit();
}
/// Just adds the elements without making ids nor slots for it, use `reserve_ids` to add ids and slots.\
/// See `reserve_ids` to know in which situation it is safe.
#[inline]
pub unsafe fn use_ids(&mut self, elements: &mut Vec<T>) {
self.data.append(elements);
}
/// Returns a slice of the underlying data vector.
#[inline]
pub fn data(&self) -> &[T] {
&self.data
}
/// Returns a mutable slice of the underlying data vector.
#[inline]
pub fn data_mut(&mut self) -> &mut [T] {
&mut self.data
}
}
impl<T, V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>> BeachMap<T, V> {
/// Returns the next id, from the linked list if it isn't empty or a brand new one
fn next_id(&mut self) -> ID<V> {
match &mut self.available_ids {
Some(available_ids) => {
let head = available_ids.head;
if available_ids.is_last() {
self.available_ids = None
} else {
// assign the first available id to the next one
// SAFE available_ids are always valid ids indices
available_ids.head = unsafe { self.ids.get_unchecked(head).index };
}
// reassign id.index to the future index of the data
// SAFE first_available_id is always a valid index
unsafe {
self.ids.get_unchecked_mut(head).index = self.data.len();
}
ID {
index: head,
version: unsafe { self.ids.get_unchecked_mut(head).version },
}
}
None => {
// if there is no available id, push a new one at the end of ids
self.ids.push(ID {
index: self.data.len(),
version: V::default(),
});
ID {
index: self.ids.len() - 1,
version: V::default(),
}
}
}
}
/// Adds an item to the BeachMap returning an ID.\
/// If you want to insert a self-referencing value, use `insert_with_id`.
pub fn insert(&mut self, value: T) -> ID<V> {
let id = self.next_id();
self.slots.push(id.index);
self.data.push(value);
id
}
/// Gives to `f` the future id of the element and insert the result of `f` to the BeachMap.
pub fn insert_with_id<F: FnOnce(ID<V>) -> T>(&mut self, f: F) -> ID<V> {
let id = self.next_id();
self.slots.push(id.index);
self.data.push(f(id));
id
}
/// Consumes as many available ids as possible and map slots to the new ids
fn map_indices(&mut self, additional: usize) {
let start = self.slots.len();
if let Some(available_ids) = &mut self.available_ids {
for i in 0..additional {
let head = available_ids.head;
self.slots.push(available_ids.head);
// assign first_available_id to the next available index
// or None if it's the last one
// SAFE while in the linked list, ids[index].index is always a valid ids index
if available_ids.is_last() {
self.available_ids = None;
// assign ids[index] to the index where the data will be
// SAFE slots are always valid ids index
unsafe {
self.ids.get_unchecked_mut(head).index = start + i;
}
break;
} else {
available_ids.head =
unsafe { self.ids.get_unchecked(available_ids.head).index };
// assign ids[index] to the index where the data will be
// SAFE slots are always valid ids index
unsafe {
self.ids.get_unchecked_mut(head).index = start + i;
}
}
}
}
self.ids.reserve(additional - (self.slots.len() - start));
for i in (self.slots.len() - start)..additional {
self.slots.push(start + i);
self.ids.push(ID {
index: start + i,
version: V::default(),
});
}
}
/// Moves all `vec`'s elements into the BeachMap leaving it empty.
pub fn append(&mut self, vec: &mut Vec<T>) -> Vec<ID<V>> {
let elements_count = vec.len();
// anchor to the first new index
let start = self.slots.len();
self.slots.reserve(elements_count);
self.map_indices(elements_count);
self.data.append(vec);
// SAFE slots are always valid ids index
self.slots[start..]
.iter()
.map(|&index| ID {
index,
version: unsafe { self.ids.get_unchecked(index).version },
})
.collect()
}
// Moves all `vec`'s elements into the BeachMap leaving it empty.\
// The IDs are stored in container.
pub fn append_in(&mut self, vec: &mut Vec<T>, container: &mut Vec<ID<V>>) {
let elements_count = vec.len();
// anchor to the first new index
let start = self.slots.len();
self.slots.reserve(elements_count);
self.map_indices(elements_count);
self.data.append(vec);
container.reserve(self.slots.len() - start);
self.slots[start..].iter().for_each(|&index| {
// SAFE slots are always valid ids index
container.push(ID {
index,
version: unsafe { self.ids.get_unchecked(index).version },
});
});
}
/// Inserts all elements of `iterator` into the BeachMap and return an ID for each element.
pub fn extend<I: IntoIterator<Item = T>>(&mut self, iterator: I) -> Vec<ID<V>> {
iterator.into_iter().map(|item| self.insert(item)).collect()
}
/// Returns a reference to the element corresponding to `id`.
#[inline]
pub fn get(&self, id: ID<V>) -> Option<&T> {
if let Some(&ID { version, .. }) = self.ids.get(id.index) {
if version == id.version {
// SAFE index is valid and the versions match
Some(unsafe { self.get_unchecked(id) })
} else {
None
}
} else {
None
}
}
/// Returns a mutable reference to an element corresponding to `id`.
#[inline]
pub fn get_mut(&mut self, id: ID<V>) -> Option<&mut T> {
if let Some(&ID { version, .. }) = self.ids.get(id.index) {
if version == id.version {
// SAFE index is valid and the versions match
Some(unsafe { self.get_unchecked_mut(id) })
} else {
None
}
} else {
None
}
}
/// Returns true if the BeachMap contains a value for the specified ID.
pub fn contains(&self, id: ID<V>) -> bool {
if id.index < self.ids.len() {
// SAFE all indices lower than len() exist
id.version == unsafe { self.ids.get_unchecked(id.index).version }
} else {
false
}
}
/// Removes an element from the BeachMap and returns it.
pub fn remove(&mut self, id: ID<V>) -> Option<T> {
if id.index < self.ids.len() {
//SAFE all index lower than len() exist
if unsafe { self.ids.get_unchecked(id.index).version == id.version } {
// SAFE ids[index].index is always a valid data index
let data_index = unsafe { self.ids.get_unchecked(id.index).index };
// change ids[slots.last()].index to data_index
// SAFE slots are always valid index
unsafe {
self.ids
.get_unchecked_mut(*self.slots.get_unchecked(self.slots.len() - 1))
.index = data_index;
}
// increment the version of ids[index]
unsafe {
self.ids.get_unchecked_mut(id.index).version += 1.into();
}
if let Some(available_ids) = &mut self.available_ids {
// if the linked list isn't empty make ids[index] point to the old tail
unsafe {
self.ids.get_unchecked_mut(available_ids.tail).index = id.index;
}
available_ids.tail = id.index;
} else {
self.available_ids = Some(LinkedList {
tail: id.index,
head: id.index,
});
}
self.slots.swap_remove(data_index);
Some(self.data.swap_remove(data_index))
} else {
None
}
} else {
None
}
}
/// Clears the BeachMap, removing all values.\
/// It does not affet the capacity.
pub fn clear(&mut self) {
// make sure available_ids is Some to be able to use unreachable_unchecked
if self.available_ids.is_none() && !self.slots.is_empty() {
self.available_ids = Some(LinkedList {
tail: unsafe { *self.slots.get_unchecked(0) },
head: unsafe { *self.slots.get_unchecked(0) },
});
}
// add all elements of the BeachMap to the available id linked list
for index in self.slots.drain(..) {
match &mut self.available_ids {
Some(available_ids) => {
// SAFE slots are always valid ids indices
unsafe { self.ids.get_unchecked_mut(index).version += 1.into() };
// SAFE available_ids are always valid ids indices
unsafe { self.ids.get_unchecked_mut(available_ids.tail).index = index };
available_ids.tail = index;
}
// SAFE we made sure it is Some unless slots.is_empty() and in this case the loop is ignored
None => unsafe { core::hint::unreachable_unchecked() },
}
}
self.data.clear();
}
/// Keep in the BeachMap the elements for which `f` returns true.
pub fn retain<F: FnMut(ID<V>, &mut T) -> bool>(&mut self, mut f: F) {
FilterOut::new(self, |id, x| !f(id, x)).for_each(drop)
}
/// Creates a draining iterator that removes all elements in the BeachMap and yields the removed items.\
/// The elements are removed even if the iterator is only partially consumed or not consumed at all.
pub fn drain(&mut self) -> alloc::vec::Drain<T> {
// make sure available_ids is Some to be able to use unreachable_unchecked
if self.available_ids.is_none() && !self.slots.is_empty() {
self.available_ids = Some(LinkedList {
tail: unsafe { *self.slots.get_unchecked(0) },
head: unsafe { *self.slots.get_unchecked(0) },
});
}
// add all elements of the BeachMap to the available id linked list
for index in self.slots.drain(..) {
match &mut self.available_ids {
Some(available_ids) => {
// SAFE slots are always valid ids indices
unsafe { self.ids.get_unchecked_mut(index) }.version += 1.into();
// SAFE available_ids are always valid ids indices
unsafe { self.ids.get_unchecked_mut(available_ids.tail) }.index = index;
available_ids.tail = index;
}
// SAFE we made sure it is Some unless slots.is_empty() and in this case the loop is ignored
None => unsafe { core::hint::unreachable_unchecked() },
}
}
self.data.drain(..)
}
/// Reserves `additional` ids. Call `use_ids` to add elements.
/// # Safety
/// `reverve_ids` and `use_ids` can be called in any order and can be called multiple times.\
/// But until you have use `additional` ids, adding or removing elements from the BeachMap will break it and other methods may panic.
pub unsafe fn reserve_ids(&mut self, additional: usize) -> Vec<ID<V>> {
let start = self.slots.len();
self.slots.reserve(additional);
self.map_indices(additional);
self.data.reserve(additional);
// SAFE slots are always valid ids index
self.slots[start..]
.iter()
.map(|&index| ID {
index,
version: self.ids.get_unchecked(index).version,
})
.collect()
}
/// Creates an iterator which uses a closure to determine if an element should be removed.\
/// If the closure returns true, then the element is removed and yielded along with its ID.
pub fn filter_out<F: FnMut(ID<V>, &mut T) -> bool>(&mut self, f: F) -> FilterOut<T, V, F> {
FilterOut::new(self, f)
}
/// Creates a draining iterator that removes all elements in the BeachMap and yields the removed items along with their ID.\
/// Only the elements consumed by the iterator are removed.
pub fn drain_with_id(&mut self) -> FilterOut<T, V, impl FnMut(ID<V>, &mut T) -> bool> {
FilterOut::new(self, |_, _| true)
}
}
impl<V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>, T>
core::ops::Index<ID<V>> for BeachMap<T, V>
{
type Output = T;
fn index(&self, id: ID<V>) -> &T {
self.get(id).unwrap()
}
}
impl<V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>, T>
core::ops::IndexMut<ID<V>> for BeachMap<T, V>
{
fn index_mut(&mut self, id: ID<V>) -> &mut T {
self.get_mut(id).unwrap()
}
}
impl<'beach, T, V> IntoIterator for &'beach BeachMap<T, V> {
type Item = &'beach T;
type IntoIter = core::slice::Iter<'beach, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'beach, T, V> IntoIterator for &'beach mut BeachMap<T, V> {
type Item = &'beach mut T;
type IntoIter = core::slice::IterMut<'beach, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
#[cfg(feature = "parallel")]
impl<'beach, T: Sync + 'beach, V> rayon::prelude::IntoParallelIterator for &'beach BeachMap<T, V> {
type Item = &'beach T;
type Iter = rayon::slice::Iter<'beach, T>;
fn into_par_iter(self) -> Self::Iter {
self.data.into_par_iter()
}
}
#[cfg(feature = "parallel")]
impl<'beach, T: Send + Sync + 'beach, V> rayon::prelude::IntoParallelIterator
for &'beach mut BeachMap<T, V>
{
type Item = &'beach mut T;
type Iter = rayon::slice::IterMut<'beach, T>;
fn into_par_iter(self) -> Self::Iter {
use rayon::prelude::IntoParallelRefMutIterator;
self.data.par_iter_mut()
}
}
pub struct FilterOut<'beach, T, V, F>
where
V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>,
F: FnMut(ID<V>, &mut T) -> bool,
{
beach: &'beach mut BeachMap<T, V>,
index: usize,
pred: F,
}
impl<'beach, T, V, F> FilterOut<'beach, T, V, F>
where
V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>,
F: FnMut(ID<V>, &mut T) -> bool,
{
fn new(beach: &'beach mut BeachMap<T, V>, f: F) -> FilterOut<'beach, T, V, F> {
// make sure first_available_id is Some to be able to use unreachable_unchecked
if beach.available_ids.is_none() && !beach.slots.is_empty() {
beach.available_ids = Some(LinkedList {
tail: unsafe { *beach.slots.get_unchecked(0) },
head: unsafe { *beach.slots.get_unchecked(0) },
});
}
FilterOut {
beach,
index: 0,
pred: f,
}
}
}
impl<'beach, T, V, F> Iterator for FilterOut<'beach, T, V, F>
where
V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>,
F: FnMut(ID<V>, &mut T) -> bool,
{
type Item = (ID<V>, T);
fn next(&mut self) -> Option<(ID<V>, T)> {
let data = &mut self.beach.data;
while self.index < data.len() {
// SAFE slots and data have the same length
let index = unsafe { *self.beach.slots.get_unchecked(self.index) };
// SAFE slots are always valid ids indices
let version = unsafe { self.beach.ids.get_unchecked(index).version };
let id = ID { index, version };
if (self.pred)(id, unsafe { data.get_unchecked_mut(self.index) }) {
unsafe {
self.beach.ids.get_unchecked_mut(index).version += 1.into();
}
match &mut self.beach.available_ids {
Some(available_ids) => {
// SAFE available_ids are always valid ids indices
unsafe {
self.beach.ids.get_unchecked_mut(available_ids.tail).index = index;
available_ids.tail = index;
}
}
None => unsafe { core::hint::unreachable_unchecked() },
};
let result = Some((id, data.swap_remove(self.index)));
self.beach.slots.swap_remove(self.index);
return result;
} else {
self.index += 1;
}
}
None
}
}
pub struct IterID<'beach, T, V> {
beach: &'beach BeachMap<T, V>,
index: usize,
}
impl<'beach, T, V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>> Iterator
for IterID<'beach, T, V>
{
type Item = (ID<V>, &'beach T);
fn next(&mut self) -> Option<(ID<V>, &'beach T)> {
if self.index < self.beach.len() {
let data_index = self.index;
self.index += 1;
// SAFE slots and data have always the same len
let index = unsafe { *self.beach.slots.get_unchecked(data_index) };
// SAFE slots are always valid ids indices
Some((
ID {
index,
version: unsafe { self.beach.ids.get_unchecked(index).version },
},
unsafe { self.beach.data.get_unchecked(data_index) },
))
} else {
None
}
}
}
pub struct IterMutID<'beach, T, V> {
ids: &'beach [ID<V>],
slots: &'beach [usize],
data: *mut T,
index: usize,
_phantom: core::marker::PhantomData<&'beach mut T>,
}
impl<
'beach,
T: 'beach,
V: Copy + Clone + Default + PartialEq + core::ops::AddAssign + From<u8>,
> Iterator for IterMutID<'beach, T, V>
{
type Item = (ID<V>, &'beach mut T);
fn next(&mut self) -> Option<(ID<V>, &'beach mut T)> {
if self.index < self.slots.len() {
let data_index = self.index;
self.index += 1;
// SAFE slots and data have always the same len
let index = unsafe { *self.slots.get_unchecked(data_index) };
// SAFE slots are always valid ids indices
// SAFE we are making multiple &mut ref but it is always to different indices
Some((
ID {
index,
version: unsafe { self.ids.get_unchecked(index) }.version,
},
unsafe { &mut *self.data.add(data_index) },
))
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert() {
let mut beach = BeachMap::<u32>::default();
let id = beach.insert(5);
assert_eq!(id.index, 0);
assert_eq!(id.version, 0);
assert_eq!(beach.ids[id.index].version, id.version);
assert_eq!(beach.slots[beach.slots.len() - 1], id.index);
assert_eq!(beach.data[beach.ids[id.index].index], 5);
assert!(beach.ids.len() == 1 && beach.slots.len() == 1 && beach.data.len() == 1);
let id2 = beach.insert(10);
assert_eq!(id2.index, 1);
assert_eq!(id.version, 0);
assert_eq!(beach.ids[id2.index].version, id2.version);
assert_eq!(beach.slots[beach.slots.len() - 1], id2.index);
assert_eq!(beach.data[beach.ids[id2.index].index], 10);
assert!(beach.ids.len() == 2 && beach.slots.len() == 2 && beach.data.len() == 2);
}
#[test]
fn insert_with_id() {
struct SelfRef {
self_ref: ID<u32>,
}
let mut beach = BeachMap::<SelfRef>::default();
let id = beach.insert_with_id(|id| SelfRef { self_ref: id });
assert_eq!(beach[id].self_ref, id);
}
#[test]
fn append() {
let mut beach = BeachMap::default();
let ids = beach.append(&mut vec![0, 1, 2, 3]);
assert_eq!(beach.ids.len(), 4);
assert_eq!(beach.slots.len(), 4);
assert_eq!(beach.data.len(), 4);
for (i, &id) in ids.iter().enumerate() {
assert_eq!(id.index, i);
assert_eq!(id.version, 0);
assert_eq!(beach.ids[id.index].version, id.version);
assert_eq!(beach.slots[i], id.index);
assert_eq!(beach[id], i);
}
}
#[test]
fn append_and_remove() {
let mut beach = BeachMap::<u32>::default();
let mut values = vec![0, 1, 2, 3];
let mut new_values = vec![4, 5, 6];
let mut old_ids = beach.append(&mut values);
let ids = old_ids.drain(2..).collect::<Vec<_>>();
for id in &old_ids {
beach.remove(*id);
}
let new_ids = beach.append(&mut new_values);
assert_eq!(beach.ids.len(), 5);
assert_eq!(beach.slots.len(), 5);
assert_eq!(beach.data.len(), 5);
assert_eq!(new_ids[0].index, old_ids[0].index);
assert_eq!(new_ids[0].version, old_ids[0].version + 1);
assert_eq!(beach[new_ids[0]], 4);
assert_eq!(new_ids[1].index, old_ids[1].index);
assert_eq!(new_ids[1].version, old_ids[1].version + 1);
assert_eq!(beach[new_ids[1]], 5);
assert_eq!(new_ids[2].index, 4);
assert_eq!(new_ids[2].version, 0);
assert_eq!(beach[new_ids[2]], 6);
assert_eq!(beach[ids[0]], 2);
assert_eq!(beach[ids[1]], 3);
}
#[test]
fn append_in() {
let mut beach = BeachMap::default();
let mut values = vec![0, 1, 2, 3];
let mut ids = Vec::new();
beach.append_in(&mut values, &mut ids);
assert_eq!(beach.ids.len(), 4);
assert_eq!(beach.slots.len(), 4);
assert_eq!(beach.data.len(), 4);
for (i, &id) in ids.iter().enumerate() {
assert_eq!(id.index, i);
assert_eq!(id.version, 0);
assert_eq!(beach.ids[id.index].version, id.version);
assert_eq!(beach.slots[i], id.index);
assert_eq!(beach.data[beach.ids[id.index].index], i);
}
}
#[test]
fn append_in_and_remove() {
let mut beach = BeachMap::default();
let mut values = vec![0, 1, 2, 3];
let mut new_values = vec![4, 5, 6];
let mut old_ids = Vec::new();
beach.append_in(&mut values, &mut old_ids);
let ids = old_ids.drain(2..).collect::<Vec<_>>();
for id in &old_ids {
beach.remove(*id);
}
let new_ids = beach.append(&mut new_values);
assert_eq!(beach.ids.len(), 5);
assert_eq!(beach.slots.len(), 5);
assert_eq!(beach.data.len(), 5);
assert_eq!(new_ids[0].index, old_ids[0].index);
assert_eq!(new_ids[0].version, old_ids[0].version + 1);
assert_eq!(beach[new_ids[0]], 4);
assert_eq!(new_ids[1].index, old_ids[1].index);
assert_eq!(new_ids[1].version, old_ids[1].version + 1);
assert_eq!(beach[new_ids[1]], 5);
assert_eq!(new_ids[2].index, 4);
assert_eq!(new_ids[2].version, 0);
assert_eq!(beach[new_ids[2]], 6);
assert_eq!(beach[ids[0]], 2);
assert_eq!(beach[ids[1]], 3);
}
#[test]
fn expend() {
let mut beach = BeachMap::default();
beach.extend(0..4);
assert_eq!(beach.data(), [0, 1, 2, 3]);
}
#[test]
fn get_and_get_mut() {
let mut beach = BeachMap::<u32>::default();
let id = beach.insert(5);
assert_eq!(beach.get(id), Some(&5));
assert_eq!(beach.get_mut(id), Some(&mut 5));
let id2 = beach.insert(10);
assert_eq!(beach.get(id2), Some(&10));
assert_eq!(beach.get_mut(id2), Some(&mut 10));
}
#[test]
fn get_and_get_mut_non_existant() {
let mut beach = BeachMap::default();
beach.insert(5);
let id = ID {
index: 1,
version: 0,
};
assert_eq!(beach.get(id), None);
assert_eq!(beach.get_mut(id), None);
let id2 = ID {
index: 0,
version: 1,
};
assert_eq!(beach.get(id2), None);
assert_eq!(beach.get_mut(id2), None);
}
#[test]
fn contains() {
let mut beach = BeachMap::default();
let id = beach.insert(5);
assert_eq!(beach.contains(id), true);
beach.remove(id);
assert_eq!(beach.contains(id), false);
}
#[test]
fn remove() {
let mut beach = BeachMap::<u32>::default();
let id = beach.insert(5);
let id2 = beach.insert(10);
assert_eq!(beach.remove(id), Some(5));
assert_eq!(beach.remove(id), None);
assert_eq!(beach.ids[id.index].version, id.version + 1);
assert_eq!(
beach.available_ids,
Some(LinkedList {
tail: id.index,
head: id.index
})
);
assert_eq!(beach[id2], 10);
assert_eq!(beach.ids.len(), 2);
assert_eq!(beach.slots.len(), 1);
assert_eq!(beach.data.len(), 1);
assert_eq!(beach.len(), 1);
assert!(beach.capacity() >= 2);
assert_eq!(beach.remove(id2), Some(10));
assert_eq!(beach.remove(id2), None);
assert_eq!(beach.ids[id2.index].version, id2.version + 1);
assert_eq!(
beach.available_ids,
Some(LinkedList {
tail: id2.index,
head: id.index
})
);
assert_eq!(beach.ids.len(), 2);
assert_eq!(beach.slots.len(), 0);
assert_eq!(beach.data.len(), 0);
assert_eq!(beach.len(), 0);
assert!(beach.capacity() >= 2);
let id3 = beach.insert(15);
assert_eq!(id3.index, id.index);
assert_eq!(id3.version, id.version + 1);
assert_eq!(beach.ids[id3.index].version, id3.version);
assert_eq!(
beach.available_ids,
Some(LinkedList {
tail: id2.index,
head: id2.index
})
);
assert_eq!(beach[id3], 15);
assert_eq!(beach.ids.len(), 2);
assert_eq!(beach.slots.len(), 1);
assert_eq!(beach.data.len(), 1);
let id4 = beach.insert(20);
assert_eq!(id4.index, id2.index);
assert_eq!(id4.version, id2.version + 1);
assert_eq!(beach.ids[id4.index].version, id4.version);
assert_eq!(beach.available_ids, None);
assert_eq!(beach[id4], 20);
assert_eq!(beach.ids.len(), 2);
assert_eq!(beach.slots.len(), 2);
assert_eq!(beach.data.len(), 2);
}
#[test]
fn iterators() {
let mut beach = BeachMap::default();
for i in 0..5 {
beach.insert(i);
}
for (value_iter, value_data) in beach.iter().zip(beach.data.iter()) {
assert_eq!(value_iter, value_data);
}
for value in &mut beach {
*value += 1;
}
for (i, (value_iter, value_data)) in beach.iter().zip(beach.data.iter()).enumerate() {
assert_eq!(value_iter, value_data);
assert_eq!(*value_iter, i + 1);
}
}
#[test]
fn iterator_with_id() {
let mut beach = BeachMap::default();
let ids = beach.extend(0..4);
let mut iter = beach.iter_with_id();
assert_eq!(iter.next(), Some((ids[0], &0)));
assert_eq!(iter.next(), Some((ids[1], &1)));
assert_eq!(iter.next(), Some((ids[2], &2)));
assert_eq!(iter.next(), Some((ids[3], &3)));
assert_eq!(iter.next(), None);
}
/*// Should not compile or pass
// You should not be able to have at the same time a mut ref to some variable inside the BeachMap and a mut ref to the BeachMap
#[test]
fn iter_mut_with_id() {
let mut beach = BeachMap::<u32, _>::default();
beach.insert(5);
let test;
{
let mut iter = beach.iter_mut_with_id();
test = iter.next();
}
beach.reserve(100);
println!("{:?}", test);
}*/
#[test]
fn len() {
let mut beach = BeachMap::default();
let id = beach.insert(5);
assert_eq!(beach.len(), beach.slots.len());
assert_eq!(beach.len(), beach.data.len());
beach.remove(id);
assert_eq!(beach.len(), beach.slots.len());
assert_eq!(beach.len(), beach.data.len());
let mut values = (0..100).collect::<Vec<_>>();
beach.append(&mut values);
assert_eq!(beach.len(), beach.slots.len());
assert_eq!(beach.len(), beach.data.len());
}
#[test]
fn reserve() {
let mut beach = BeachMap::<u32>::default();
beach.reserve(100);
assert!(beach.ids.capacity() >= 100);
assert!(beach.slots.capacity() >= 100);
assert!(beach.data.capacity() >= 100);
}
#[test]
fn reserve_ids() {
let mut beach = BeachMap::default();
let mut values = (0..100).collect::<Vec<_>>();
let ids = unsafe { beach.reserve_ids(values.len()) };
assert_eq!(beach.ids.len(), 100);
assert_eq!(beach.slots.len(), 100);
assert_eq!(beach.data.len(), 0);
assert!(beach.data.capacity() >= 100);
for (i, &id) in ids.iter().enumerate() {
assert_eq!(id.index, i);
assert_eq!(id.version, 0);
assert_eq!(beach.ids[id.index].version, id.version);
assert_eq!(beach.slots[i], id.index);
}
unsafe { beach.use_ids(&mut values) };
assert_eq!(beach.ids.len(), 100);
assert_eq!(beach.slots.len(), 100);
assert_eq!(beach.data.len(), 100);
for (i, &id) in ids.iter().enumerate() {
assert_eq!(beach.ids[id.index].version, id.version);
assert_eq!(beach.slots[i], id.index);
assert_eq!(beach.data[beach.ids[id.index].index], i);
}
}
#[test]
fn clear() {
let mut beach = BeachMap::default();
beach.extend(0..4);
beach.clear();
assert!(beach.capacity() >= 4);
assert_eq!(beach.len(), 0);
let ids = beach.extend(5..7);
assert_eq!(beach[ids[0]], 5);
assert_eq!(beach[ids[1]], 6);
}
#[test]
fn filter_out() {
let mut beach = BeachMap::default();
beach.extend(0..5);
let mut filter_out = beach.filter_out(|_, _| true);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 0,
version: 0
},
0
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 4,
version: 0
},
4
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 3,
version: 0
},
3
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 2,
version: 0
},
2
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 1,
version: 0
},
1
))
);
assert_eq!(filter_out.next(), None);
let ids = beach.extend(5..10);
assert_eq!(beach[ids[0]], 5);
assert_eq!(beach[ids[1]], 6);
assert_eq!(beach[ids[2]], 7);
assert_eq!(beach[ids[3]], 8);
assert_eq!(beach[ids[4]], 9);
let mut beach2 = BeachMap::default();
(0u32..6).map(|x| beach2.insert(x)).for_each(|_| {});
let mut filter_out = beach2.filter_out(|_, &mut x| x % 2 == 0);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 0,
version: 0
},
0
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 2,
version: 0
},
2
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 4,
version: 0
},
4
))
);
assert_eq!(filter_out.next(), None);
assert_eq!(beach2.data[0], 5);
assert_eq!(beach2.data[1], 1);
assert_eq!(beach2.data[2], 3);
let mut beach3 = BeachMap::default();
(0u32..6).map(|x| beach3.insert(x)).for_each(|_| {});
let mut filter_out = beach3.filter_out(|_, &mut x| x % 2 != 0);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 1,
version: 0
},
1
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 5,
version: 0
},
5
))
);
assert_eq!(
filter_out.next(),
Some((
ID {
index: 3,
version: 0
},
3
))
);
assert_eq!(filter_out.next(), None);
assert_eq!(beach3.data[0], 0);
assert_eq!(beach3.data[1], 4);
assert_eq!(beach3.data[2], 2);
}
#[test]
fn drain() {
let mut beach = BeachMap::default();
beach.extend(0..4);
let mut drain = beach.drain();
assert_eq!(drain.next(), Some(0));
assert_eq!(drain.next(), Some(1));
assert_eq!(drain.next(), Some(2));
assert_eq!(drain.next(), Some(3));
assert_eq!(drain.next(), None);
drop(drain);
let ids = beach.extend(4..8);
assert_eq!(beach[ids[0]], 4);
assert_eq!(beach[ids[1]], 5);
assert_eq!(beach[ids[2]], 6);
assert_eq!(beach[ids[3]], 7);
}
}
|
use std::collections::HashSet;
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let s = scan!(String);
let t = scan!(String);
let mut s: Vec<char> = s.chars().collect();
let mut t: Vec<char> = t.chars().collect();
for _ in 0..2 {
let mut dest = vec![HashSet::new(); 26];
for i in 0..s.len() {
dest[s[i] as usize - 'a' as usize].insert(t[i] as usize - 'a' as usize);
}
let ok = dest.iter().all(|s| s.len() <= 1);
if !ok {
println!("No");
return;
}
std::mem::swap(&mut s, &mut t);
}
println!("Yes");
}
|
/// Returns a all of the elements provided in list, sorted.
///
/// # Arguments
///
/// * `list` - A list of elements to sort.
/// * `_unused_param` - Provided only for demonstration purposes.
pub fn merge_sort<T: PartialOrd + Clone>(list: Vec<T>, _unused_param: usize) -> Vec<T> {
return merge_sort_recur(list);
}
fn merge_sort_recur<T: PartialOrd + Clone>(list: Vec<T>) -> Vec<T> {
if list.len() == 1 {
return list;
}
let mid = (list.len()-1)/2 + 1;
// Print me here....
let left = merge_sort_recur(list.clone()[0..mid].to_vec()); //left
let right = merge_sort_recur(list.clone()[mid..list.len()].to_vec()); //right
merge(left, right)
}
fn merge<T: PartialOrd + Clone>(left: Vec<T>, right: Vec<T>) -> Vec<T> {
let mut new: Vec<T> = Vec::new();
let mut left_idx = 0;
let mut right_idx = 0;
while new.len() < left.len() + right.len() {
while left[left_idx] <= right[right_idx] {
new.push(left[left_idx].clone());
left_idx += 1;
if left_idx > left.len() - 1 {
append(right, right_idx, & mut new);
return new
}
}
while right[right_idx] <= left[left_idx] {
new.push(right[right_idx].clone()); // Point out explicit clone here vs copy
right_idx += 1;
if right_idx > right.len() - 1 {
append(left, left_idx, & mut new);
return new
}
}
}
new
}
fn append<T: PartialOrd + Clone>(from: Vec<T>, mut from_idx: usize, to: &mut Vec<T>) {
while from_idx <= from.len() - 1 {
to.push(from[from_idx].clone());
from_idx += 1;
}
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
#[test]
fn test_merge_lst() {
let left = vec![1, 3];
let right = vec![2];
// Private functions can be tested too!
assert_eq!(merge(left, right), vec![1, 2, 3]);
}
#[test]
fn test_merge_sort() {
let list = vec![1, 3, 2, 5, 8, 7, 0, 4, 6, 9];
assert_eq!(merge_sort(list, 5), vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
}
}
// println!("left: {:?}", list.clone()[0..mid].to_vec());
// println!("right: {:?}", list.clone()[mid..list.len()].to_vec()); |
use crate::util::{drop_span, ExprFactory, HANDLER};
use dashmap::DashMap;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{iter, mem};
use swc_atoms::{js_word, JsWord};
use swc_common::{iter::IdentifyLast, sync::Lrc, FileName, SourceMap, Spanned, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_parser::{Parser, StringInput, Syntax};
use swc_ecma_visit::{Fold, FoldWith};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Options {
#[serde(default = "default_pragma")]
pub pragma: String,
#[serde(default = "default_pragma_frag")]
pub pragma_frag: String,
#[serde(default = "default_throw_if_namespace")]
pub throw_if_namespace: bool,
#[serde(default)]
pub development: bool,
#[serde(default)]
pub use_builtins: bool,
}
impl Default for Options {
fn default() -> Self {
Options {
pragma: default_pragma(),
pragma_frag: default_pragma_frag(),
throw_if_namespace: default_throw_if_namespace(),
development: false,
use_builtins: false,
}
}
}
fn default_pragma() -> String {
"React.createElement".into()
}
fn default_pragma_frag() -> String {
"React.Fragment".into()
}
fn default_throw_if_namespace() -> bool {
true
}
fn parse_option(cm: &SourceMap, name: &str, src: String) -> Box<Expr> {
static CACHE: Lazy<DashMap<String, Box<Expr>>> = Lazy::new(|| DashMap::with_capacity(2));
let fm = cm.new_source_file(FileName::Custom(format!("<jsx-config-{}.js>", name)), src);
if let Some(expr) = CACHE.get(&**fm.src) {
return expr.clone();
}
let expr = Parser::new(Syntax::default(), StringInput::from(&*fm), None)
.parse_expr()
.map_err(|e| {
if HANDLER.is_set() {
HANDLER.with(|h| e.into_diagnostic(h).emit())
}
})
.map(drop_span)
.unwrap_or_else(|()| {
panic!(
"faield to parse jsx option {}: '{}' is not an expression",
name, fm.src,
)
});
CACHE.insert((*fm.src).clone(), expr.clone());
expr
}
/// `@babel/plugin-transform-react-jsx`
///
/// Turn JSX into React function calls
pub fn jsx(cm: Lrc<SourceMap>, options: Options) -> impl Fold {
Jsx {
pragma: ExprOrSuper::Expr(parse_option(&cm, "pragma", options.pragma)),
pragma_frag: ExprOrSpread {
spread: None,
expr: parse_option(&cm, "pragmaFrag", options.pragma_frag),
},
use_builtins: options.use_builtins,
throw_if_namespace: options.throw_if_namespace,
}
}
struct Jsx {
pragma: ExprOrSuper,
pragma_frag: ExprOrSpread,
use_builtins: bool,
throw_if_namespace: bool,
}
noop_fold_type!(Jsx);
impl Jsx {
fn jsx_frag_to_expr(&mut self, el: JSXFragment) -> Expr {
let span = el.span();
Expr::Call(CallExpr {
span,
callee: self.pragma.clone(),
args: iter::once(self.pragma_frag.clone())
// attribute: null
.chain(iter::once(Lit::Null(Null { span: DUMMY_SP }).as_arg()))
.chain({
// Children
el.children
.into_iter()
.filter_map(|c| self.jsx_elem_child_to_expr(c))
})
.collect(),
type_args: None,
})
}
fn jsx_elem_to_expr(&mut self, el: JSXElement) -> Expr {
let span = el.span();
let name = self.jsx_name(el.opening.name);
Expr::Call(CallExpr {
span,
callee: self.pragma.clone(),
args: iter::once(name.as_arg())
.chain(iter::once({
// Attributes
self.fold_attrs(el.opening.attrs).as_arg()
}))
.chain({
// Children
el.children
.into_iter()
.filter_map(|c| self.jsx_elem_child_to_expr(c))
})
.collect(),
type_args: Default::default(),
})
}
fn jsx_elem_child_to_expr(&mut self, c: JSXElementChild) -> Option<ExprOrSpread> {
Some(match c {
JSXElementChild::JSXText(text) => {
// TODO(kdy1): Optimize
let s = Str {
span: text.span,
has_escape: text.raw != text.value,
value: jsx_text_to_str(text.value),
};
if s.value.is_empty() {
return None;
}
Lit::Str(s).as_arg()
}
JSXElementChild::JSXExprContainer(JSXExprContainer {
expr: JSXExpr::Expr(e),
..
}) => e.as_arg(),
JSXElementChild::JSXExprContainer(JSXExprContainer {
expr: JSXExpr::JSXEmptyExpr(..),
..
}) => return None,
JSXElementChild::JSXElement(el) => self.jsx_elem_to_expr(*el).as_arg(),
JSXElementChild::JSXFragment(el) => self.jsx_frag_to_expr(el).as_arg(),
JSXElementChild::JSXSpreadChild(JSXSpreadChild { .. }) => {
unimplemented!("jsx sperad child")
}
})
}
fn fold_attrs(&mut self, attrs: Vec<JSXAttrOrSpread>) -> Box<Expr> {
if attrs.is_empty() {
return Box::new(Expr::Lit(Lit::Null(Null { span: DUMMY_SP })));
}
let is_complex = attrs.iter().any(|a| match *a {
JSXAttrOrSpread::SpreadElement(..) => true,
_ => false,
});
if is_complex {
let mut args = vec![];
let mut cur_obj_props = vec![];
macro_rules! check {
() => {{
if args.is_empty() || !cur_obj_props.is_empty() {
args.push(
ObjectLit {
span: DUMMY_SP,
props: mem::replace(&mut cur_obj_props, vec![]),
}
.as_arg(),
)
}
}};
}
for attr in attrs {
match attr {
JSXAttrOrSpread::JSXAttr(a) => {
cur_obj_props.push(PropOrSpread::Prop(Box::new(attr_to_prop(a))))
}
JSXAttrOrSpread::SpreadElement(e) => {
check!();
args.push(e.expr.as_arg());
}
}
}
check!();
// calls `_extends` or `Object.assign`
Box::new(Expr::Call(CallExpr {
span: DUMMY_SP,
callee: {
if self.use_builtins {
member_expr!(DUMMY_SP, Object.assign).as_callee()
} else {
helper!(extends, "extends")
}
},
args,
type_args: None,
}))
} else {
Box::new(Expr::Object(ObjectLit {
span: DUMMY_SP,
props: attrs
.into_iter()
.map(|a| match a {
JSXAttrOrSpread::JSXAttr(a) => a,
_ => unreachable!(),
})
.map(attr_to_prop)
.map(|v| v.fold_with(self))
.map(Box::new)
.map(PropOrSpread::Prop)
.collect(),
}))
}
}
}
impl Fold for Jsx {
fn fold_expr(&mut self, expr: Expr) -> Expr {
let mut expr = expr.fold_children_with(self);
if let Expr::JSXElement(el) = expr {
// <div></div> => React.createElement('div', null);
return self.jsx_elem_to_expr(*el);
}
if let Expr::JSXFragment(frag) = expr {
// <></> => React.createElement(React.Fragment, null);
return self.jsx_frag_to_expr(frag);
}
if let Expr::Paren(ParenExpr {
span,
expr: inner_expr,
..
}) = expr
{
if let Expr::JSXElement(el) = *inner_expr {
return self.jsx_elem_to_expr(*el);
}
if let Expr::JSXFragment(frag) = *inner_expr {
// <></> => React.createElement(React.Fragment, null);
return self.jsx_frag_to_expr(frag);
}
expr = Expr::Paren(ParenExpr {
span,
expr: inner_expr,
});
}
expr
}
}
impl Jsx {
fn jsx_name(&self, name: JSXElementName) -> Box<Expr> {
let span = name.span();
match name {
JSXElementName::Ident(i) => {
// If it starts with lowercase digit
let c = i.sym.chars().next().unwrap();
if i.sym == js_word!("this") {
return Box::new(Expr::This(ThisExpr { span }));
}
if c.is_ascii_lowercase() {
Box::new(Expr::Lit(Lit::Str(Str {
span,
value: i.sym,
has_escape: false,
})))
} else {
Box::new(Expr::Ident(i))
}
}
JSXElementName::JSXNamespacedName(JSXNamespacedName { ref ns, ref name }) => {
if self.throw_if_namespace {
HANDLER.with(|handler| {
handler
.struct_span_err(
span,
"JSX Namespace is disabled by default because react does not \
support it yet. You can specify \
jsc.transform.react.throwIfNamespace to false to override \
default behavior",
)
.emit()
});
}
Box::new(Expr::Lit(Lit::Str(Str {
span,
value: format!("{}:{}", ns.sym, name.sym).into(),
has_escape: false,
})))
}
JSXElementName::JSXMemberExpr(JSXMemberExpr { obj, prop }) => {
fn convert_obj(obj: JSXObject) -> ExprOrSuper {
let span = obj.span();
match obj {
JSXObject::Ident(i) => {
if i.sym == js_word!("this") {
return ExprOrSuper::Expr(Box::new(Expr::This(ThisExpr { span })));
}
i.as_obj()
}
JSXObject::JSXMemberExpr(e) => {
let e = *e;
MemberExpr {
span,
obj: convert_obj(e.obj),
prop: Box::new(Expr::Ident(e.prop)),
computed: false,
}
.as_obj()
}
}
}
Box::new(Expr::Member(MemberExpr {
span,
obj: convert_obj(obj),
prop: Box::new(Expr::Ident(prop)),
computed: false,
}))
}
}
}
}
fn attr_to_prop(a: JSXAttr) -> Prop {
let key = to_prop_name(a.name);
let value = a
.value
.map(|v| match v {
JSXAttrValue::JSXExprContainer(JSXExprContainer {
expr: JSXExpr::Expr(e),
..
}) => e,
JSXAttrValue::JSXElement(e) => Box::new(Expr::JSXElement(e)),
JSXAttrValue::JSXFragment(e) => Box::new(Expr::JSXFragment(e)),
JSXAttrValue::Lit(lit) => Box::new(lit.into()),
JSXAttrValue::JSXExprContainer(JSXExprContainer {
span: _,
expr: JSXExpr::JSXEmptyExpr(_),
}) => unreachable!("attr_to_prop(JSXEmptyExpr)"),
})
.unwrap_or_else(|| {
Box::new(Expr::Lit(Lit::Bool(Bool {
span: key.span(),
value: true,
})))
});
Prop::KeyValue(KeyValueProp { key, value })
}
fn to_prop_name(n: JSXAttrName) -> PropName {
let span = n.span();
match n {
JSXAttrName::Ident(i) => {
if i.sym.contains('-') {
PropName::Str(Str {
span,
value: i.sym,
has_escape: false,
})
} else {
PropName::Ident(i)
}
}
JSXAttrName::JSXNamespacedName(JSXNamespacedName { ns, name }) => PropName::Str(Str {
span,
value: format!("{}:{}", ns.sym, name.sym).into(),
has_escape: false,
}),
}
}
fn jsx_text_to_str(t: JsWord) -> JsWord {
static SPACE_NL_START: Lazy<Regex> = Lazy::new(|| Regex::new("^\\s*\n\\s*").unwrap());
static SPACE_NL_END: Lazy<Regex> = Lazy::new(|| Regex::new("\\s*\n\\s*$").unwrap());
if t == *" " {
return t;
}
if !t.contains(' ') && !t.contains('\n') {
return t;
}
let s = SPACE_NL_START.replace_all(&t, "");
let s = SPACE_NL_END.replace_all(&s, "");
let need_leading_space = s.starts_with(' ');
let need_trailing_space = s.ends_with(' ');
let mut buf = String::from(if need_leading_space { " " } else { "" });
for (last, s) in s.split_ascii_whitespace().identify_last() {
buf.push_str(s);
if !last {
buf.push(' ');
}
}
if need_trailing_space && !buf.ends_with(' ') {
buf.push(' ');
}
buf.into()
}
|
use dynasm::dynasm;
use dynasmrt::DynasmApi;
use std::{error::Error, fs, fs::File, io::Write, os::unix::fs::PermissionsExt, path::PathBuf};
// TODO: These are not constant
pub(crate) const CODE_START: usize = 0x11f8;
const PAGE: usize = 4096;
const RAM_PAGES: usize = 1024; // 4MB RAM
pub(crate) fn rom_start(code_size: usize) -> usize {
// Add offset and round to next page boundary
let mut code_end = CODE_START + code_size;
if code_end % PAGE != 0 {
code_end += PAGE;
code_end -= code_end % PAGE;
}
assert_eq!(code_end % PAGE, 0);
code_end
}
pub(crate) fn ram_start(rom_start: usize, rom_size: usize) -> usize {
// Add offset and round to next page boundary
let mut rom_end = rom_start + rom_size;
if rom_end % PAGE != 0 {
rom_end += PAGE;
rom_end -= rom_end % PAGE;
}
assert_eq!(rom_end % PAGE, 0);
rom_end
}
/// The `code`, `rom` and `ram` segments will be extended to 4k page boundaries,
/// concatenated and loaded at address 0x1000. Ram will be extended to 4MB.
pub(crate) struct Assembly {
pub(crate) code: Vec<u8>,
pub(crate) rom: Vec<u8>,
pub(crate) ram: Vec<u8>,
}
impl Assembly {
pub(crate) fn save(&self, destination: &PathBuf) -> Result<(), Box<dyn Error>> {
let exe = self.to_macho();
{
let mut file = File::create(destination)?;
file.write_all(&exe)?;
file.sync_all()?;
}
{
let mut perms = fs::metadata(destination)?.permissions();
perms.set_mode(0o755); // rwx r_x r_x
fs::set_permissions(destination, perms)?;
}
Ok(())
}
// NOTE: The documentation on Mach-O is incomplete compared to the source. XNU
// is substantially stricter than the documentation may appear.
// See <https://pewpewthespells.com/re/Mach-O_File_Format.pdf>
// See <https://github.com/apple/darwin-xnu/blob/master/EXTERNAL_HEADERS/mach-o/loader.h>
// See <https://github.com/apple/darwin-xnu/blob/master/bsd/kern/mach_loader.c>
pub(crate) fn to_macho(&self) -> Vec<u8> {
let num_segments = 4;
let header_size: usize = 32 + 72 * num_segments + 184;
let code_pages = (self.code.len() + header_size + PAGE - 1) / PAGE;
let rom_pages = (self.rom.len() + PAGE - 1) / PAGE;
let ram_init_pages = (self.ram.len() + PAGE - 1) / PAGE;
let ram_pages = std::cmp::max(RAM_PAGES, ram_init_pages);
let mut ops = dynasmrt::x64::Assembler::new().unwrap();
// All offsets and sizes are in pages
fn segment(
ops: &mut dynasmrt::x64::Assembler,
vm_start: usize,
vm_size: usize,
file_start: usize,
file_size: usize,
protect: u32,
) {
assert!(vm_size > 0);
let file_start = if file_size > 0 { file_start } else { 0 };
dynasm!(ops
; .dword 0x19 // Segment command
; .dword 72 // command size
; .qword 0 // segment name
; .qword 0 // segment name
; .qword (vm_start * PAGE) as i64 // VM Address
; .qword (vm_size * PAGE) as i64 // VM Size
; .qword (file_start * PAGE) as i64 // File Offset
; .qword (file_size * PAGE) as i64 // File Size
; .dword protect as i32 // max protect
; .dword protect as i32 // initial protect
; .dword 0 // Num sections
; .dword 0 // Flags
);
}
let end_of_ram = code_pages + rom_pages + ram_pages;
let mut vm_offset = 0;
let mut file_offset = 0;
// Mach-O header (32 bytes)
dynasm!(ops
; .dword 0xfeed_facf_u32 as i32 // Magic
; .dword 0x0100_0007_u32 as i32 // Cpu type x86_64
; .dword 0x8000_0003_u32 as i32 // Cpu subtype (i386)
; .dword 0x2 // Type: executable
; .dword (num_segments + 1) as i32 // num_commands
; .dword (num_segments * 72 + 184) as i32 // Size of commands
; .dword 0x1 // Noun definitions
; .dword 0 // Reserved
);
// Page zero (___)
// This is required by XNU for the process to start.
segment(&mut ops, vm_offset, 1, 0, 0, 0);
vm_offset += 1;
// Code (R_X)
// XNU insists there is one R_X segment starting from the start of the file,
// even tough this includes the non-executable the Mach-O headers.
// See <https://github.com/apple/darwin-xnu/blob/a449c6a/bsd/kern/mach_loader.c#L985>
segment(&mut ops, vm_offset, code_pages, 0, code_pages, 5);
vm_offset += code_pages;
file_offset += code_pages;
// ROM (R__)
segment(&mut ops, vm_offset, rom_pages, file_offset, rom_pages, 1);
vm_offset += rom_pages;
file_offset += rom_pages;
// RAM (RW_)
segment(
&mut ops,
vm_offset,
ram_pages,
file_offset,
ram_init_pages,
3,
);
// Unix thread segment (184 bytes)
// rip need to be initialized to the start of the program.
// If rsp is zero, XNU will allocate a stack for the program. XNU requires
// programs to have a stack and uses it to pass command line and environment
// arguments. On start rsp will point to the top of the stack. To prevent
// XNU from allocating an otherwise unecessary stack, but still keep the
// variables, we set rsp to the top of the RAM. On start, variables will be
// in [rsp ... end of ram - 8]. The last eight bytes are reserved to store
// rsp in on start.
// This initial 'stack' looks like:
// See <https://github.com/apple/darwin-xnu/blob/master/bsd/kern/kern_exec.c#L3821>
dynasm!(ops
; .dword 0x5 // Segment command
; .dword 184 // Command size
; .dword 0x4 // Flavour
; .dword 42 // Thread state (needs to be 42)
; .qword 0, 0, 0, 0 // r0, r3, r1, r2 (rax, rbx, rcx, rdx)
; .qword 0, 0, 0 // r7, r6, r5 (rdi, rsi, rbp)
; .qword (end_of_ram * PAGE - 8) as i64 // r4 (rsp)
; .qword 0, 0, 0, 0, 0, 0, 0, 0 // r8..r15
; .qword (PAGE + header_size) as i64 // rip
; .qword 0, 0, 0, 0 // rflags, cs, fs, gs
);
// Concatenate all the pages
let mut result = ops.finalize().unwrap()[..].to_owned();
assert_eq!(result.len(), header_size);
assert_eq!(result.len(), CODE_START - PAGE);
result.extend(&self.code);
zero_pad_to_boundary(&mut result, PAGE);
assert_eq!(result.len(), code_pages * PAGE);
result.extend(&self.rom);
zero_pad_to_boundary(&mut result, PAGE);
assert_eq!(result.len(), (code_pages + rom_pages) * PAGE);
result.extend(&self.ram);
zero_pad_to_boundary(&mut result, PAGE);
assert_eq!(
result.len(),
(code_pages + rom_pages + ram_init_pages) * PAGE
);
result
}
}
fn zero_pad_to_boundary(vec: &mut Vec<u8>, block_size: usize) {
let trailing = vec.len() % block_size;
if trailing > 0 {
let padding = block_size - trailing;
vec.extend(std::iter::repeat(0_u8).take(padding));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.