text stringlengths 8 4.13M |
|---|
#[cfg(feature = "nalgebra_math")]
/// Only if nalgebra_math feature is enabled
pub use crate::math::nalgebra::*;
#[cfg(feature = "nalgebra_glm_math")]
/// Only if nalgebra_math feature is enabled
pub use crate::math::nalgebra_glm::*;
#[cfg(feature = "native_math")]
/// Only if native_math feature is enabled
pub use crate::math::native::*;
#[cfg(feature = "nalgebra")]
pub use crate::math::nalgebra_common::*;
pub use crate::traits::extra::F32Compat;
pub use crate::traits::required::SliceExt;
pub use crate::hierarchy::SceneGraph;
pub use crate::components::{DirtyTransform, TransformRoot};
// re-export
pub use shipyard_hierarchy::*;
|
#[doc = "Reader of register MEMRMP"]
pub type R = crate::R<u32, super::MEMRMP>;
#[doc = "Writer for register MEMRMP"]
pub type W = crate::W<u32, super::MEMRMP>;
#[doc = "Register MEMRMP `reset()`'s with value 0"]
impl crate::ResetValue for super::MEMRMP {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `MEM_BOOT`"]
pub type MEM_BOOT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MEM_BOOT`"]
pub struct MEM_BOOT_W<'a> {
w: &'a mut W,
}
impl<'a> MEM_BOOT_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 `SWP_FMC`"]
pub type SWP_FMC_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SWP_FMC`"]
pub struct SWP_FMC_W<'a> {
w: &'a mut W,
}
impl<'a> SWP_FMC_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);
self.w
}
}
impl R {
#[doc = "Bit 0 - Memory boot mapping"]
#[inline(always)]
pub fn mem_boot(&self) -> MEM_BOOT_R {
MEM_BOOT_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 10:11 - FMC memory mapping swap"]
#[inline(always)]
pub fn swp_fmc(&self) -> SWP_FMC_R {
SWP_FMC_R::new(((self.bits >> 10) & 0x03) as u8)
}
}
impl W {
#[doc = "Bit 0 - Memory boot mapping"]
#[inline(always)]
pub fn mem_boot(&mut self) -> MEM_BOOT_W {
MEM_BOOT_W { w: self }
}
#[doc = "Bits 10:11 - FMC memory mapping swap"]
#[inline(always)]
pub fn swp_fmc(&mut self) -> SWP_FMC_W {
SWP_FMC_W { w: self }
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[inline(always)]
pub unsafe fn syscall0(n: usize) -> usize {
let ret: usize;
llvm_asm!("syscall" : "={rax}"(ret)
: "{rax}"(n)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall1(n: usize, a1: usize) -> usize {
let ret: usize;
llvm_asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall2(n: usize, a1: usize, a2: usize) -> usize {
let ret: usize;
llvm_asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall3(n: usize, a1: usize, a2: usize, a3: usize) -> usize {
let ret: usize;
llvm_asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall4(n: usize, a1: usize, a2: usize, a3: usize,
a4: usize) -> usize {
let ret: usize;
llvm_asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3),
"{r10}"(a4)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall5(n: usize, a1: usize, a2: usize, a3: usize,
a4: usize, a5: usize) -> usize {
let ret: usize;
llvm_asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3),
"{r10}"(a4), "{r8}"(a5)
: "rcx", "r11", "memory"
: "volatile");
ret
}
#[inline(always)]
pub unsafe fn syscall6(n: usize, a1: usize, a2: usize, a3: usize,
a4: usize, a5: usize, a6: usize) -> usize {
let ret: usize;
llvm_asm!("syscall" : "={rax}"(ret)
: "{rax}"(n), "{rdi}"(a1), "{rsi}"(a2), "{rdx}"(a3),
"{r10}"(a4), "{r8}"(a5), "{r9}"(a6)
: "rcx", "r11", "memory"
: "volatile");
ret
}
pub fn KLoadBinary(_fileName: &String, _envs: &Vec<String>, _args: &Vec<String>) {} |
pub mod api_key;
pub mod error;
pub mod header;
pub mod record;
use rskafka_wire_format::error::ParseError;
use rskafka_wire_format::prelude::*;
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct BrokerId(pub(crate) i32);
impl WireFormatParse for BrokerId {
fn parse(input: &[u8]) -> IResult<&[u8], Self, ParseError> {
let (input, v) = i32::parse(input)?;
Ok((input, BrokerId(v)))
}
}
impl std::fmt::Display for BrokerId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::{Error, ResultExt};
use fidl::endpoints::{create_endpoints, ClientEnd};
use fidl_fuchsia_mediaplayer::TimelineFunction;
use fidl_fuchsia_mediasession::{
ControllerControlHandle, ControllerEvent, ControllerMarker, ControllerRegistryEvent,
ControllerRegistryEventStream, ControllerRegistryMarker, ControllerRegistryProxy,
ControllerRequest, ControllerRequestStream, PlaybackState, PlaybackStatus, PublisherMarker,
PublisherProxy, RepeatMode,
};
use fuchsia_app as app;
use fuchsia_async as fasync;
use fuchsia_zircon as zx;
use futures::stream::{FusedStream, TryStreamExt};
use zx::AsHandleRef;
const MEDIASESSION_URL: &str = "fuchsia-pkg://fuchsia.com/mediasession#meta/mediasession.cmx";
fn default_playback_status() -> PlaybackStatus {
PlaybackStatus {
duration: Some(100),
playback_state: Some(PlaybackState::Playing),
playback_function: Some(TimelineFunction {
subject_time: 0,
reference_time: 0,
subject_delta: 1,
reference_delta: 1,
}),
repeat_mode: Some(RepeatMode::Off),
shuffle_on: Some(false),
has_next_item: Some(true),
has_prev_item: Some(false),
error: None,
}
}
struct TestSession {
request_stream: ControllerRequestStream,
control_handle: ControllerControlHandle,
client_end: ClientEnd<ControllerMarker>,
}
impl TestSession {
fn new() -> Result<Self, Error> {
let (client_end, server_end) =
create_endpoints::<ControllerMarker>().expect("Fidl endpoints.");
let (request_stream, control_handle) = server_end
.into_stream_and_control_handle()
.context("Unpacking Controller server end.")?;
Ok(Self { request_stream, control_handle, client_end })
}
}
struct TestService {
// This needs to stay alive to keep the service running.
#[allow(unused)]
app: app::client::App,
publisher: PublisherProxy,
controller_registry: ControllerRegistryProxy,
active_session_changes: ControllerRegistryEventStream,
}
impl TestService {
fn new() -> Result<Self, Error> {
let launcher = app::client::Launcher::new().context("Creating launcher.")?;
let mediasession = launcher
.launch(String::from(MEDIASESSION_URL), None)
.context("Launching mediasession.")?;
let publisher =
mediasession.connect_to_service(PublisherMarker).context("Connecting to Publisher.")?;
let controller_registry = mediasession
.connect_to_service(ControllerRegistryMarker)
.context("Connecting to ControllerRegistry.")?;
let active_session_changes = controller_registry.take_event_stream();
Ok(Self { app: mediasession, publisher, controller_registry, active_session_changes })
}
async fn expect_active_session(&mut self, expected: Option<zx::Koid>) {
assert!(!self.active_session_changes.is_terminated());
let ControllerRegistryEvent::OnActiveSession { active_session: actual } =
await!(self.active_session_changes.try_next())
.expect("Reported active session.")
.expect("Active session stream");
let actual = actual
.session_id
.map(|session_id| session_id.as_handle_ref().get_koid().expect("Handle actual KOID"));
assert_eq!(actual, expected);
}
}
#[fasync::run_singlethreaded]
#[test]
async fn service_reports_no_active_session() {
let mut test_service = TestService::new().expect("Test service.");
await!(test_service.expect_active_session(None));
}
#[fasync::run_singlethreaded]
#[test]
async fn service_routes_controls() {
let test_service = TestService::new().expect("Test service.");
// Creates a new session and publishes it. Returns the proxy through Media
// Session service and the request stream on the backend.
let new_session = || {
async {
let test_session = TestSession::new().expect("Test session.");
let session_id = await!(test_service.publisher.publish(test_session.client_end))
.expect("Session id.");
let (client_end, server_end) =
create_endpoints::<ControllerMarker>().expect("Controller endpoints.");
test_service
.controller_registry
.connect_to_controller_by_id(session_id, server_end)
.expect("To connect to session.");
let proxy = client_end.into_proxy().expect("Controller a proxy.");
(proxy, test_session.request_stream)
}
};
let (proxy_a, mut request_stream_a) = await!(new_session());
let (proxy_b, mut request_stream_b) = await!(new_session());
proxy_a.play().expect("To call Play() on Session a.");
proxy_b.pause().expect("To call Pause() on Session b.");
let a_event = await!(request_stream_a.try_next()).expect("Next request from session a.");
let b_event = await!(request_stream_b.try_next()).expect("Next request from session b.");
assert!(match a_event {
Some(ControllerRequest::Play { .. }) => true,
_ => false,
},);
assert!(match b_event {
Some(ControllerRequest::Pause { .. }) => true,
_ => false,
},);
// Ensure the behaviour continues.
proxy_b.play().expect("To call Play() on Session b.");
let b_event = await!(request_stream_b.try_next()).expect("Next request from session b.");
assert!(match b_event {
Some(ControllerRequest::Play { .. }) => true,
_ => false,
},);
}
#[fasync::run_singlethreaded]
#[test]
async fn service_reports_published_active_session() {
let mut test_service = TestService::new().expect("Test service.");
await!(test_service.expect_active_session(None));
let test_session = TestSession::new().expect("Test session.");
let our_session_id =
await!(test_service.publisher.publish(test_session.client_end)).expect("Session id.");
test_session
.control_handle
.send_on_playback_status_changed(default_playback_status())
.expect("To update playback status.");
await!(test_service.expect_active_session(Some(
our_session_id.as_handle_ref().get_koid().expect("Handle expected KOID")
)));
}
#[fasync::run_singlethreaded]
#[test]
async fn service_reports_changed_active_session() {
let mut test_service = TestService::new().expect("Test service.");
await!(test_service.expect_active_session(None));
// Publish sessions.
let session_count: usize = 100;
let mut keep_alive = Vec::new();
for i in 0..session_count {
let test_session = TestSession::new().expect(&format!("Test session {}.", i));
let session_id = await!(test_service.publisher.publish(test_session.client_end))
.expect(&format!("Session {}", i));
test_session
.control_handle
.send_on_playback_status_changed(default_playback_status())
.expect("To update playback status.");
await!(test_service.expect_active_session(Some(
session_id.as_handle_ref().get_koid().expect("Handle expected KOID")
)));
keep_alive.push(test_session.control_handle);
}
}
#[fasync::run_singlethreaded]
#[test]
async fn service_broadcasts_events() {
let mut test_service = TestService::new().expect("Test service.");
await!(test_service.expect_active_session(None));
let test_session = TestSession::new().expect("Test session.");
let session_id = await!(test_service.publisher.publish(test_session.client_end))
.expect(&format!("To publish session."));
// Send a single event.
test_session
.control_handle
.send_on_playback_status_changed(default_playback_status())
.expect("To update playback status.");
// Ensure we wait for the service to accept the session.
await!(test_service.expect_active_session(Some(
session_id.as_handle_ref().get_koid().expect("Handle expected KOID")
)));
// Connect many clients and ensure they all receive the event.
let client_count: usize = 100;
for _ in 0..client_count {
let (client_end, server_end) =
create_endpoints::<ControllerMarker>().expect("Controller endpoints.");
test_service
.controller_registry
.connect_to_controller_by_id(
session_id
.as_handle_ref()
.duplicate(zx::Rights::INSPECT | zx::Rights::TRANSFER)
.expect("Duplicate session handle.")
.into(),
server_end,
)
.expect("To connect to session.");
let mut event_stream =
client_end.into_proxy().expect("Controller proxy").take_event_stream();
let event = await!(event_stream.try_next()).expect("Next Controller event.");
assert_eq!(
event.and_then(|event| match event {
ControllerEvent::OnPlaybackStatusChanged { playback_status } => {
Some(playback_status)
}
_ => None,
}),
Some(default_playback_status())
);
}
}
#[fasync::run_singlethreaded]
#[test]
async fn service_correctly_tracks_session_ids_states_and_lifetimes() {
let test_service = TestService::new().expect("Test service.");
// Publish 100 sessions and have each of them post a playback status.
let count = 100;
let mut test_sessions = Vec::new();
let numbered_playback_status =
|i| PlaybackStatus { duration: Some(i), ..default_playback_status() };
for i in 0..count {
let test_session = TestSession::new().expect(&format!("Test session {}.", i));
let session_id = await!(test_service.publisher.publish(test_session.client_end))
.expect(&format!("To publish test session {}.", i));
test_session
.control_handle
.send_on_playback_status_changed(numbered_playback_status(i as i64))
.expect(&format!("To broadcast playback status {}.", i));
test_sessions.push((session_id, test_session.control_handle));
}
enum Expectation {
SessionIsDropped,
SessionReportsPlaybackStatus(PlaybackStatus),
}
// Set up expectations.
let mut expectations = Vec::new();
let mut control_handles_to_keep_sessions_alive = Vec::new();
for (i, (session_id, control_handle)) in test_sessions.into_iter().enumerate() {
let should_drop = i % 3 == 0;
expectations.push(if should_drop {
control_handle.shutdown();
(Expectation::SessionIsDropped, session_id)
} else {
control_handles_to_keep_sessions_alive.push(control_handle);
(
Expectation::SessionReportsPlaybackStatus(numbered_playback_status(i as i64)),
session_id,
)
});
}
// Check all expectations.
for (expectation, session_id) in expectations.into_iter() {
let (client_end, server_end) =
create_endpoints::<ControllerMarker>().expect("Fidl endpoints.");
test_service
.controller_registry
.connect_to_controller_by_id(
session_id
.as_handle_ref()
.duplicate(zx::Rights::INSPECT | zx::Rights::TRANSFER)
.expect("Duplicate session handle.")
.into(),
server_end,
)
.expect(&format!("To make connection request to session {:?}", session_id));
let mut event_stream = client_end
.into_proxy()
.expect(&format!("Controller proxy for session {:?}.", session_id))
.take_event_stream();
let maybe_event = await!(event_stream.try_next()).expect("Next session event.");
match expectation {
Expectation::SessionIsDropped => {
// If we shutdown the session, this or the next event should be
// None depending on whether our shutdown reached the service
// before this request.
if maybe_event.is_some() {
let next_event = await!(event_stream.try_next()).expect("Next session event.");
assert!(next_event.is_none(), "{:?}", next_event)
}
}
Expectation::SessionReportsPlaybackStatus(expected) => match maybe_event {
Some(ControllerEvent::OnPlaybackStatusChanged { playback_status: actual }) => {
assert_eq!(actual, expected)
}
other => panic!("Expected a playback status event; got: {:?}", other),
},
}
}
}
|
// Copyright 2012-2014 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.
// Test that destructor on a struct runs successfully after the struct
// is boxed and converted to an object.
#![feature(box_syntax)]
static mut value: usize = 0;
struct Cat {
name : usize,
}
trait Dummy {
fn get(&self) -> usize;
}
impl Dummy for Cat {
fn get(&self) -> usize { self.name }
}
impl Drop for Cat {
fn drop(&mut self) {
unsafe { value = self.name; }
}
}
pub fn main() {
{
let x = box Cat {name: 22};
let nyan: Box<Dummy> = x as Box<Dummy>;
}
unsafe {
assert_eq!(value, 22);
}
}
|
use shipyard::Component;
use wasm_bindgen::JsCast;
use web_sys::{Window, Document, HtmlElement, HtmlCanvasElement, WebGlRenderingContext};
use wasm_bindgen::prelude::*;
use awsm_web::window::get_window_size;
use awsm_web::webgl::{
get_webgl_context_1,
WebGlContextOptions,
};
use std::rc::Rc;
use std::cell::RefCell;
#[derive(Component)]
pub struct Dom {
pub window: Window,
pub document: Document,
pub body: HtmlElement,
pub canvas: HtmlCanvasElement,
header: RefCell<Option<HtmlElement>>
}
impl Dom {
pub fn new() -> Rc<Self> {
let window = web_sys::window().expect_throw("should have a Window");
let document = window.document().expect_throw("should have a Document");
let body = document.body().expect_throw("should have a Body");
let canvas: HtmlCanvasElement = document.get_element_by_id("canvas").unwrap_throw().dyn_into().unwrap_throw();
Rc::new(Self {
window,
document,
body,
canvas,
header: RefCell::new(None)
})
}
pub fn _clear_ui(&self) {
if let Some(header) = self.header.borrow_mut().take() {
self.body.remove_child(&header.unchecked_into()).unwrap();
}
}
pub fn set_header_text(&self, text: &str) {
if self.header.borrow().is_none() {
let header: HtmlElement = self.document.create_element("div").unwrap_throw().dyn_into().unwrap_throw();
header.set_class_name("header");
self.body.append_child(&header).unwrap_throw();
*self.header.borrow_mut() = Some(header);
}
self.header.borrow().as_ref().unwrap_throw().set_text_content(Some(text));
}
pub fn window_size(&self) -> (u32, u32) {
get_window_size(&self.window).unwrap()
}
pub fn create_gl_context(&self) -> WebGlRenderingContext {
//not using any webgl2 features so might as well stick with v1
get_webgl_context_1(&self.canvas, Some(&WebGlContextOptions {
alpha: false,
..WebGlContextOptions::default()
})).unwrap_throw()
}
}
|
use crate::Region;
use game_lib::bevy::{
asset as bevy_asset,
core::{self as bevy_core, Byteable},
prelude::*,
reflect::TypeUuid,
render::{
self as bevy_render,
renderer::{RenderResource, RenderResources},
},
};
#[derive(Clone, Debug, RenderResources, TypeUuid)]
#[uuid = "ffa702fe-f6f0-473c-be92-c48e13eec041"]
pub struct RegionData {
pub tile_data: [RegionTileData; Region::TILES],
}
pub struct RegionBuffer {
pub buffer: Handle<Texture>,
}
impl From<&Region> for RegionData {
fn from(region: &Region) -> Self {
let tile_data: [_; Region::TILES] =
array_init::from_iter(Region::BOUNDS.iter_positions().map(|position| {
let tile = region.get(position).unwrap();
let atlas_index = tile.map(|tile| tile.index().0.into()).unwrap_or(-1);
RegionTileData {
tile_color: Color::WHITE.into(),
atlas_index,
padding: Default::default(),
}
}))
.unwrap();
RegionData {
tile_data,
}
}
}
impl From<&mut Region> for RegionData {
fn from(region: &mut Region) -> Self {
RegionData::from(&*region)
}
}
#[derive(Clone, Copy, Debug, Default, RenderResource, TypeUuid)]
#[uuid = "fe1239e5-9e5e-4f1e-a485-6eedc0cb5968"]
#[repr(C)]
pub struct RegionTileData {
pub tile_color: Vec4,
pub atlas_index: i32,
padding: [i32; 3],
}
unsafe impl Byteable for RegionTileData {}
|
// 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.
#[macro_use]
pub mod testing;
mod banjo_library;
mod cc_prebuilt_library;
mod cc_source_library;
mod common;
mod dart_library;
mod device_profile;
mod documentation;
mod fidl_library;
mod host_tool;
mod json;
mod loadable_module;
mod manifest;
mod sysroot;
pub use crate::banjo_library::*;
pub use crate::cc_prebuilt_library::*;
pub use crate::cc_source_library::*;
pub use crate::common::*;
pub use crate::dart_library::*;
pub use crate::device_profile::*;
pub use crate::documentation::*;
pub use crate::fidl_library::*;
pub use crate::host_tool::*;
pub use crate::json::JsonObject;
pub use crate::loadable_module::*;
pub use crate::manifest::*;
pub use crate::sysroot::*;
|
// use std::{path::Path, fs::File, io::BufReader};
// use mp4::{Mp4Reader, Mp4Box, Result};
// #[derive(Debug, Clone, PartialEq, Default)]
// pub struct Box {
// pub name: String,
// pub size: u64,
// pub summary: String,
// pub indent: u32,
// }
// pub fn get_boxes(file: File) -> Result<Vec<Box>> {
// let size = file.metadata()?.len();
// let reader = BufReader::new(file);
// let mp4 = mp4::Mp4Reader::read_header(reader, size)?;
// // collect known boxes
// let mut boxes = vec![
// build_box(&mp4.ftyp),
// build_box(&mp4.moov),
// build_box(&mp4.moov.mvhd),
// ];
// if let Some(ref mvex) = &mp4.moov.mvex {
// boxes.push(build_box(mvex));
// if let Some(mehd) = &mvex.mehd {
// boxes.push(build_box(mehd));
// }
// boxes.push(build_box(&mvex.trex));
// }
// // trak.
// for track in mp4.tracks().values() {
// boxes.push(build_box(&track.trak));
// boxes.push(build_box(&track.trak.tkhd));
// if let Some(ref edts) = track.trak.edts {
// boxes.push(build_box(edts));
// if let Some(ref elst) = edts.elst {
// boxes.push(build_box(elst));
// }
// }
// // trak.mdia
// let mdia = &track.trak.mdia;
// boxes.push(build_box(mdia));
// boxes.push(build_box(&mdia.mdhd));
// boxes.push(build_box(&mdia.hdlr));
// boxes.push(build_box(&track.trak.mdia.minf));
// // trak.mdia.minf
// let minf = &track.trak.mdia.minf;
// if let Some(ref vmhd) = &minf.vmhd {
// boxes.push(build_box(vmhd));
// }
// if let Some(ref smhd) = &minf.smhd {
// boxes.push(build_box(smhd));
// }
// // trak.mdia.minf.stbl
// let stbl = &track.trak.mdia.minf.stbl;
// boxes.push(build_box(stbl));
// boxes.push(build_box(&stbl.stsd));
// if let Some(ref avc1) = &stbl.stsd.avc1 {
// boxes.push(build_box(avc1));
// }
// if let Some(ref hev1) = &stbl.stsd.hev1 {
// boxes.push(build_box(hev1));
// }
// if let Some(ref mp4a) = &stbl.stsd.mp4a {
// boxes.push(build_box(mp4a));
// }
// boxes.push(build_box(&stbl.stts));
// if let Some(ref ctts) = &stbl.ctts {
// boxes.push(build_box(ctts));
// }
// if let Some(ref stss) = &stbl.stss {
// boxes.push(build_box(stss));
// }
// boxes.push(build_box(&stbl.stsc));
// boxes.push(build_box(&stbl.stsz));
// if let Some(ref stco) = &stbl.stco {
// boxes.push(build_box(stco));
// }
// if let Some(ref co64) = &stbl.co64 {
// boxes.push(build_box(co64));
// }
// }
// // If fragmented, add moof boxes.
// for moof in mp4.moofs.iter() {
// boxes.push(build_box(moof));
// boxes.push(build_box(&moof.mfhd));
// for traf in moof.trafs.iter() {
// boxes.push(build_box(traf));
// boxes.push(build_box(&traf.tfhd));
// if let Some(ref trun) = &traf.trun {
// boxes.push(build_box(trun));
// }
// }
// }
// Ok(boxes)
// }
// pub fn build_box<M: Mp4Box + std::fmt::Debug>(m: &M) -> Box {
// Box {
// name: m.box_type().to_string(),
// size: m.box_size(),
// summary: m.summary().unwrap(),
// indent: 0,
// }
// }
// pub fn get_mp4_by_path (filename: &str) -> Mp4Reader<BufReader<File>> {
// let f = File::open(filename).unwrap();
// let size = f.metadata().unwrap().len();
// let reader = BufReader::new(f);
// mp4::Mp4Reader::read_header(reader, size).unwrap()
// }
use std::fmt;
#[path="./ftyp/index.rs"]
mod ftmp;
use ftmp::*;
#[path="./moov/index.rs"]
mod moov;
use moov::*;
pub struct BoxHeader {
pub box_size: Vec<u8>, // 4
pub box_type: Vec<u8>, // 4
pub large_size: Vec<u8>, // box_size === 1 ? 8 : 0
}
pub fn vec_to_number(data: Vec<u8>) -> usize {
let len = data.len() as u32;
let mut result = 0;
let base = 256_usize;
for (index, num) in data.iter().enumerate() {
result += base.pow(len - index as u32 - 1) * (*num) as usize;
}
result
}
pub fn read_info(data: Vec<u8>) {
let ftyp = read_ftyp(&data);
let offset = ftyp.ftyp_header.get_box_size();
let moov = read_moov(&data, offset);
} |
//! Utilities used during the initial setup
use crate::Pool;
use actix_web::middleware::Logger;
use blake2::{Blake2b, Digest};
use diesel::{
r2d2::{self, ConnectionManager},
sqlite::SqliteConnection,
};
use std::{env, path::PathBuf};
#[cfg(not(feature = "dev"))]
use dirs;
#[cfg(feature = "dev")]
use dotenv;
#[cfg(feature = "dev")]
use std::str::FromStr;
#[cfg(not(feature = "dev"))]
use std::{
fs,
io::{self, BufRead},
process,
};
#[cfg(not(feature = "dev"))]
use toml;
/// Returns a path to the directory storing application data
#[cfg(not(feature = "dev"))]
pub fn get_data_dir() -> PathBuf {
let mut dir = dirs::home_dir().expect("Can't find home directory.");
dir.push(".filite");
dir
}
/// Returns a path to the configuration file
#[cfg(not(feature = "dev"))]
fn get_config_path() -> PathBuf {
let mut path = get_data_dir();
path.push("config.toml");
path
}
/// Returns a path to the bearer token hash
#[cfg(not(feature = "dev"))]
pub fn get_password_path() -> PathBuf {
let mut path = get_data_dir();
path.push("passwd");
path
}
/// Returns the BLAKE2b digest of the input string
pub fn hash<T: AsRef<[u8]>>(input: T) -> Vec<u8> {
let mut hasher = Blake2b::new();
hasher.input(input);
hasher.result().to_vec()
}
/// Returns an environment variable and panic if it isn't found
#[cfg(feature = "dev")]
#[macro_export]
macro_rules! get_env {
($k:literal) => {
std::env::var($k).expect(&format!("Can't find {} environment variable", $k));
};
}
/// Returns a parsed environment variable and panic if it isn't found or is not parsable
#[cfg(feature = "dev")]
macro_rules! parse_env {
($k:literal) => {
get_env!($k).parse().expect(&format!("Invalid {}", $k))
};
}
/// Application configuration
#[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(not(feature = "dev"), serde(default))]
pub struct Config {
/// Port to listen on
pub port: u16,
/// SQLite database connection url
pub database_url: String,
/// SQLite database connection pool size
pub pool_size: u32,
/// Directory where to store static files
pub files_dir: PathBuf,
/// Maximum allowed file size
pub max_filesize: usize,
}
#[cfg(not(feature = "dev"))]
impl Default for Config {
fn default() -> Self {
let port = 8080;
let database_url = {
let mut path = get_data_dir();
path.push("database.db");
path.to_str()
.expect("Can't convert database path to string")
.to_owned()
};
let pool_size = std::cmp::max(1, num_cpus::get() as u32 / 2);
let files_dir = {
let mut path = get_data_dir();
path.push("files");
path
};
let max_filesize = 10_000_000;
Config {
port,
database_url,
pool_size,
files_dir,
max_filesize,
}
}
}
impl Config {
/// Deserialize the config file
#[cfg(not(feature = "dev"))]
pub fn read_file() -> Result<Self, &'static str> {
let path = get_config_path();
let contents = if let Ok(contents) = fs::read_to_string(&path) {
contents
} else {
return Err("Can't read config file.");
};
let result = toml::from_str(&contents);
if result.is_err() {
return Err("Invalid config file.");
}
let mut result: Config = result.unwrap();
if result.files_dir.is_absolute() {
if fs::create_dir_all(&result.files_dir).is_err() {
return Err("Can't create files_dir.");
}
result.files_dir = match result.files_dir.canonicalize() {
Ok(path) => path,
Err(_) => return Err("Invalid files_dir."),
}
} else {
let mut data_dir = get_data_dir();
data_dir.push(&result.files_dir);
if fs::create_dir_all(&data_dir).is_err() {
return Err("Can't create files_dir.");
}
result.files_dir = match data_dir.canonicalize() {
Ok(path) => path,
Err(_) => return Err("Invalid files_dir."),
}
}
Ok(result)
}
/// Serialize the config file
#[cfg(not(feature = "dev"))]
pub fn write_file(&self) -> Result<(), &'static str> {
let path = get_config_path();
let contents = toml::to_string(&self).expect("Can't serialize config.");
match fs::write(&path, &contents) {
Ok(_) => Ok(()),
Err(_) => Err("Can't write config file."),
}
}
/// Creates a config from environment variables
#[cfg(feature = "dev")]
pub fn debug() -> Self {
dotenv::dotenv().ok();
let port = parse_env!("PORT");
let database_url = get_env!("DATABASE_URL");
let pool_size = parse_env!("POOL_SIZE");
let files_dir = {
let files_dir = get_env!("FILES_DIR");
let path = PathBuf::from_str(&files_dir).expect("Can't convert files dir to path");
if path.is_absolute() {
path.canonicalize().expect("Invalid FILES_DIR")
} else {
let cargo_manifest_dir = env!("CARGO_MANIFEST_DIR");
let mut cargo_manifest_dir = PathBuf::from_str(cargo_manifest_dir)
.expect("Can't convert cargo manifest dir to path");
cargo_manifest_dir.push(&path);
cargo_manifest_dir
.canonicalize()
.expect("Invalid FILES_DIR")
}
};
let max_filesize = parse_env!("MAX_FILESIZE");
Config {
port,
database_url,
pool_size,
files_dir,
max_filesize,
}
}
}
/// Creates a SQLite database connection pool
pub fn create_pool(url: &str, size: u32) -> Pool {
let manager = ConnectionManager::<SqliteConnection>::new(url);
r2d2::Pool::builder()
.max_size(size)
.build(manager)
.expect("Can't create pool")
}
/// Initializes the logger
pub fn init_logger() {
if cfg!(feature = "dev") && env::var_os("RUST_LOG").is_none() {
env::set_var("RUST_LOG", "actix_web=debug");
} else if !cfg!(feature = "dev") {
env::set_var("RUST_LOG", "actix_web=info");
}
env_logger::init();
}
/// Returns the logger middleware
pub fn logger_middleware() -> Logger {
#[cfg(feature = "dev")]
{
dotenv::dotenv().ok();
if let Ok(format) = env::var("LOG_FORMAT") {
Logger::new(&format)
} else {
Logger::default()
}
}
#[cfg(not(feature = "dev"))]
{
Logger::default()
}
}
/// Performs the initial setup
#[cfg(not(feature = "dev"))]
pub fn init() -> Config {
let data_dir = get_data_dir();
if !data_dir.exists() {
eprintln!("Generating config file...");
fs::create_dir_all(&data_dir)
.unwrap_or_else(|e| eprintln!("Can't create config directory: {}.", e));
Config::default().write_file().unwrap_or_else(|e| {
eprintln!("{}", e);
process::exit(1);
});
let stdin = io::stdin();
let mut stdin = stdin.lock();
eprintln!("Enter the password to use:");
let mut password = String::new();
stdin.read_line(&mut password).unwrap_or_else(|e| {
eprintln!("Can't read password: {}", e);
process::exit(1);
});
password = password.replace("\r", "");
password = password.replace("\n", "");
let password_hash = hash(&password);
let password_path = get_password_path();
fs::write(&password_path, password_hash.as_slice()).unwrap_or_else(|e| {
eprintln!("Can't write password: {}", e);
process::exit(1);
});
let mut config_path = data_dir;
config_path.push("config.toml");
eprintln!(
"Almost ready. To get started, edit the config file at {} and restart.",
&config_path.to_str().unwrap(),
);
process::exit(0);
}
Config::read_file().unwrap_or_else(|e| {
eprintln!("{}", e);
process::exit(1);
})
}
|
use crate::event::{LogEvent, Value};
use bytes::{Bytes, BytesMut};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum MergeStrategy {
Discard,
Sum,
Max,
Min,
Array,
Concat,
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct DiscardMerger {
v: Value,
}
impl DiscardMerger {
fn new(v: Value) -> Self {
Self { v }
}
}
impl ReduceValueMerger for DiscardMerger {
fn add(&mut self, _v: Value) -> Result<(), String> {
Ok(())
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
v.insert(k, self.v);
Ok(())
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct ConcatMerger {
v: BytesMut,
}
impl ConcatMerger {
fn new(v: Bytes) -> Self {
Self { v: v.into() }
}
}
impl ReduceValueMerger for ConcatMerger {
fn add(&mut self, v: Value) -> Result<(), String> {
if let Value::Bytes(b) = v {
self.v.extend(&[b' ']);
self.v.extend_from_slice(&b);
Ok(())
} else {
Err(format!(
"expected string value, found: '{}'",
v.to_string_lossy()
))
}
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
v.insert(k, Value::Bytes(self.v.into()));
Ok(())
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct ConcatArrayMerger {
v: Vec<Value>,
}
impl ConcatArrayMerger {
fn new(v: Vec<Value>) -> Self {
Self { v }
}
}
impl ReduceValueMerger for ConcatArrayMerger {
fn add(&mut self, v: Value) -> Result<(), String> {
if let Value::Array(a) = v {
self.v.extend_from_slice(&a);
} else {
self.v.push(v);
}
Ok(())
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
v.insert(k, Value::Array(self.v));
Ok(())
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct ArrayMerger {
v: Vec<Value>,
}
impl ArrayMerger {
fn new(v: Value) -> Self {
Self { v: vec![v] }
}
}
impl ReduceValueMerger for ArrayMerger {
fn add(&mut self, v: Value) -> Result<(), String> {
self.v.push(v);
Ok(())
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
v.insert(k, Value::Array(self.v));
Ok(())
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct TimestampWindowMerger {
started: DateTime<Utc>,
latest: DateTime<Utc>,
}
impl TimestampWindowMerger {
fn new(v: DateTime<Utc>) -> Self {
Self {
started: v,
latest: v,
}
}
}
impl ReduceValueMerger for TimestampWindowMerger {
fn add(&mut self, v: Value) -> Result<(), String> {
if let Value::Timestamp(ts) = v {
self.latest = ts
} else {
return Err(format!(
"expected timestamp value, found: {}",
v.to_string_lossy()
));
}
Ok(())
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
v.insert(format!("{}_end", k), Value::Timestamp(self.latest));
v.insert(k, Value::Timestamp(self.started));
Ok(())
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
enum NumberMergerValue {
Int(i64),
Float(f64),
}
impl From<i64> for NumberMergerValue {
fn from(v: i64) -> Self {
NumberMergerValue::Int(v)
}
}
impl From<f64> for NumberMergerValue {
fn from(v: f64) -> Self {
NumberMergerValue::Float(v)
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct AddNumbersMerger {
v: NumberMergerValue,
}
impl AddNumbersMerger {
fn new(v: NumberMergerValue) -> Self {
Self { v }
}
}
impl ReduceValueMerger for AddNumbersMerger {
fn add(&mut self, v: Value) -> Result<(), String> {
// Try and keep max precision with integer values, but once we've
// received a float downgrade to float precision.
match v {
Value::Integer(i) => match self.v {
NumberMergerValue::Int(j) => self.v = NumberMergerValue::Int(i + j),
NumberMergerValue::Float(j) => self.v = NumberMergerValue::Float(i as f64 + j),
},
Value::Float(f) => match self.v {
NumberMergerValue::Int(j) => self.v = NumberMergerValue::Float(f + j as f64),
NumberMergerValue::Float(j) => self.v = NumberMergerValue::Float(f + j),
},
_ => {
return Err(format!(
"expected numeric value, found: '{}'",
v.to_string_lossy()
));
}
}
Ok(())
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
match self.v {
NumberMergerValue::Float(f) => v.insert(k, Value::Float(f)),
NumberMergerValue::Int(i) => v.insert(k, Value::Integer(i)),
};
Ok(())
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct MaxNumberMerger {
v: NumberMergerValue,
}
impl MaxNumberMerger {
fn new(v: NumberMergerValue) -> Self {
Self { v }
}
}
impl ReduceValueMerger for MaxNumberMerger {
fn add(&mut self, v: Value) -> Result<(), String> {
// Try and keep max precision with integer values, but once we've
// received a float downgrade to float precision.
match v {
Value::Integer(i) => {
match self.v {
NumberMergerValue::Int(i2) => {
if i > i2 {
self.v = NumberMergerValue::Int(i);
}
}
NumberMergerValue::Float(f2) => {
let f = i as f64;
if f > f2 {
self.v = NumberMergerValue::Float(f);
}
}
};
}
Value::Float(f) => {
let f2 = match self.v {
NumberMergerValue::Int(i2) => i2 as f64,
NumberMergerValue::Float(f2) => f2,
};
if f > f2 {
self.v = NumberMergerValue::Float(f);
}
}
_ => {
return Err(format!(
"expected numeric value, found: '{}'",
v.to_string_lossy()
));
}
}
Ok(())
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
match self.v {
NumberMergerValue::Float(f) => v.insert(k, Value::Float(f)),
NumberMergerValue::Int(i) => v.insert(k, Value::Integer(i)),
};
Ok(())
}
}
//------------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct MinNumberMerger {
v: NumberMergerValue,
}
impl MinNumberMerger {
fn new(v: NumberMergerValue) -> Self {
Self { v }
}
}
impl ReduceValueMerger for MinNumberMerger {
fn add(&mut self, v: Value) -> Result<(), String> {
// Try and keep max precision with integer values, but once we've
// received a float downgrade to float precision.
match v {
Value::Integer(i) => {
match self.v {
NumberMergerValue::Int(i2) => {
if i < i2 {
self.v = NumberMergerValue::Int(i);
}
}
NumberMergerValue::Float(f2) => {
let f = i as f64;
if f < f2 {
self.v = NumberMergerValue::Float(f);
}
}
};
}
Value::Float(f) => {
let f2 = match self.v {
NumberMergerValue::Int(i2) => i2 as f64,
NumberMergerValue::Float(f2) => f2,
};
if f < f2 {
self.v = NumberMergerValue::Float(f);
}
}
_ => {
return Err(format!(
"expected numeric value, found: '{}'",
v.to_string_lossy()
));
}
}
Ok(())
}
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String> {
match self.v {
NumberMergerValue::Float(f) => v.insert(k, Value::Float(f)),
NumberMergerValue::Int(i) => v.insert(k, Value::Integer(i)),
};
Ok(())
}
}
//------------------------------------------------------------------------------
pub trait ReduceValueMerger: std::fmt::Debug + Send + Sync {
fn add(&mut self, v: Value) -> Result<(), String>;
fn insert_into(self: Box<Self>, k: String, v: &mut LogEvent) -> Result<(), String>;
}
impl From<Value> for Box<dyn ReduceValueMerger> {
fn from(v: Value) -> Self {
match v {
Value::Integer(i) => Box::new(AddNumbersMerger::new(i.into())),
Value::Float(f) => Box::new(AddNumbersMerger::new(f.into())),
Value::Timestamp(ts) => Box::new(TimestampWindowMerger::new(ts)),
Value::Map(_) => Box::new(DiscardMerger::new(v)),
Value::Null => Box::new(DiscardMerger::new(v)),
Value::Boolean(_) => Box::new(DiscardMerger::new(v)),
Value::Bytes(_) => Box::new(DiscardMerger::new(v)),
Value::Array(_) => Box::new(DiscardMerger::new(v)),
}
}
}
pub fn get_value_merger(v: Value, m: &MergeStrategy) -> Result<Box<dyn ReduceValueMerger>, String> {
match m {
MergeStrategy::Sum => match v {
Value::Integer(i) => Ok(Box::new(AddNumbersMerger::new(i.into()))),
Value::Float(f) => Ok(Box::new(AddNumbersMerger::new(f.into()))),
_ => Err(format!(
"expected number value, found: '{}'",
v.to_string_lossy()
)),
},
MergeStrategy::Max => match v {
Value::Integer(i) => Ok(Box::new(MaxNumberMerger::new(i.into()))),
Value::Float(f) => Ok(Box::new(MaxNumberMerger::new(f.into()))),
_ => Err(format!(
"expected number value, found: '{}'",
v.to_string_lossy()
)),
},
MergeStrategy::Min => match v {
Value::Integer(i) => Ok(Box::new(MinNumberMerger::new(i.into()))),
Value::Float(f) => Ok(Box::new(MinNumberMerger::new(f.into()))),
_ => Err(format!(
"expected number value, found: '{}'",
v.to_string_lossy()
)),
},
MergeStrategy::Concat => match v {
Value::Bytes(b) => Ok(Box::new(ConcatMerger::new(b))),
Value::Array(a) => Ok(Box::new(ConcatArrayMerger::new(a))),
_ => Err(format!(
"expected string or array value, found: '{}'",
v.to_string_lossy()
)),
},
MergeStrategy::Array => Ok(Box::new(ArrayMerger::new(v))),
MergeStrategy::Discard => Ok(Box::new(DiscardMerger::new(v))),
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::Event;
use serde_json::json;
use string_cache::DefaultAtom as Atom;
#[test]
fn initial_values() {
assert!(get_value_merger("foo".into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger("foo".into(), &MergeStrategy::Sum).is_err());
assert!(get_value_merger("foo".into(), &MergeStrategy::Max).is_err());
assert!(get_value_merger("foo".into(), &MergeStrategy::Min).is_err());
assert!(get_value_merger("foo".into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger("foo".into(), &MergeStrategy::Concat).is_ok());
assert!(get_value_merger(42.into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger(42.into(), &MergeStrategy::Sum).is_ok());
assert!(get_value_merger(42.into(), &MergeStrategy::Min).is_ok());
assert!(get_value_merger(42.into(), &MergeStrategy::Max).is_ok());
assert!(get_value_merger(42.into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger(42.into(), &MergeStrategy::Concat).is_err());
assert!(get_value_merger(4.2.into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger(4.2.into(), &MergeStrategy::Sum).is_ok());
assert!(get_value_merger(4.2.into(), &MergeStrategy::Min).is_ok());
assert!(get_value_merger(4.2.into(), &MergeStrategy::Max).is_ok());
assert!(get_value_merger(4.2.into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger(4.2.into(), &MergeStrategy::Concat).is_err());
assert!(get_value_merger(true.into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger(true.into(), &MergeStrategy::Sum).is_err());
assert!(get_value_merger(true.into(), &MergeStrategy::Max).is_err());
assert!(get_value_merger(true.into(), &MergeStrategy::Min).is_err());
assert!(get_value_merger(true.into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger(true.into(), &MergeStrategy::Concat).is_err());
assert!(get_value_merger(Utc::now().into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger(Utc::now().into(), &MergeStrategy::Sum).is_err());
assert!(get_value_merger(Utc::now().into(), &MergeStrategy::Max).is_err());
assert!(get_value_merger(Utc::now().into(), &MergeStrategy::Min).is_err());
assert!(get_value_merger(Utc::now().into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger(Utc::now().into(), &MergeStrategy::Concat).is_err());
assert!(get_value_merger(json!([]).into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger(json!([]).into(), &MergeStrategy::Sum).is_err());
assert!(get_value_merger(json!([]).into(), &MergeStrategy::Max).is_err());
assert!(get_value_merger(json!([]).into(), &MergeStrategy::Min).is_err());
assert!(get_value_merger(json!([]).into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger(json!([]).into(), &MergeStrategy::Concat).is_ok());
assert!(get_value_merger(json!({}).into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger(json!({}).into(), &MergeStrategy::Sum).is_err());
assert!(get_value_merger(json!({}).into(), &MergeStrategy::Max).is_err());
assert!(get_value_merger(json!({}).into(), &MergeStrategy::Min).is_err());
assert!(get_value_merger(json!({}).into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger(json!({}).into(), &MergeStrategy::Concat).is_err());
assert!(get_value_merger(json!(null).into(), &MergeStrategy::Discard).is_ok());
assert!(get_value_merger(json!(null).into(), &MergeStrategy::Sum).is_err());
assert!(get_value_merger(json!(null).into(), &MergeStrategy::Max).is_err());
assert!(get_value_merger(json!(null).into(), &MergeStrategy::Min).is_err());
assert!(get_value_merger(json!(null).into(), &MergeStrategy::Array).is_ok());
assert!(get_value_merger(json!(null).into(), &MergeStrategy::Concat).is_err());
}
#[test]
fn merging_values() {
assert_eq!(
merge("foo".into(), "bar".into(), &MergeStrategy::Discard),
Ok("foo".into())
);
assert_eq!(
merge("foo".into(), "bar".into(), &MergeStrategy::Array),
Ok(json!(["foo", "bar"]).into())
);
assert_eq!(
merge("foo".into(), "bar".into(), &MergeStrategy::Concat),
Ok("foo bar".into())
);
assert!(merge("foo".into(), 42.into(), &MergeStrategy::Concat).is_err());
assert!(merge("foo".into(), 4.2.into(), &MergeStrategy::Concat).is_err());
assert!(merge("foo".into(), true.into(), &MergeStrategy::Concat).is_err());
assert!(merge("foo".into(), Utc::now().into(), &MergeStrategy::Concat).is_err());
assert!(merge("foo".into(), json!({}).into(), &MergeStrategy::Concat).is_err());
assert!(merge("foo".into(), json!([]).into(), &MergeStrategy::Concat).is_err());
assert!(merge("foo".into(), json!(null).into(), &MergeStrategy::Concat).is_err());
assert_eq!(
merge(21.into(), 21.into(), &MergeStrategy::Sum),
Ok(42.into())
);
assert_eq!(
merge(41.into(), 42.into(), &MergeStrategy::Max),
Ok(42.into())
);
assert_eq!(
merge(42.into(), 41.into(), &MergeStrategy::Max),
Ok(42.into())
);
assert_eq!(
merge(42.into(), 43.into(), &MergeStrategy::Min),
Ok(42.into())
);
assert_eq!(
merge(43.into(), 42.into(), &MergeStrategy::Min),
Ok(42.into())
);
assert_eq!(
merge(2.1.into(), 2.1.into(), &MergeStrategy::Sum),
Ok(4.2.into())
);
assert_eq!(
merge(4.1.into(), 4.2.into(), &MergeStrategy::Max),
Ok(4.2.into())
);
assert_eq!(
merge(4.2.into(), 4.1.into(), &MergeStrategy::Max),
Ok(4.2.into())
);
assert_eq!(
merge(4.2.into(), 4.3.into(), &MergeStrategy::Min),
Ok(4.2.into())
);
assert_eq!(
merge(4.3.into(), 4.2.into(), &MergeStrategy::Min),
Ok(4.2.into())
);
assert_eq!(
merge(json!([4]).into(), json!([2]).into(), &MergeStrategy::Concat),
Ok(json!([4, 2]).into())
);
assert_eq!(
merge(json!([]).into(), 42.into(), &MergeStrategy::Concat),
Ok(json!([42]).into())
);
}
fn merge(initial: Value, additional: Value, strategy: &MergeStrategy) -> Result<Value, String> {
let mut merger = get_value_merger(initial, strategy)?;
merger.add(additional)?;
let mut output = Event::new_empty_log();
let mut output = output.as_mut_log();
merger.insert_into("out".into(), &mut output)?;
Ok(output.remove(&Atom::from("out")).unwrap())
}
}
|
use super::super::{Model, Var, EqXY, NeqXY, EqXYC, NeqXYC, EqXC, NeqXC};
use super::{NeqXYCxy};
#[test]
fn neqxycxy_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), -2, 255, "x");
let y = Var::new(m.clone(), 10, 10, "y");
NeqXYCxy::new(m.clone(), x.clone(), y.clone(), -11);
assert_eq!((x.min(), x.max()), (-2, 255));
NeqXYCxy::new(m.clone(), x.clone(), y.clone(), -12);
assert_eq!((x.min(), x.max()), (0, 255));
NeqXYCxy::new(m.clone(), x.clone(), y.clone(), 245);
assert_eq!((x.min(), x.max()), (0, 254));
}
#[test]
fn eqxy_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), 8, 255, "x");
let y = Var::new(m.clone(), -2, 128, "y");
EqXY::new(m.clone(), x.clone(), y.clone());
assert_eq!((x.min(), x.max(), y.min(), y.max()), (8, 128, 8, 128));
}
#[test]
fn eqxyc_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), 8, 255, "x");
let y = Var::new(m.clone(), -2, 128, "y");
EqXYC::new(m.clone(), x.clone(), y.clone(), 2);
assert_eq!((x.min(), x.max(), y.min(), y.max()), (8, 130, 6, 128));
}
#[test]
fn eqxc_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), 8, 255, "x");
EqXC::new(m.clone(), x.clone(), 42);
assert_eq!((x.min(), x.max()), (42, 42));
assert!(x.is_instanciated());
}
#[test]
fn neqxy_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), 8, 255, "x");
let y = Var::new(m.clone(), -2, 128, "y");
NeqXY::new(m.clone(), x.clone(), y.clone());
EqXC::new(m.clone(), x.clone(), 128);
assert_eq!((x.min(), x.max(), y.min(), y.max()), (128, 128, -2, 127));
}
#[test]
fn neqxyc_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), 8, 255, "x");
let y = Var::new(m.clone(), -2, -2, "y");
NeqXYC::new(m.clone(), x.clone(), y.clone(), 257);
assert_eq!((x.min(), x.max(), y.min(), y.max()), (8, 254, -2, -2));
}
#[test]
fn neqxc_does_propagate() {
let m = Model::new();
let x = Var::new(m.clone(), 8, 255, "x");
NeqXC::new(m.clone(), x.clone(), 9);
NeqXC::new(m.clone(), x.clone(), 10);
NeqXC::new(m.clone(), x.clone(), 8);
assert_eq!((x.min(), x.max()), (11, 255));
}
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
use rocket::response::NamedFile;
extern crate diesel;
#[macro_use] extern crate serde_derive;
use rocket_contrib::templates::Template;
use std::path::{Path, PathBuf};
#[derive(Serialize)]
struct TemplateContext {
items: Vec<&'static str>,
}
#[get("/")]
fn index() -> Template {
let context = TemplateContext {
items: vec!["input", "from","backend"]
};
Template::render("index", &context)
}
#[get("/login")]
fn log() -> Template {
let context = TemplateContext {
items: vec!["input", "from","backend"]
};
Template::render("login", &context)
}
#[get("/<file..>")]
fn files(file: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("static/").join(file)).ok()
}
fn rock() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![index, log, files])
.attach(Template::fairing())
}
fn main() {
rock().launch();
}
|
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let n: usize = rd.get();
let s: String = rd.get();
let s: Vec<char> = s.chars().collect();
let total: u64 = 1_000_000_000_0;
if n == 1 {
println!("{}", if s[0] == '0' { total } else { total * 2 });
return;
}
let mut cnt: u64 = 0;
let mut cur: usize = if s[0..2] == ['1', '0'] {
cnt += 1;
2
} else if s[0] == '0' {
cnt += 1;
1
} else {
0
};
while cur + 2 < n {
if s[cur..=(cur + 2)] == ['1', '1', '0'] {
cnt += 1;
cur += 3;
} else {
break;
}
}
if cur + 1 < n && s[cur..=(cur + 1)] == ['1', '1'] {
cur += 2;
cnt += 1;
} else if cur < n && s[cur] == '1' {
cur += 1;
cnt += 1;
}
let ans = if cur == n { total - cnt + 1 } else { 0 };
println!("{}", ans);
}
pub struct ProconReader<R: std::io::Read> {
reader: R,
}
impl<R: std::io::Read> ProconReader<R> {
pub fn new(reader: R) -> Self {
Self { reader }
}
pub fn get<T: std::str::FromStr>(&mut self) -> T {
use std::io::Read;
let buf = self
.reader
.by_ref()
.bytes()
.map(|b| b.unwrap())
.skip_while(|&byte| byte == b' ' || byte == b'\n' || byte == b'\r')
.take_while(|&byte| byte != b' ' && byte != b'\n' && byte != b'\r')
.collect::<Vec<_>>();
std::str::from_utf8(&buf)
.unwrap()
.parse()
.ok()
.expect("Parse Error.")
}
}
|
use std::ops::Range;
use std::str::FromStr;
use firefly_diagnostics::{ByteOffset, SourceIndex, SourceSpan};
use firefly_intern::Symbol;
use firefly_number::{Float, FloatError, Integer};
use firefly_parser::{Scanner, Source};
use crate::util::escape_stm::{EscapeStm, EscapeStmAction};
use super::errors::LexicalError;
use super::token::*;
use super::Lexed;
macro_rules! pop {
($lex:ident) => {{
$lex.skip();
}};
($lex:ident, $code:expr) => {{
$lex.skip();
$code
}};
}
macro_rules! pop2 {
($lex:ident) => {{
$lex.skip();
$lex.skip();
}};
($lex:ident, $code:expr) => {{
$lex.skip();
$lex.skip();
$code
}};
}
macro_rules! pop3 {
($lex:ident) => {{
$lex.skip();
$lex.skip();
$lex.skip()
}};
($lex:ident, $code:expr) => {{
$lex.skip();
$lex.skip();
$lex.skip();
$code
}};
}
/// The lexer that is used to perform lexical analysis on the Erlang grammar. The lexer implements
/// the `Iterator` trait, so in order to retrieve the tokens, you simply have to iterate over it.
///
/// # Errors
///
/// Because the lexer is implemented as an iterator over tokens, this means that you can continue
/// to get tokens even if a lexical error occurs. The lexer will attempt to recover from an error
/// by injecting tokens it expects.
///
/// If an error is unrecoverable, the lexer will continue to produce tokens, but there is no
/// guarantee that parsing them will produce meaningful results, it is primarily to assist in
/// gathering as many errors as possible.
pub struct Lexer<S> {
/// The scanner produces a sequence of chars + location, and can be controlled
/// The location produces is a SourceIndex
scanner: Scanner<S>,
/// Escape sequence state machine.
escape: EscapeStm<SourceIndex>,
/// The most recent token to be lexed.
/// At the start and end, this should be Token::EOF
token: Token,
/// The position in the input where the current token starts
/// At the start this will be the byte index of the beginning of the input
token_start: SourceIndex,
/// The position in the input where the current token ends
/// At the start this will be the byte index of the beginning of the input
token_end: SourceIndex,
/// When we have reached true EOF, this gets set to true, and the only token
/// produced after that point is Token::EOF, or None, depending on how you are
/// consuming the lexer
eof: bool,
}
impl<S> Lexer<S>
where
S: Source,
{
/// Produces an instance of the lexer with the lexical analysis to be performed on the `input`
/// string. Note that no lexical analysis occurs until the lexer has been iterated over.
pub fn new(scanner: Scanner<S>) -> Self {
let start = scanner.start();
let mut lexer = Lexer {
scanner,
escape: EscapeStm::new(),
token: Token::EOF,
token_start: start + ByteOffset(0),
token_end: start + ByteOffset(0),
eof: false,
};
lexer.advance();
lexer
}
pub fn lex(&mut self) -> Option<<Self as Iterator>::Item> {
if self.eof && self.token == Token::EOF {
return None;
}
let token = std::mem::replace(&mut self.token, Token::EOF);
let result = if let Token::Error(err) = token {
Some(Err(err))
} else {
Some(Ok(LexicalToken(
self.token_start.clone(),
token,
self.token_end.clone(),
)))
};
self.advance();
result
}
fn advance(&mut self) {
self.advance_start();
self.token = self.tokenize();
}
#[inline]
fn advance_start(&mut self) {
let mut position: SourceIndex;
loop {
let (pos, c) = self.scanner.read();
position = pos;
if c == '\0' {
self.eof = true;
return;
}
if c.is_whitespace() {
self.scanner.advance();
continue;
}
break;
}
self.token_start = position;
}
#[inline]
fn pop(&mut self) -> char {
let (pos, c) = self.scanner.pop();
self.token_end = pos + ByteOffset::from_char_len(c);
c
}
#[inline]
fn peek(&mut self) -> char {
let (_, c) = self.scanner.peek();
c
}
#[inline]
fn peek_next(&mut self) -> char {
let (_, c) = self.scanner.peek_next();
c
}
#[inline]
fn read(&mut self) -> char {
let (_, c) = self.scanner.read();
c
}
#[inline]
fn index(&mut self) -> SourceIndex {
self.scanner.read().0
}
#[inline]
fn skip(&mut self) {
self.pop();
}
/// Get the span for the current token in `Source`.
#[inline]
pub fn span(&self) -> SourceSpan {
SourceSpan::new(self.token_start, self.token_end)
}
/// Get a string slice of the current token.
#[inline]
fn slice(&self) -> &str {
self.scanner.slice(self.span())
}
#[inline]
fn slice_span(&self, span: impl Into<Range<usize>>) -> &str {
self.scanner.slice(span)
}
#[inline]
fn skip_whitespace(&mut self) {
let mut c: char;
loop {
c = self.read();
if !c.is_whitespace() {
break;
}
self.skip();
}
}
fn tokenize(&mut self) -> Token {
let c = self.read();
if c == '%' {
self.skip();
return self.lex_comment();
}
if c == '\0' {
self.eof = true;
return Token::EOF;
}
if c.is_whitespace() {
self.skip_whitespace();
}
match self.read() {
',' => pop!(self, Token::Comma),
';' => pop!(self, Token::Semicolon),
'_' => self.lex_identifier(),
'0'..='9' => self.lex_number(),
'a'..='z' => self.lex_bare_atom(),
'A'..='Z' => self.lex_identifier(),
'#' => pop!(self, Token::Pound),
'*' => pop!(self, Token::Star),
'!' => pop!(self, Token::Bang),
'[' => pop!(self, Token::LBracket),
']' => pop!(self, Token::RBracket),
'(' => pop!(self, Token::LParen),
')' => pop!(self, Token::RParen),
'{' => pop!(self, Token::LBrace),
'}' => pop!(self, Token::RBrace),
'?' => match self.peek() {
'?' => pop2!(self, Token::DoubleQuestion),
_ => pop!(self, Token::Question),
},
'-' => match self.peek() {
'-' => pop2!(self, Token::MinusMinus),
'>' => pop2!(self, Token::RightStab),
_ => pop!(self, Token::Minus),
},
'$' => {
self.skip();
if self.read() == '\\' {
return match self.lex_escape_sequence() {
Ok(num) => match std::char::from_u32(num as u32) {
Some(c) => Token::Char(c),
None => Token::Integer((num as i64).into()),
},
Err(err) => Token::Error(err),
};
}
Token::Char(self.pop())
}
'"' => self.lex_string(),
'\'' => match self.lex_string() {
Token::String(s) => Token::Atom(s),
other => other,
},
':' => match self.peek() {
'=' => pop2!(self, Token::ColonEqual),
':' => pop2!(self, Token::ColonColon),
_ => pop!(self, Token::Colon),
},
'+' => {
if self.peek() == '+' {
pop2!(self, Token::PlusPlus)
} else {
pop!(self, Token::Plus)
}
}
'/' => {
if self.peek() == '=' {
pop2!(self, Token::IsNotEqual)
} else {
pop!(self, Token::Slash)
}
}
'=' => match self.peek() {
'=' => pop2!(self, Token::IsEqual),
'>' => pop2!(self, Token::RightArrow),
'<' => pop2!(self, Token::IsLessThanOrEqual),
':' => {
if self.peek_next() == '=' {
pop3!(self, Token::IsExactlyEqual)
} else {
Token::Error(LexicalError::UnexpectedCharacter {
start: self.span().start(),
found: self.peek_next(),
})
}
}
'/' => {
if self.peek_next() == '=' {
pop3!(self, Token::IsExactlyNotEqual)
} else {
Token::Error(LexicalError::UnexpectedCharacter {
start: self.span().start(),
found: self.peek_next(),
})
}
}
_ => pop!(self, Token::Equals),
},
'<' => match self.peek() {
'<' => pop2!(self, Token::BinaryStart),
'-' => pop2!(self, Token::LeftStab),
'=' => pop2!(self, Token::LeftArrow),
_ => pop!(self, Token::IsLessThan),
},
'>' => match self.peek() {
'>' => pop2!(self, Token::BinaryEnd),
'=' => pop2!(self, Token::IsGreaterThanOrEqual),
_ => pop!(self, Token::IsGreaterThan),
},
'|' => {
if self.peek() == '|' {
pop2!(self, Token::BarBar)
} else {
pop!(self, Token::Bar)
}
}
'.' => {
if self.peek() == '.' {
if self.peek_next() == '.' {
pop3!(self, Token::DotDotDot)
} else {
pop2!(self, Token::DotDot)
}
} else {
pop!(self, Token::Dot)
}
}
'\\' => {
// Allow escaping newlines
let c = self.peek();
if c == '\n' {
pop2!(self);
return self.tokenize();
}
return match self.lex_escape_sequence() {
Ok(t) => Token::Integer((t as i64).into()),
Err(e) => Token::Error(e),
};
}
c => Token::Error(LexicalError::UnexpectedCharacter {
start: self.span().start(),
found: c,
}),
}
}
fn lex_comment(&mut self) -> Token {
let mut c = self.read();
// If there is another '%', then this is a regular comment line
if c == '%' {
self.skip();
loop {
c = self.read();
if c == '\n' {
break;
}
if c == '\0' {
self.eof = true;
break;
}
self.skip();
}
return Token::Comment;
}
// If no '%', then we should check for an Edoc tag, first skip all whitespace and advance
// the token start
self.skip_whitespace();
// See if this is an Edoc tag
c = self.read();
if c == '@' {
if self.peek().is_ascii_alphabetic() {
self.skip();
// Get the tag identifier
self.lex_identifier();
// Skip any leading whitespace in the value
self.skip_whitespace();
// Get value
loop {
c = self.read();
if c == '\n' {
break;
}
if c == '\0' {
self.eof = true;
break;
}
self.skip();
}
return Token::Edoc;
}
}
// If we reach here, its a normal comment
loop {
if c == '\n' {
break;
}
if c == '\0' {
self.eof = true;
break;
}
self.skip();
c = self.read();
}
return Token::Comment;
}
#[inline]
fn lex_escape_sequence(&mut self) -> Result<u64, LexicalError> {
let start_idx = self.index();
let c = self.read();
debug_assert_eq!(c, '\\');
self.escape.reset();
let mut byte_idx = 0;
loop {
let c = self.read();
let idx = start_idx + byte_idx;
let c = if c == '\0' { None } else { Some(c) };
let res = self.escape.transition(c, idx);
match res {
Ok((action, result)) => {
if let EscapeStmAction::Next = action {
byte_idx += c.map(|c| c.len_utf8()).unwrap_or(0);
self.pop();
}
if let Some(result) = result {
return Ok(result.cp);
}
}
Err(err) => Err(LexicalError::EscapeError { source: err })?,
}
}
}
#[inline]
fn lex_string(&mut self) -> Token {
let quote = self.pop();
debug_assert!(quote == '"' || quote == '\'');
let mut buf = None;
loop {
match self.read() {
'\\' => match self.lex_escape_sequence() {
Ok(_c) => (),
Err(err) => return Token::Error(err),
},
'\0' if quote == '"' => {
return Token::Error(LexicalError::UnclosedString { span: self.span() });
}
'\0' if quote == '\'' => {
return Token::Error(LexicalError::UnclosedAtom { span: self.span() });
}
c if c == quote => {
let span = self.span().shrink_front(ByteOffset(1));
self.skip();
self.advance_start();
if self.read() == quote {
self.skip();
buf = Some(self.slice_span(span).to_string());
continue;
}
let symbol = if let Some(mut buf) = buf {
buf.push_str(self.slice_span(span));
Symbol::intern(&buf)
} else {
Symbol::intern(self.slice_span(span))
};
let token = Token::String(symbol);
return token;
}
_ => {
self.skip();
continue;
}
}
}
}
#[inline]
fn lex_identifier(&mut self) -> Token {
let c = self.pop();
debug_assert!(c == '_' || c.is_ascii_alphabetic());
loop {
match self.read() {
'_' => self.skip(),
'@' => self.skip(),
'0'..='9' => self.skip(),
c if c.is_alphabetic() => self.skip(),
_ => break,
}
}
Token::Ident(Symbol::intern(self.slice()))
}
#[inline]
fn lex_bare_atom(&mut self) -> Token {
let c = self.pop();
debug_assert!(c.is_ascii_lowercase());
loop {
match self.read() {
'_' => self.skip(),
'@' => self.skip(),
'0'..='9' => self.skip(),
c if c.is_alphabetic() => self.skip(),
_ => break,
}
}
Token::from_bare_atom(self.slice())
}
#[inline]
fn lex_digits(
&mut self,
radix: u32,
allow_leading_underscore: bool,
num: &mut String,
) -> Result<(), LexicalError> {
let mut last_underscore = !allow_leading_underscore;
let mut c = self.read();
loop {
match c {
c if c.is_digit(radix) => {
last_underscore = false;
num.push(self.pop());
}
'_' if last_underscore => {
return Err(LexicalError::UnexpectedCharacter {
start: self.span().start(),
found: c,
});
}
'_' if self.peek().is_digit(radix) => {
last_underscore = true;
self.pop();
}
_ => break,
}
c = self.read();
}
Ok(())
}
#[inline]
fn lex_number(&mut self) -> Token {
let mut num = String::new();
let mut c;
// Expect the first character to be either a sign on digit
c = self.read();
debug_assert!(c == '-' || c == '+' || c.is_digit(10), "got {}", c);
// If sign, consume it
//
// -10
// ^
//
let negative = c == '-';
if c == '-' || c == '+' {
num.push(self.pop());
}
// Consume leading digits
//
// -10.0
// ^^
//
// 10e10
// ^^
//
if let Err(err) = self.lex_digits(10, false, &mut num) {
return Token::Error(err);
}
// If we have a dot with a trailing number, we lex a float.
// Otherwise we return consumed digits as an integer token.
//
// 10.0
// ^ lex_float()
//
// fn() -> 10 + 10.
// ^ return integer token
//
c = self.read();
if c == '.' {
if self.peek().is_digit(10) {
// Pushes .
num.push(self.pop());
return self.lex_float(num, false);
}
return to_integer_literal(&num, 10);
}
// Consume exponent marker
//
// 10e10
// ^ lex_float()
//
// 10e-10
// ^^ lex_float()
if c == 'e' || c == 'E' {
let c2 = self.peek();
if c2 == '-' || c2 == '+' {
num.push(self.pop());
num.push(self.pop());
return self.lex_float(num, true);
} else if c2.is_digit(10) {
num.push(self.pop());
return self.lex_float(num, true);
}
}
// If followed by '#', the leading digits were the radix
//
// 10#16
// ^ interpret leading as radix
if c == '#' {
self.skip();
// Parse in the given radix
let radix = match num[..].parse::<u32>() {
Ok(r) => r,
Err(e) => {
return Token::Error(LexicalError::InvalidRadix {
span: self.span(),
reason: e.to_string(),
});
}
};
if radix >= 2 && radix <= 32 {
let mut num = String::new();
// If we have a sign, push that to the new integer string
c = self.read();
if c.is_digit(radix) {
if negative {
num.push('-');
}
}
// Lex the digits themselves
if let Err(err) = self.lex_digits(radix, false, &mut num) {
return Token::Error(err);
}
return to_integer_literal(&num, radix);
} else {
Token::Error(LexicalError::InvalidRadix {
span: self.span(),
reason: "invalid radix (must be in 2..32)".to_string(),
})
}
} else {
to_integer_literal(&num, 10)
}
}
// Called after consuming a number up to and including the '.'
#[inline]
fn lex_float(&mut self, num: String, seen_e: bool) -> Token {
let mut num = num;
let mut c = self.pop();
debug_assert!(c.is_digit(10), "got {}", c);
num.push(c);
if let Err(err) = self.lex_digits(10, true, &mut num) {
return Token::Error(err);
}
c = self.read();
// If we've already seen e|E, then we're done
if seen_e {
return self.to_float_literal(num);
}
if c == 'E' || c == 'e' {
num.push(self.pop());
c = self.read();
if c == '-' || c == '+' {
num.push(self.pop());
c = self.read();
}
if !c.is_digit(10) {
return Token::Error(LexicalError::InvalidFloat {
span: self.span(),
reason: "expected digits after scientific notation".to_string(),
});
}
if let Err(err) = self.lex_digits(10, false, &mut num) {
return Token::Error(err);
}
}
self.to_float_literal(num)
}
fn to_float_literal(&self, num: String) -> Token {
let reason = match f64::from_str(&num) {
Ok(f) => match Float::new(f) {
Ok(f) => return Token::Float(f),
Err(FloatError::Nan) => "float cannot be NaN".to_string(),
Err(FloatError::Infinite) => "float cannot be -Inf or Inf".to_string(),
},
Err(e) => e.to_string(),
};
Token::Error(LexicalError::InvalidFloat {
span: self.span(),
reason,
})
}
}
impl<S> Iterator for Lexer<S>
where
S: Source,
{
type Item = Lexed;
fn next(&mut self) -> Option<Self::Item> {
let mut res = self.lex();
loop {
match res {
Some(Ok(LexicalToken(_, Token::Comment, _))) => {
res = self.lex();
}
_ => break,
}
}
res
}
}
// Converts the string literal into either a `i64` or arbitrary precision integer, preferring `i64`.
//
// This function panics if the literal is unparseable due to being invalid for the given radix,
// or containing non-ASCII digits.
fn to_integer_literal(literal: &str, radix: u32) -> Token {
let int = Integer::from_string_radix(literal, radix).unwrap();
Token::Integer(int)
}
#[cfg(test)]
mod test {
use firefly_diagnostics::{ByteIndex, CodeMap, SourceId, SourceIndex, SourceSpan};
use firefly_number::Float;
use firefly_parser::{FileMapSource, Scanner, Source};
use pretty_assertions::assert_eq;
use crate::lexer::*;
macro_rules! symbol {
($sym:expr) => {
Symbol::intern($sym)
};
}
macro_rules! assert_lex(
($input:expr, $expected:expr) => ({
let codemap = CodeMap::new();
let id = codemap.add("nofile", $input.to_string());
let file = codemap.get(id).unwrap();
let source = FileMapSource::new(file);
let scanner = Scanner::new(source);
let lexer = Lexer::new(scanner);
let results = lexer.map(|result| {
match result {
Ok(LexicalToken(_start, token, _end)) => {
Ok(token)
}
Err(err) => {
Err(err)
}
}
}).collect::<Vec<_>>();
assert_eq!(results, $expected(id));
})
);
#[test]
fn lex_symbols() {
assert_lex!(":", |_| vec![Ok(Token::Colon)]);
assert_lex!(",", |_| vec![Ok(Token::Comma)]);
assert_lex!("=", |_| vec![Ok(Token::Equals)]);
}
#[test]
fn lex_comment() {
assert_lex!("% this is a comment", |_| vec![]);
assert_lex!("% @author Paul", |_| vec![Ok(Token::Edoc)]);
}
macro_rules! f {
($float:expr) => {
Token::Float(Float::new($float).unwrap())
};
}
#[test]
fn lex_float_literal() {
// With leading 0
assert_lex!("0.0", |_| vec![Ok(f!(0.0))]);
assert_lex!("000051.0", |_| vec![Ok(f!(51.0))]);
assert_lex!("05162.0", |_| vec![Ok(f!(5162.0))]);
assert_lex!("099.0", |_| vec![Ok(f!(99.0))]);
assert_lex!("04624.51235", |_| vec![Ok(f!(4624.51235))]);
assert_lex!("0.987", |_| vec![Ok(f!(0.987))]);
assert_lex!("0.55e10", |_| vec![Ok(f!(0.55e10))]);
assert_lex!("612.0e61", |_| vec![Ok(f!(612e61))]);
assert_lex!("0.0e-1", |_| vec![Ok(f!(0e-1))]);
assert_lex!("41.0e+9", |_| vec![Ok(f!(41e+9))]);
// Without leading 0
assert_lex!("5162.0", |_| vec![Ok(f!(5162.0))]);
assert_lex!("99.0", |_| vec![Ok(f!(99.0))]);
assert_lex!("4624.51235", |_| vec![Ok(f!(4624.51235))]);
assert_lex!("612.0e61", |_| vec![Ok(f!(612e61))]);
assert_lex!("41.0e+9", |_| vec![Ok(f!(41e+9))]);
// With leading negative sign
assert_lex!("-700.5", |_| vec![Ok(Token::Minus), Ok(f!(700.5))]);
assert_lex!("-9.0e2", |_| vec![Ok(Token::Minus), Ok(f!(9.0e2))]);
assert_lex!("-0.5e1", |_| vec![Ok(Token::Minus), Ok(f!(0.5e1))]);
assert_lex!("-0.0", |_| vec![Ok(Token::Minus), Ok(f!(0.0))]);
// Underscores
assert_lex!("12_3.45_6", |_| vec![Ok(f!(123.456))]);
assert_lex!("1e1_0", |_| vec![Ok(f!(1e10))]);
assert_lex!("123_.456", |_| vec![
Ok(Token::Integer(123.into())),
Ok(Token::Ident(symbol!("_"))),
Ok(Token::Dot),
Ok(Token::Integer(456.into())),
]);
}
#[test]
fn lex_identifier_or_atom() {
assert_lex!("_identifier", |_| vec![Ok(Token::Ident(symbol!(
"_identifier"
)))]);
assert_lex!("_Identifier", |_| vec![Ok(Token::Ident(symbol!(
"_Identifier"
)))]);
assert_lex!("identifier", |_| vec![Ok(Token::Atom(symbol!(
"identifier"
)))]);
assert_lex!("Identifier", |_| vec![Ok(Token::Ident(symbol!(
"Identifier"
)))]);
assert_lex!("z0123", |_| vec![Ok(Token::Atom(symbol!("z0123")))]);
assert_lex!("i_d@e_t0123", |_| vec![Ok(Token::Atom(symbol!(
"i_d@e_t0123"
)))]);
}
#[test]
fn lex_integer_literal() {
// Decimal
assert_lex!("1", |_| vec![Ok(Token::Integer(1.into()))]);
assert_lex!("9624", |_| vec![Ok(Token::Integer(9624.into()))]);
assert_lex!("-1", |_| vec![
Ok(Token::Minus),
Ok(Token::Integer(1.into()))
]);
assert_lex!("-9624", |_| vec![
Ok(Token::Minus),
Ok(Token::Integer(9624.into()))
]);
// Hexadecimal
assert_lex!(r#"\x00"#, |_| vec![Ok(Token::Integer(0x0.into()))]);
assert_lex!(r#"\x{1234FF}"#, |_| vec![Ok(Token::Integer(
0x1234FF.into()
))]);
assert_lex!("-16#0", |_| vec![
Ok(Token::Minus),
Ok(Token::Integer(0x0.into()))
]);
assert_lex!("-16#1234FF", |_| vec![
Ok(Token::Minus),
Ok(Token::Integer(0x1234FF.into()))
]);
// Octal
assert_lex!(r#"\0"#, |_| vec![Ok(Token::Integer(0.into()))]);
assert_lex!(r#"\624"#, |_| vec![Ok(Token::Integer(0o624.into()))]);
assert_lex!(r#"\6244"#, |_| vec![
Ok(Token::Integer(0o624.into())),
Ok(Token::Integer(4.into()))
]);
// Octal integer literal followed by non-octal digits.
assert_lex!(r#"\008"#, |_| vec![
Ok(Token::Integer(0.into())),
Ok(Token::Integer(8.into()))
]);
assert_lex!(r#"\1238"#, |_| vec![
Ok(Token::Integer(0o123.into())),
Ok(Token::Integer(8.into()))
]);
// Underscores
assert_lex!("123_456", |_| vec![Ok(Token::Integer(123456.into()))]);
assert_lex!("123_456_789", |_| vec![Ok(Token::Integer(
123456789.into()
))]);
assert_lex!("1_2", |_| vec![Ok(Token::Integer(12.into()))]);
assert_lex!("16#123_abc", |_| vec![Ok(Token::Integer(0x123abc.into()))]);
assert_lex!("10#123_abc", |_| vec![
Ok(Token::Integer(123.into())),
Ok(Token::Ident(Symbol::intern("_abc")))
]);
assert_lex!("1_6#abc", |_| vec![Ok(Token::Integer(0xabc.into()))]);
assert_lex!("1__0", |_| vec![
Ok(Token::Integer(1.into())),
Ok(Token::Ident(Symbol::intern("__0")))
]);
assert_lex!("123_", |_| vec![
Ok(Token::Integer(123.into())),
Ok(Token::Ident(Symbol::intern("_"))),
]);
assert_lex!("123__", |_| vec![
Ok(Token::Integer(123.into())),
Ok(Token::Ident(Symbol::intern("__"))),
]);
}
#[test]
fn lex_string() {
assert_lex!(r#""this is a string""#, |_| vec![Ok(Token::String(
symbol!("this is a string")
))]);
assert_lex!(r#""this is a string"#, |source_id| vec![Err(
LexicalError::UnclosedString {
span: SourceSpan::new(
SourceIndex::new(source_id, ByteIndex(0)),
SourceIndex::new(source_id, ByteIndex(17))
)
}
)]);
}
#[test]
fn lex_whitespace() {
assert_lex!(" \n \t", |_| vec![]);
assert_lex!("\r\n", |_| vec![]);
}
}
|
use juniper::{graphql_scalar, InputValue, ScalarValue, Value};
struct ScalarSpecifiedByUrl;
#[graphql_scalar(
specified_by_url = "not an url",
with = scalar,
parse_token(i32),
)]
type Scalar = ScalarSpecifiedByUrl;
mod scalar {
use super::*;
pub(super) fn to_output<S: ScalarValue>(_: &ScalarSpecifiedByUrl) -> Value<S> {
Value::scalar(0)
}
pub(super) fn from_input<S: ScalarValue>(
_: &InputValue<S>,
) -> Result<ScalarSpecifiedByUrl, String> {
Ok(ScalarSpecifiedByUrl)
}
}
fn main() {}
|
pub fn combinations<T: Copy>(k: usize, li: &[T]) -> Vec<Vec<T>> {
fn comb_rec<T: Copy>(k: usize, rem: &[T], acc: &Vec<T>) -> Vec<Vec<T>> {
if k == 1 {
rem.into_iter()
.map(|&x| {
let mut acc2 = acc.clone();
acc2.push(x);
acc2
})
.collect()
} else {
let mut res = vec![];
for i in 0..(rem.len() - k + 1) {
let (left, right) = rem.split_at(i + 1);
let x = left[left.len() - 1];
let mut acc2 = acc.clone();
acc2.push(x);
res.extend(comb_rec(k - 1, &right, &acc2));
}
res
}
}
comb_rec(k, &li, &vec![])
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn test_combimations() {
let li = vec!['a', 'b', 'c', 'd', 'e', 'f'];
let combs = combinations(3, &li);
assert_eq!(combs.len(), 20);
for comb in &combs {
assert_eq!(comb.len(), 3);
let uniq: HashSet<char> = comb.clone().into_iter().collect();
assert_eq!(uniq.len(), 3);
}
let uniq: HashSet<Vec<char>> = combs.clone().into_iter().collect();
assert_eq!(uniq.len(), 20);
}
}
|
use crate::Space::*;
use std::collections::HashMap;
enum Space {
Floor,
Empty,
Occupied,
}
fn get_input() -> HashMap<(i64, i64), Space> {
let mut map = HashMap::new();
include_str!("../input.txt")
.lines()
.enumerate()
.for_each(|(y, line)| {
line.chars().enumerate().for_each(|(x, ch)| {
map.insert(
(x as i64, y as i64),
match ch {
'.' => Floor,
'L' => Empty,
'#' => Occupied,
_ => panic!(),
},
);
});
});
map
}
fn generation(curr: &HashMap<(i64, i64), Space>, post: &mut HashMap<(i64, i64), Space>) -> bool {
let mut changed = false;
let dirs = [
(0i64, 1i64),
(1, 0),
(0, -1),
(-1, 0),
(1, 1),
(-1, -1),
(1, -1),
(-1, 1),
];
curr.iter().for_each(|((x, y), space)| {
// ------------------------------------------ part one:
// let occupied_nearby = dirs
// .iter()
// .filter(|&&dir| matches!(curr.get(&(x + dir.0, y + dir.1)), Some(Occupied)))
// .count();
// ------------------------------------------ part one:
let occupied_nearby = dirs
.iter()
.filter(|&&dir| {
let mut checked = (x + dir.0, y + dir.1);
let mut out = false;
while let Some(space) = curr.get(&checked) {
match space {
Occupied => {
out = true;
break;
}
Empty => {
break;
}
Floor => {}
}
checked = (checked.0 + dir.0, checked.1 + dir.1);
}
out
})
.count();
match space {
Floor => {
post.insert((*x, *y), Floor);
}
Empty => {
// if occupied_nearby == 0 {
if occupied_nearby == 0 {
post.insert((*x, *y), Occupied);
changed = true;
} else {
post.insert((*x, *y), Empty);
}
}
Occupied => {
// if occupied_nearby >= 4 {
if occupied_nearby >= 5 {
post.insert((*x, *y), Empty);
changed = true;
} else {
post.insert((*x, *y), Occupied);
}
}
};
});
changed
}
fn main() {
let mut curr: HashMap<(i64, i64), Space> = get_input();
let mut post: HashMap<(i64, i64), Space> = HashMap::new();
let mut changed = true;
let mut generations = 0;
while changed {
changed = generation(&curr, &mut post);
curr = post;
post = HashMap::new();
generations += 1;
}
let free_seats = curr.iter().filter(|&a| matches!(a.1, Occupied)).count();
println!("part one, generations: {}", generations);
println!("part one, free seats: {}", free_seats);
}
|
use neon::prelude::*;
use manifest::StreamType;
use ::MANIFEST;
/// # Arguments
/// None
///
/// # Return
/// A string containing the loaded manifest's root node ID.
///
/// # Exceptions
/// Throws if there is no loaded manifest.
pub fn get_root_node_id(mut cx: FunctionContext) -> JsResult<JsString> {
if let Some(ref manifest) = *MANIFEST.read() {
Ok(cx.string(format!("{}", manifest.get_root_node_id().to_hyphenated())))
} else {
error!("tried to get root node ID while no manifest loaded");
cx.throw_error("no manifest loaded")
}
}
/// # Arguments
/// [parent node ID: String, node type: String]
///
/// # Return
/// A string containing the ID of the new node, or null if the parent
/// did not exist.
///
/// # Exceptions
/// Throws if there is no loaded manifest or if the node ID can't be parsed.
pub fn create_node(mut cx: FunctionContext) -> JsResult<JsValue> {
let parent_id = get_id_arg!(cx[0]);
let node_type = {
use manifest::NodeType::*;
let node_type = cx.argument::<JsString>(1)?.value();
match &node_type[..] {
"Root" => Root,
"Title" => Title,
"PublicationTime" => PublicationTime,
"Franchise" => Franchise,
"Show" => Show,
"Season" => Season,
"Episode" => Episode,
"Movie" => Movie,
"FanmadeContent" => FanmadeContent,
"Game" => Game,
"Image" => Image,
"Literature" => Literature,
"Book" => Book,
"Comic" => Comic,
"Chapter" => Chapter,
"Album" => Album,
"Music" => Music,
"MiscAudio" => MiscAudio,
other => Other(other.to_string()),
}
};
info!("Creating new node with parent {} and type {:?}", parent_id, node_type);
if let Some(ref mut manifest) = *MANIFEST.write() {
if let Ok(new_id) = manifest.create_node(&parent_id, node_type) {
Ok(cx.string(format!("{}", new_id.to_hyphenated())).upcast())
} else {
Ok(cx.null().upcast())
}
} else {
error!("tried to add node while no manifest loaded");
cx.throw_error("no manifest loaded")
}
}
/// Determines the parent of the given node. The root node's parent is itself.
///
/// # Arguments
/// [node ID: String]
///
/// # Return
/// A string, the ID of the parent node. If the given node did not exist, returns
/// null.
///
/// # Exceptions
/// Throws if there is no loaded manifest or if the node ID can't be parsed.
pub fn get_node_parent(mut cx: FunctionContext) -> JsResult<JsValue> {
let node_id = get_id_arg!(cx[0]);
info!("Finding parent of node {}", node_id);
if let Some(ref manifest) = *MANIFEST.read() {
if let Ok(parent_id) = manifest.get_node_parent(&node_id) {
Ok(cx.string(format!("{}", parent_id.to_hyphenated())).upcast())
} else {
warn!("Tried to find the parent of non-existant node {}", node_id);
Ok(cx.null().upcast())
}
} else {
error!("tried to find a node's parent while no manifest loaded");
cx.throw_error("no manifest loaded")
}
}
/// Determines the type of the given node.
///
/// # Arguments
/// [node ID: String]
///
/// # Return
/// A string, the type of the given node. If the given node did not exist, returns
/// null.
///
/// # Exceptions
/// Throws if there is no loaded manifest or if the node ID can't be parsed.
pub fn get_node_type(mut cx: FunctionContext) -> JsResult<JsValue> {
let node_id = get_id_arg!(cx[0]);
info!("Finding type of node {}", node_id);
if let Some(ref manifest) = *MANIFEST.read() {
if let Ok(node_type) = manifest.get_node_type(&node_id) {
Ok(cx.string(format!("{}", node_type)).upcast())
} else {
warn!("Tried to find the type of non-existant node {}", node_id);
Ok(cx.null().upcast())
}
} else {
error!("tried to find a node's type while no manifest loaded");
cx.throw_error("no manifest loaded")
}
}
/// Finds all children of the given node.
///
/// # Arguments
/// [node ID: String]
///
/// # Return
/// An array of strings, each of which are the ID of a child node
/// of the given node, or null if the node doesn't exist.
///
/// # Exceptions
/// Throws if there is no loaded manifest or if the node ID can't be parsed.
pub fn find_node_children(mut cx: FunctionContext) -> JsResult<JsValue> {
let node_id = get_id_arg!(cx[0]);
info!("Finding children of node {}", node_id);
if let Some(ref manifest) = *MANIFEST.read() {
if let Ok(children) = manifest.get_node_children(&node_id) {
let mut array = JsArray::new(&mut cx, children.len() as u32);
for (i, child_id) in children.iter().enumerate() {
let val = cx.string(format!("{}", child_id.to_hyphenated()));
array.set(&mut cx, i as u32, val)?;
}
Ok(array.upcast())
} else {
warn!("tried to find the children of a non-existant node");
Ok(cx.null().upcast())
}
} else {
error!("tried to find a node's children while no manifest loaded");
cx.throw_error("no manifest loaded")
}
}
/// # Arguments
/// [node ID: String]
///
/// # Return
///
/// TODO: should this just return an array of stream IDs?
///
/// An array of objects, structured as follows:
/// {
/// "id": [stream ID: String]
/// "type": [stream type: String],
/// "size": [stream size: Number],
/// "tags": [tag IDs as strings] <- TODO: NOT YET IMPLEMENTED
/// }
/// If the node refers to an unknown stream, then that entry in the returned array
/// will be null. If the node has no streams, the returned array will be empty.
///
/// If there is no node of the given ID, then this returns null.
///
/// # Exceptions
/// Throws if there is no loaded manifest or if the node ID can't be parsed.
pub fn get_node_streams(mut cx: FunctionContext) -> JsResult<JsValue> {
let node_id = get_id_arg!(cx[0]);
info!("Finding streams of node {}", node_id);
if let Some(ref manifest) = *MANIFEST.read() {
if let Ok(streams) = manifest.get_node_streams(&node_id) {
let mut array = JsArray::new(&mut cx, streams.len() as u32);
for (i, stream_id) in streams.iter().enumerate() {
if let Ok((stream_type, stream_size)) = manifest.get_stream_metadata(stream_id) {
let id = cx.string(format!("{}", stream_id.to_hyphenated()));
let stream_type = cx.string(match stream_type {
StreamType::Audio { .. } => "Audio",
StreamType::Visual { .. } => "Visual",
StreamType::Text { .. } => "Text",
StreamType::DateTime { .. } => "DateTime",
StreamType::Archive { .. } => "Archive",
});
// The cast to f64 is safe for all values up to 2^53 + 1.
let stream_size = cx.number(stream_size as f64);
let stream_tags = cx.empty_array(); // TODO
let mut obj = cx.empty_object();
obj.set(&mut cx, "id", id)?;
obj.set(&mut cx, "type", stream_type)?;
obj.set(&mut cx, "size", stream_size)?;
obj.set(&mut cx, "tags", stream_tags)?;
array.set(&mut cx, i as u32, obj)?;
} else {
let null = cx.null();
array.set(&mut cx, i as u32, null)?;
}
}
Ok(array.upcast())
} else {
warn!("tried to find streams of nonexistent node {}", node_id);
Ok(cx.null().upcast())
}
} else {
error!("tried to find streams of a node while no manifest loaded");
cx.throw_error("no manifest loaded")
}
} |
#![feature(nll)]
pub mod scheme;
use scheme::interpreter::Interpreter;
fn main() {
let mut interp = Interpreter::new();
let args: Vec<String> = std::env::args().collect();
if args.len() > 1 {
interp.run_once(&args[1]);
} else {
interp.run_repl();
}
}
|
mod back_of_house {
//公有结构体
pub struct Breakfast {
//公有字段 toast
pub toast: String,
//私有字段 seasonal_fruit
seasonal_fruit: String,
}
impl Breakfast {
//添加关联方法
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String:: from(toast),
seasonal_fruit: String:: from( "peaches"),
}
}
}
}
pub fn eat_at_restaurant() {
// Order a breakfast in the summer with Rye toast
let mut meal = back_of_house::Breakfast::summer( "Rye");
// Change our mind about what bread we'd like
meal.toast = String:: from( "Wheat");
println!( "I'd like {} toast please", meal.toast);
}
|
use crate::model::*;
use crate::util;
use std::collections::VecDeque;
use std::fmt::Write;
use std::io::{copy, Read, Seek};
use std::path::{Path, PathBuf};
use std::vec::Vec;
use hyper;
use hyper_rustls;
use id3;
use log;
use select::document::Document;
use select::predicate::{Class, Name, Predicate};
use tempfile;
use zip;
pub trait Source {
fn belongs(&self, url: &str) -> bool;
fn fetch(&self, url: &str, mp3_dir: &Path) -> Result<Album, util::Error>;
fn description(&self, album: &Album, track: &Track) -> Result<String, util::Error>;
}
const SOURCES: [&dyn Source; 1] = [&Ektoplazm {}];
pub fn fetch(url: &str, mp3_dir: &Path) -> Result<Album, util::Error> {
for s in &SOURCES {
if s.belongs(url) {
return s.fetch(url, mp3_dir);
}
}
Err(util::Error::new(&format!("No source known for {}", url)))
}
pub fn description(album: &Album, track: &Track) -> Result<String, util::Error> {
for s in &SOURCES {
if s.belongs(&album.url) {
return s.description(album, track);
}
}
Err(util::Error::new(&format!(
"No source known for {}",
album.url
)))
}
struct Ektoplazm {}
impl Source for Ektoplazm {
fn belongs(&self, url: &str) -> bool {
url.starts_with("https://ektoplazm.com/free-music/")
}
fn fetch(&self, url: &str, mp3_dir: &Path) -> Result<Album, util::Error> {
log::info!("Fetching {}", url);
let res = download(url)?;
let (mp3_link, license_link, labels, tags, _) = ektoplazm_parse(res)?;
let mut res = download(&mp3_link)?;
let mut tmp = tempfile::tempfile()?;
copy(&mut res, &mut tmp)?;
let tmpdir = unpack(tmp, mp3_dir)?;
let (album_title, album_artist, album_year, tracks) = read_id3(tmpdir.path())?;
let album = Album {
url: url.to_string(),
artist: album_artist,
title: album_title,
license: license_link,
year: album_year,
labels: labels,
tags: tags,
tracks: tracks,
youtube_id: None,
};
let tmpdir = tmpdir.into_path();
if let Err(e) = std::fs::rename(&tmpdir, album.dirname(mp3_dir)) {
std::fs::remove_dir_all(tmpdir)?;
return Err(util::Error::from(e));
}
Ok(album)
}
fn description(&self, album: &Album, track: &Track) -> Result<String, util::Error> {
let mut trackno = 99;
for (n, t) in album.tracks.iter().enumerate() {
if track == t {
trackno = n + 1;
break;
}
}
let mut result = format!("Download the full album from Ektoplazm: {}\n", album.url);
write!(result, "\nArtist: {}", track.artist)?;
write!(result, "\nTrack: {}", track.title)?;
if let Some(y) = album.year {
write!(result, "\nAlbum: {} ({})", album.title, y)?;
} else {
write!(result, "\nAlbum: {}", album.title)?;
}
write!(result, "\nTrack number: {:02}", trackno)?;
if let Some(b) = track.bpm {
write!(result, "\nBPM: {}", b)?;
}
write!(result, "\n")?;
if !album.tags.is_empty() {
write!(result, "\nTags: {}", album.tags.join(", "))?;
}
if !album.labels.is_empty() {
write!(result, "\nReleased by: {}", album.labels.join(" & "))?;
}
if let Some(l) = &album.license {
write!(result, "\nLicense: {}", l)?;
}
Ok(result)
}
}
fn track_to_album(album_item: &mut Option<String>, track_item: Option<&str>) {
if let Some(tr) = track_item {
if let Some(al) = album_item {
if tr != al {
log::warn!(
"Album metadata has multiple different values {:?}, {:?}",
al,
tr
);
}
} else {
*album_item = Some(tr.to_string());
}
}
}
fn required_tag<T>(result: Option<T>, what: &str, path: &Path) -> Result<T, util::Error> {
result.ok_or(util::Error::new(&format!(
"{} tag missing in {:?}",
what, path
)))
}
fn read_id3(dir: &Path) -> Result<(String, Option<String>, Option<u16>, Vec<Track>), util::Error> {
let mut tracks: Vec<(u32, Track)> = Vec::new();
let mut album_artist: Option<String> = None;
let mut album_title: Option<String> = None;
let mut album_year: Option<u16> = None;
for f in std::fs::read_dir(dir)? {
let f = f?;
if !f.file_type()?.is_file() {
continue;
}
let path = f.path();
match path.extension() {
None => continue,
Some(ext) => {
if ext != "mp3" {
continue;
}
}
}
let tag = id3::Tag::read_from_path(&path)?;
let num = required_tag(tag.track(), "Track number", &path)?;
tracks.push((
num,
Track {
artist: required_tag(tag.artist(), "Artist", &path)?.to_string(),
title: required_tag(tag.title(), "Title", &path)?.to_string(),
bpm: tag
.get("TBPM")
.and_then(|f| f.content().text())
.and_then(|t| t.parse().ok()),
mp3_file: Some(PathBuf::from(f.file_name())),
video_file: None,
youtube_id: None,
},
));
track_to_album(&mut album_artist, tag.album_artist());
track_to_album(&mut album_title, tag.album());
album_year = tag.year().map(|y| y as u16);
}
tracks.sort_by_key(|t| t.0);
let tracks = tracks.into_iter().map(|t| t.1).collect();
if album_artist == Some("VA".to_string()) {
album_artist = None;
}
match album_title {
None => Err(util::Error::new("Album artist cannot be determined")),
Some(t) => Ok((t, album_artist, album_year, tracks)),
}
}
fn download(url: &str) -> Result<hyper::client::response::Response, util::Error> {
log::debug!("GET {}", url);
let client = hyper::Client::with_connector(hyper::net::HttpsConnector::new(
hyper_rustls::TlsClient::new(),
));
let res = client
.get(url)
.header(hyper::header::UserAgent(util::USER_AGENT.to_owned()))
.send()?;
//let mut body = Vec::new();
if res.status != hyper::status::StatusCode::Ok {
log::error!("Failed to GET {}: {:?}", url, res);
//let _body_len = res.read_to_end(&mut body)?;
//log::debug!("{:?}\n{:?}", res, std::str::from_utf8(&body).unwrap());
return Err(util::Error::new("Failed to fetch URL"));
}
log::debug!("Got status {}", res.status);
Ok(res)
}
fn ektoplazm_parse<T: Read>(
res: T,
) -> util::Result<(String, Option<String>, Vec<String>, Vec<String>, u32)> {
let doc = Document::from_read(res)?;
let mp3_link = match doc
.find(Class("entry").descendant(Name("a")))
.filter(|tag| tag.text() == "MP3 Download")
.filter_map(|tag| tag.attr("href"))
.next()
{
None => return Err(util::Error::new("Failed to find download link")),
Some(link) => link.to_string(),
};
let license_link = doc
.find(Class("entry").descendant(Name("a")))
.filter(|tag| {
tag.attr("href")
.map_or(false, |target| target.contains("creativecommons"))
})
.filter(|tag| {
let lower = tag.text().to_lowercase();
lower.contains("license") || lower.contains("licence") || lower.contains("commons")
})
.filter_map(|tag| tag.attr("href"))
.next()
.map(|x| x.to_string());
let tags = doc
.find(Name("h3").descendant(Class("style")).descendant(Name("a")))
.map(|tag| tag.text())
.collect();
let labels = doc
.find(Name("h3").child(Name("strong")).child(Name("a")))
.map(|tag| tag.text())
.collect();
let tracknum = doc.find(Class("tl").descendant(Class("t"))).count();
Ok((mp3_link, license_link, labels, tags, tracknum as u32))
}
fn unpack<T: Read + Seek>(res: T, outdir: &Path) -> Result<tempfile::TempDir, util::Error> {
let mut zip = zip::ZipArchive::new(res)?;
let tmpdir = tempfile::Builder::new()
.prefix("0-ektoboat-tmp-")
.tempdir_in(outdir)?;
for i in 0..zip.len() {
let mut zipfile = zip.by_index(i)?;
let sanitized = zipfile.sanitized_name();
let basename = match sanitized.file_name() {
None => {
log::warn!("Unzip: skipping {:?}", sanitized);
continue;
}
Some(f) => f,
};
let mut dest = PathBuf::from(tmpdir.path());
dest.push(basename);
log::debug!("Unzip {:?} -> {:?}", basename, dest);
let mut df = std::fs::File::create(dest)?;
copy(&mut zipfile, &mut df)?;
}
Ok(tmpdir)
}
pub struct EktoplazmScraper {
next_page: u32,
urls: VecDeque<String>,
}
impl EktoplazmScraper {
pub fn from_offset(offset: u32) -> EktoplazmScraper {
EktoplazmScraper {
next_page: 1 + offset / 5,
urls: VecDeque::new(),
}
}
}
impl std::iter::Iterator for EktoplazmScraper {
type Item = Result<String, util::Error>;
fn next(&mut self) -> Option<Self::Item> {
if self.urls.is_empty() {
self.urls = match ektoplazm_scrape_list(self.next_page) {
Err(e) => return Some(Err(e)),
Ok(urls) => urls,
};
self.next_page += 1;
}
let url = self.urls.pop_front()?;
/*
let (tracks, zipbytes) = match ektoplazm_scrape_album(&url) {
Err(e) => return Some(Err(e)),
Ok((t, z)) => (t, z),
};
Some(Ok((url, tracks, zipbytes)))
*/
Some(Ok(url))
}
}
fn ektoplazm_scrape_list(offset: u32) -> Result<VecDeque<String>, util::Error> {
let url = format!("https://ektoplazm.com/section/free-music/page/{}", offset);
let res = download(&url)?;
let doc = Document::from_read(res)?;
let links = doc
.find(Class("post").child(Name("h1")).child(Name("a")))
.filter_map(|tag| tag.attr("href"))
.map(|x| x.to_string())
.collect();
Ok(links)
}
/*
fn ektoplazm_scrape_album(url: &str) -> Result<(u32, u32), util::Error> {
let res = download(url)?;
let (mp3_link, _, _, _, _tracks) = ektoplazm_parse(res)?;
let res = download(&mp3_link)?;
let length = res.headers.get::<hyper::header::ContentLength>().map(|n| n.0 as u32).unwrap_or(0);
drop(res);
Ok((tracks, length))
}
*/
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
use std::fs;
use std::path::PathBuf;
fn fixture(fname: &str) -> std::fs::File {
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests");
d.push("data");
d.push(fname);
fs::File::open(d).unwrap()
}
#[test]
fn parse_ektoplazm() {
let cases = &[
(
"ektoplazm1.html",
"https://ektoplazm.com/files/Globular%20-%20Entangled%20Everything%20-%202018%20-%20MP3.zip",
Some("https://creativecommons.org/licenses/by-nc-sa/4.0/"),
Vec::new(),
vec!["Downtempo", "Psy Dub"],
10,
),
(
"ektoplazm-label.html",
"https://ektoplazm.com/files/White%20Morph%20-%20Dream%20Catcher%20-%202012%20-%20MP3.zip",
Some("https://creativecommons.org/licenses/by-nc-sa/3.0/"),
vec!["3L3Mental Records"],
vec!["Full-On", "Morning"],
4,
),
(
"ektoplazm-va.html",
"https://ektoplazm.com/files/VA%20-%20Dividing%202%20Worlds%20-%202018%20-%20MP3.zip",
Some("https://creativecommons.org/licenses/by-nc-sa/4.0/"),
vec!["Jaira Records"],
vec!["Techno", "Techtrance", "Zenonesque"],
9,
),
(
"ektoplazm-multilabel.html",
"https://ektoplazm.com/files/Rose%20Red%20Flechette%20-%20The%20Destruction%20Myth%20-%202018%20-%20MP3.zip",
Some("https://creativecommons.org/licenses/by-nc-sa/4.0/"),
vec!["Anomalistic Records", "Splatterkore Reck-ords"],
vec!["Experimental", "Psycore"],
8,
),
(
"ektoplazm-license.html",
"https://ektoplazm.com/files/Ekoplex%20-%20Enter%20The%20Dragon%20EP%20-%202008%20-%20MP3.zip",
Some("https://creativecommons.org/licenses/by-nc-nd/2.5/ca/"),
vec!["Ektoplazm"],
vec!["Full-On"],
3,
),
];
for c in cases {
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests");
d.push("data");
d.push(c.0);
let f = fs::File::open(d).unwrap();
let (mp3, license, labels, tags, tracknum) = ektoplazm_parse(f).unwrap();
assert_eq!(mp3, c.1.to_string());
assert_eq!(license, c.2.map(|x| x.to_string()));
assert_eq!(labels, c.3);
assert_eq!(tags, c.4);
assert_eq!(tracknum, c.5);
}
}
#[test]
fn unpack_id3_ektoplazm() {
let f = fixture("Risingson - Predestination - 2016 - MP3.zip");
let expected: HashSet<(String, u64)> = [
("00 - Risingson - Predestination.jpg", 2447869),
("01 - Risingson - Digital Being.mp3", 12879872),
("02 - Risingson - Robosapiens.mp3", 12060672),
("03 - Risingson - Predestination.mp3", 12892160),
("folder.jpg", 136773),
]
.iter()
.cloned()
.map(|(f, s)| (f.to_string(), s))
.collect();
let testdir = tempfile::tempdir().unwrap();
let dir = unpack(f, testdir.path()).unwrap();
let contents = fs::read_dir(dir.path())
.unwrap()
.map(|x| x.unwrap())
.map(|de| {
(
de.file_name().into_string().unwrap(),
de.metadata().unwrap().len(),
)
})
.collect::<HashSet<(_, _)>>();
assert_eq!(contents, expected);
let (album_title, album_artist, album_year, tracks) = read_id3(dir.path()).unwrap();
assert_eq!(album_title, "Predestination".to_string());
assert_eq!(album_artist, Some("Risingson".to_string()));
assert_eq!(album_year, Some(2016));
assert_eq!(
tracks,
vec![
Track {
artist: "Risingson".to_string(),
title: "Digital Being".to_string(),
bpm: Some(88),
mp3_file: Some(PathBuf::from("01 - Risingson - Digital Being.mp3")),
video_file: None,
youtube_id: None,
},
Track {
artist: "Risingson".to_string(),
title: "Robosapiens".to_string(),
bpm: Some(97),
mp3_file: Some(PathBuf::from("02 - Risingson - Robosapiens.mp3")),
video_file: None,
youtube_id: None,
},
Track {
artist: "Risingson".to_string(),
title: "Predestination".to_string(),
bpm: Some(88),
mp3_file: Some(PathBuf::from("03 - Risingson - Predestination.mp3")),
video_file: None,
youtube_id: None,
},
]
);
}
#[test]
fn description_ektoplazm() {
let testcases = [(
Album {
url: "https://ektoplazm.com/free-music/asdfasdf".to_string(),
artist: Some("Risingson".to_string()),
title: "Forgot".to_string(),
license: None,
year: None,
labels: vec![],
tags: vec![],
tracks: vec![],
youtube_id: None,
},
Track {
artist: "Risingson".to_string(),
title: "Digital Being".to_string(),
bpm: Some(88),
mp3_file: Some(PathBuf::from("01 - Risingson - Digital Being.mp3")),
video_file: None,
youtube_id: None,
},
"exp",
)];
for tc in &testcases {
println!("{}", description(&tc.0, &tc.1).unwrap());
}
}
}
|
pub struct Handler {}
impl Handler {
pub fn new() -> Handler {
Handler {}
}
}
|
#![crate_name="albino"]
#![crate_type="bin"]
#![feature(phase)]
#[phase(plugin, link)] extern crate log;
extern crate whitebase;
extern crate albino;
use std::os;
use std::io::process::{Command,InheritFd,ExitStatus,ExitSignal};
fn main() {
debug!("executing; cmd=albino; args={}", os::args());
let (cmd, args) = process(os::args());
match cmd.as_slice() {
"--help" | "-h" | "help" | "-?" => {
println!("Commands:");
println!(" build # compile the source code file");
println!(" exec # execute the bytecode file");
println!(" run # build and execute");
println!("");
}
"--version" | "-v" | "version" => {
println!("albino {}, whitebase {}", albino::version(), whitebase::version());
}
_ => {
let command = format!("albino-{}{}", cmd, os::consts::EXE_SUFFIX);
let mut command = match os::self_exe_path() {
Some(path) => {
let p = path.join(command.as_slice());
if p.exists() {
Command::new(p)
} else {
Command::new(command)
}
}
None => Command::new(command),
};
let command = command
.args(args.as_slice())
.stdin(InheritFd(0))
.stdout(InheritFd(1))
.stderr(InheritFd(2))
.status();
match command {
Ok(ExitStatus(0)) => (),
Ok(ExitStatus(i)) | Ok(ExitSignal(i)) => handle_error("", i),
Err(_) => handle_error("no such command.", 127),
}
}
}
}
fn process(args: Vec<String>) -> (String, Vec<String>) {
let mut args = Vec::from_slice(args.tail());
let head = args.shift().unwrap_or("--help".to_string());
(head, args)
}
fn handle_error<'a>(message: &'a str, exit: int) {
println!("{}", message);
os::set_exit_status(exit)
}
|
pub struct Physics {
pub x: f32,
pub y: f32,
pub vx: f32,
pub vy: f32,
}
pub fn inertia(dt: f32, physics: &mut Physics)
{
physics.x = position_wrapped_horizontal(physics.x, physics.vx, dt);
physics.y = position_wrapped_vertical (physics.y, physics.vy, dt);
}
fn position_wrapped_horizontal(x: f32, vx: f32, dt: f32) -> f32
{
(x + (vx * dt) + crate::ARENA_WIDTH) % crate::ARENA_WIDTH
}
fn position_wrapped_vertical(y: f32, vy: f32, dt: f32) -> f32
{
(y + (vy * dt) + crate::ARENA_HEIGHT) % crate::ARENA_HEIGHT
}
|
extern crate byteorder;
use std::*;
use self::byteorder::*;
pub struct Sha256 {
working_hash: [u32; 8],
total_data_len: u64,
tmp_data: [u8; 64],
tmp_data_len: usize,
hash: [u8; 32],
}
const K256: [u32; 64] = [
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2,
];
#[inline(always)]
fn sig0(val: u32) -> u32 {
u32::rotate_right(val, 7) ^ u32::rotate_right(val, 18) ^ (val >> 3)
}
#[inline(always)]
fn sig1(val: u32) -> u32 {
u32::rotate_right(val, 17) ^ u32::rotate_right(val, 19) ^ (val >> 10)
}
#[inline(always)]
fn ep0(val: u32) -> u32 {
u32::rotate_right(val, 2) ^ u32::rotate_right(val, 13) ^ u32::rotate_right(val, 22)
}
#[inline(always)]
fn ep1(val: u32) -> u32 {
u32::rotate_right(val, 6) ^ u32::rotate_right(val, 11) ^ u32::rotate_right(val, 25)
}
#[inline(always)]
fn ch(x: u32, y: u32, z: u32) -> u32 {
(x & y) ^ (!x & z)
}
#[inline(always)]
fn maj(x: u32, y: u32, z: u32) -> u32 {
(x & y) ^ (x & z) ^ (y & z)
}
impl Sha256 {
pub fn new() -> Sha256 {
Sha256 { working_hash: [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19,
],
total_data_len: 0,
tmp_data: [0; 64],
tmp_data_len: 0,
hash: [0; 32]}
}
fn hash_data(&mut self) {
let data: &[u8; 64] = &self.tmp_data;
let mut var: [u32; 8];
let mut t1: u32;
let mut t2: u32;
let mut m: [u32; 64] = [0; 64];
for i in 0..(64 / 4) {
m[i] = BigEndian::read_u32(&data[i * 4..i * 4 + 4]);
}
for i in 16..64 {
m[i] = sig1(m[i - 2])
.wrapping_add(m[i - 7])
.wrapping_add(sig0(m[i - 15]))
.wrapping_add(m[i - 16]);
}
var = self.working_hash;
for i in 0..64 {
t1 = var[7]
.wrapping_add(ep1(var[4]))
.wrapping_add(ch(var[4], var[5], var[6]))
.wrapping_add(K256[i])
.wrapping_add(m[i]);
t2 = ep0(var[0])
.wrapping_add(maj(var[0], var[1], var[2]));
var[7] = var[6];
var[6] = var[5];
var[5] = var[4];
var[4] = var[3].wrapping_add(t1);
var[3] = var[2];
var[2] = var[1];
var[1] = var[0];
var[0] = t1.wrapping_add(t2);
}
for i in 0..8 {
self.working_hash[i] = self.working_hash[i].wrapping_add(var[i]);
}
}
pub fn update(&mut self, data: &[u8]) {
self.total_data_len += data.len() as u64;
for d in data.iter() {
self.tmp_data[self.tmp_data_len] = *d;
self.tmp_data_len += 1;
if self.tmp_data_len == 64 {
self.hash_data();
self.tmp_data_len = 0;
}
}
}
pub fn finish<'a>(&'a mut self) -> &'a[u8; 32] {
if self.tmp_data_len < 56 {
self.tmp_data[self.tmp_data_len] = 0x80;
self.tmp_data_len += 1;
for i in self.tmp_data_len..56 {
self.tmp_data[i] = 0x00;
}
} else {
self.tmp_data[self.tmp_data_len] = 0x80;
self.tmp_data_len += 1;
for i in self.tmp_data_len..64 {
self.tmp_data[i] = 0x00;
}
self.hash_data();
self.tmp_data.clone_from_slice(&[0; 56]);
}
BigEndian::write_u64(&mut self.tmp_data[56..64], self.total_data_len * 8);
self.hash_data();
for i in 0..8 {
BigEndian::write_u32(&mut self.hash[i*4..i*4+4], self.working_hash[i]);
}
&self.hash
}
pub fn get_hash<'a>(&'a mut self) -> &'a[u8; 32] {
&self.hash
}
}
|
use super::control_handle::ControlHandle;
use crate::win32::{window_helper as wh, window::build_notice};
use crate::NwgError;
const NOT_BOUND: &'static str = "Notice is not yet bound to a winapi object";
const UNUSABLE_NOTICE: &'static str = "Notice parent window was freed";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Notice handle is not Notice!";
/**
An invisible component that can be triggered by other thread.
A notice object does not send data between threads. Rust has already plenty of way to do this.
The notice object only serve to "wake up" the GUI thread.
A notice must have a parent window. If the parent is destroyed before the notice, the notice becomes invalid.
Requires the `notice` feature.
## Example
```rust
use native_windows_gui as nwg;
fn build_notice(notice: &mut nwg::Notice, window: &nwg::Window) {
nwg::Notice::builder()
.parent(window)
.build(notice);
}
```
```rust
use native_windows_gui as nwg;
use std::thread;
use std::time;
fn notice(noticer: &nwg::Notice) {
let sender = noticer.sender();
thread::spawn(move || {
thread::sleep(time::Duration::new(5, 0));
sender.notice();
});
}
```
*/
#[derive(Default, PartialEq, Eq)]
pub struct Notice {
pub handle: ControlHandle
}
impl Notice {
pub fn builder() -> NoticeBuilder {
NoticeBuilder {
parent: None
}
}
/// A shortcut over the builder API for the notice object
pub fn create<C: Into<ControlHandle>>(parent: C) -> Result<Notice, NwgError> {
let mut notice = Self::default();
Self::builder()
.parent(parent)
.build(&mut notice)?;
Ok(notice)
}
/// Checks if the notice is still usable. A notice becomes unusable when the parent window is destroyed.
/// This will also return false if the notice is not initialized.
pub fn valid(&self) -> bool {
if self.handle.blank() { return false; }
let (hwnd, _) = self.handle.notice().expect(BAD_HANDLE);
wh::window_valid(hwnd)
}
/// Return an handle to the notice window or `None` if the window was destroyed.
pub fn window_handle(&self) -> Option<ControlHandle> {
match self.valid() {
true => Some(ControlHandle::Hwnd(self.handle.notice().unwrap().0)),
false => None
}
}
/// Change the parent window of the notice. This won't update the NoticeSender already created.
/// Panics if the control is not a window-like control or if the notice was not initialized
pub fn set_window_handle<C: Into<ControlHandle>>(&mut self, window: C) {
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let hwnd = window.into().hwnd().expect("New notice parent is not a window control");
let (_, id) = self.handle.notice().expect(BAD_HANDLE);
self.handle = ControlHandle::Notice(hwnd, id);
}
/// Create a new `NoticeSender` bound to this Notice
pub fn sender(&self) -> NoticeSender {
if self.handle.blank() { panic!("{}", NOT_BOUND); }
if !self.valid() { panic!("{}", UNUSABLE_NOTICE); }
let (hwnd, id) = self.handle.notice().expect(BAD_HANDLE);
NoticeSender {
hwnd: hwnd as usize,
id,
}
}
}
impl Drop for Notice {
fn drop(&mut self) {
self.handle.destroy();
}
}
/// NoticeSender sends message to its parent `Notice` from another thread
#[derive(Clone, Copy)]
pub struct NoticeSender {
hwnd: usize,
id: u32,
}
impl NoticeSender {
/// Send a message to the thread of the parent `Notice`
pub fn notice(&self) {
use winapi::um::winuser::SendNotifyMessageW;
use winapi::shared::minwindef::{WPARAM, LPARAM};
use winapi::shared::windef::HWND;
unsafe {
SendNotifyMessageW(self.hwnd as HWND, wh::NOTICE_MESSAGE, self.id as WPARAM, self.hwnd as LPARAM);
}
}
}
pub struct NoticeBuilder {
parent: Option<ControlHandle>
}
impl NoticeBuilder {
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> NoticeBuilder {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Notice) -> Result<(), NwgError> {
let parent = match self.parent {
Some(p) => match p.hwnd() {
Some(handle) => Ok(handle),
None => Err(NwgError::control_create("Wrong parent type"))
},
None => Err(NwgError::no_parent("Notice"))
}?;
out.handle = build_notice(parent);
Ok(())
}
}
|
use super::core::*;
use super::editor::*;
use super::notebook::*;
use super::super::host::*;
use desync::Desync;
use std::sync::*;
///
/// A script host for Gluon scripts
///
/// See [https://gluon-lang.org] for details on this language.
///
pub struct GluonScriptHost {
/// The core is used to execute the scripts asynchronously and process their results
core: Arc<Desync<GluonScriptHostCore>>
}
impl GluonScriptHost {
///
/// Creates a new Gluon script host with no scripts running
///
pub fn new() -> GluonScriptHost {
let core = GluonScriptHostCore::new();
GluonScriptHost {
core: Arc::new(Desync::new(core))
}
}
}
impl FloScriptHost for GluonScriptHost {
type Notebook = GluonScriptNotebook;
type Editor = GluonScriptEditor;
///
/// Retrieves the script notebook for this host
///
/// The notebook can be used to attach input streams to input symbols and retrieve output streams from scripts.
///
fn notebook(&self) -> Self::Notebook {
let root_namespace = self.core.sync(|core| core.root_namespace());
GluonScriptNotebook::new(root_namespace)
}
///
/// Retrieves the editor for this host
///
/// The editor can be used to define input symbols, scripts and namespaces
///
fn editor(&self) -> Self::Editor {
GluonScriptEditor::new(Arc::clone(&self.core))
}
}
|
/// Describes the types instruction and operands can take.
use crate::ir;
use serde::{Deserialize, Serialize};
use std::fmt;
use utils::*;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
/// Values and intructions types.
pub enum Type {
/// Type for integer values, with a fixed number of bits.
I(u16),
/// Type for floating point values, with a fixed number of bits.
F(u16),
/// Pointer type of the given memory space.
PtrTo(ir::MemId),
}
impl Type {
/// Returns true if the type is an integer.
pub fn is_integer(self) -> bool {
match self {
Type::I(_) | Type::PtrTo(_) => true,
Type::F(_) => false,
}
}
/// Returns true if the type is a float.
pub fn is_float(self) -> bool {
match self {
Type::F(_) => true,
Type::I(_) | Type::PtrTo(..) => false,
}
}
/// Return the number of bits of the type
pub fn bitwidth(self) -> Option<u32> {
match self {
Type::I(bits) | Type::F(bits) => Some(u32::from(bits)),
_ => None,
}
}
/// Returns the number of bytes of the type.
pub fn len_byte(self) -> Option<u32> {
self.bitwidth().map(|bits| div_ceil(bits, 8))
}
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Type::I(s) => write!(f, "i{}", s),
Type::F(s) => write!(f, "f{}", s),
Type::PtrTo(mem) => write!(f, "ptr to {:?}", mem),
}
}
}
|
pub struct Solution;
impl Solution {
pub fn add_digits(num: i32) -> i32 {
let mut num = num;
while num >= 10 {
let mut tmp = 0;
while num > 0 {
tmp += num % 10;
num /= 10;
}
num = tmp;
}
num
}
}
#[test]
fn test0258() {
fn case(num: i32, want: i32) {
let got = Solution::add_digits(num);
assert_eq!(got, want);
}
case(38, 2);
}
|
// 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.
/// An arena.
pub trait Arena<Holds>: Sized
{
/// Used to hold this arena instance.
///
/// The naive implementation is to Box this instance.
///
/// However, a more efficient strategy, particularly for large allocations, would be to use mmap or an unsized type.
///
/// If overriding `Self::drop_from_non_null()` make sure this is also overridden or memory leaks (or worse) will occur.
#[inline(always)]
fn to_non_null(self) -> NonNull<Self>
{
unsafe{ NonNull::new_unchecked(Box::into_raw(Box::new(self))) }
}
/// Used to drop an arena instance previously converted to a pointer with `Self::to_non_null()`.
///
/// The naive implementation is to un-Box this instance.
///
/// If overriding `Self::to_null_null()` make sure this is also overridden or memory leaks (or worse) will occur.
#[inline(always)]
fn drop_from_non_null(this: NonNull<Self>)
{
unsafe { drop(Box::from_raw(this.as_ptr())) }
}
/// Allocate a `Holds` within this arena.
///
/// The returned pointer should be considered uninitialized.
///
/// None is returned if allocation failed.
fn allocate(&self) -> Result<(NonNull<Holds>, ArenaIndex), ArenaAllocationError>;
/// Get a `Holds` within this arena.
fn get(&self, arena_index: ArenaIndex) -> &mut Holds;
/// Reclaim (drop, destroy or recycle) `Holds` within this arena.
fn reclaim(&self, arena_index: ArenaIndex);
}
|
extern crate serialize;
extern crate flate2;
extern crate curl;
extern crate tar;
use self::flate2::reader::GzDecoder;
use std::io::{BufReader, IoResult};
use self::tar::Archive;
use self::curl::http;
pub enum DowntarError {
HttpError,
UntarError
}
fn untar_stream (stream: BufReader, dest: &Path) -> IoResult<()> {
let mut gzipped = GzDecoder::new(stream);
let untar = try!(Archive::new(gzipped).unpack(dest));
Ok(())
}
pub fn download (url: String, dest: Path) -> Result<(), DowntarError> {
let res = match http::handle().get(url).exec() {
Ok(body) => body,
Err(_) => return Err(DowntarError::HttpError)
};
match untar_stream(BufReader::new(res.get_body()), &dest) {
Ok(_) => {},
Err(_) => return Err(DowntarError::UntarError)
};
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::fs;
#[test]
fn get_file () {
let url = "https://wiki.mozilla.org/images/f/ff/Example.json.gz";
super::download(url.to_string(), ".".to_string());
}
}
|
#[doc = "Reader of register IER"]
pub type R = crate::R<u32, super::IER>;
#[doc = "Writer for register IER"]
pub type W = crate::W<u32, super::IER>;
#[doc = "Register IER `reset()`'s with value 0"]
impl crate::ResetValue for super::IER {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TAMP1IE`"]
pub type TAMP1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP1IE`"]
pub struct TAMP1IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP1IE_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 `TAMP2IE`"]
pub type TAMP2IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP2IE`"]
pub struct TAMP2IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP2IE_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 `TAMP3IE`"]
pub type TAMP3IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP3IE`"]
pub struct TAMP3IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP3IE_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 `TAMP4IE`"]
pub type TAMP4IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP4IE`"]
pub struct TAMP4IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP4IE_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 `TAMP5IE`"]
pub type TAMP5IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP5IE`"]
pub struct TAMP5IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP5IE_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 `TAMP6IE`"]
pub type TAMP6IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP6IE`"]
pub struct TAMP6IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP6IE_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 `TAMP7IE`"]
pub type TAMP7IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP7IE`"]
pub struct TAMP7IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP7IE_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 `TAMP8IE`"]
pub type TAMP8IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMP8IE`"]
pub struct TAMP8IE_W<'a> {
w: &'a mut W,
}
impl<'a> TAMP8IE_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 `ITAMP1IE`"]
pub type ITAMP1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP1IE`"]
pub struct ITAMP1IE_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP1IE_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 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `ITAMP2IE`"]
pub type ITAMP2IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP2IE`"]
pub struct ITAMP2IE_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP2IE_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 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `ITAMP3IE`"]
pub type ITAMP3IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP3IE`"]
pub struct ITAMP3IE_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP3IE_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 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `ITAMP5IE`"]
pub type ITAMP5IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP5IE`"]
pub struct ITAMP5IE_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP5IE_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 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `ITAMP8IE`"]
pub type ITAMP8IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ITAMP8IE`"]
pub struct ITAMP8IE_W<'a> {
w: &'a mut W,
}
impl<'a> ITAMP8IE_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 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
impl R {
#[doc = "Bit 0 - TAMP1IE"]
#[inline(always)]
pub fn tamp1ie(&self) -> TAMP1IE_R {
TAMP1IE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - TAMP2IE"]
#[inline(always)]
pub fn tamp2ie(&self) -> TAMP2IE_R {
TAMP2IE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - TAMP3IE"]
#[inline(always)]
pub fn tamp3ie(&self) -> TAMP3IE_R {
TAMP3IE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - TAMP4IE"]
#[inline(always)]
pub fn tamp4ie(&self) -> TAMP4IE_R {
TAMP4IE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - TAMP5IE"]
#[inline(always)]
pub fn tamp5ie(&self) -> TAMP5IE_R {
TAMP5IE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - TAMP6IE"]
#[inline(always)]
pub fn tamp6ie(&self) -> TAMP6IE_R {
TAMP6IE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - TAMP7IE"]
#[inline(always)]
pub fn tamp7ie(&self) -> TAMP7IE_R {
TAMP7IE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - TAMP8IE"]
#[inline(always)]
pub fn tamp8ie(&self) -> TAMP8IE_R {
TAMP8IE_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 16 - ITAMP1IE"]
#[inline(always)]
pub fn itamp1ie(&self) -> ITAMP1IE_R {
ITAMP1IE_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - ITAMP2IE"]
#[inline(always)]
pub fn itamp2ie(&self) -> ITAMP2IE_R {
ITAMP2IE_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - ITAMP3IE"]
#[inline(always)]
pub fn itamp3ie(&self) -> ITAMP3IE_R {
ITAMP3IE_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 20 - ITAMP5IE"]
#[inline(always)]
pub fn itamp5ie(&self) -> ITAMP5IE_R {
ITAMP5IE_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 23 - ITAMP8IE"]
#[inline(always)]
pub fn itamp8ie(&self) -> ITAMP8IE_R {
ITAMP8IE_R::new(((self.bits >> 23) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TAMP1IE"]
#[inline(always)]
pub fn tamp1ie(&mut self) -> TAMP1IE_W {
TAMP1IE_W { w: self }
}
#[doc = "Bit 1 - TAMP2IE"]
#[inline(always)]
pub fn tamp2ie(&mut self) -> TAMP2IE_W {
TAMP2IE_W { w: self }
}
#[doc = "Bit 2 - TAMP3IE"]
#[inline(always)]
pub fn tamp3ie(&mut self) -> TAMP3IE_W {
TAMP3IE_W { w: self }
}
#[doc = "Bit 3 - TAMP4IE"]
#[inline(always)]
pub fn tamp4ie(&mut self) -> TAMP4IE_W {
TAMP4IE_W { w: self }
}
#[doc = "Bit 4 - TAMP5IE"]
#[inline(always)]
pub fn tamp5ie(&mut self) -> TAMP5IE_W {
TAMP5IE_W { w: self }
}
#[doc = "Bit 5 - TAMP6IE"]
#[inline(always)]
pub fn tamp6ie(&mut self) -> TAMP6IE_W {
TAMP6IE_W { w: self }
}
#[doc = "Bit 6 - TAMP7IE"]
#[inline(always)]
pub fn tamp7ie(&mut self) -> TAMP7IE_W {
TAMP7IE_W { w: self }
}
#[doc = "Bit 7 - TAMP8IE"]
#[inline(always)]
pub fn tamp8ie(&mut self) -> TAMP8IE_W {
TAMP8IE_W { w: self }
}
#[doc = "Bit 16 - ITAMP1IE"]
#[inline(always)]
pub fn itamp1ie(&mut self) -> ITAMP1IE_W {
ITAMP1IE_W { w: self }
}
#[doc = "Bit 17 - ITAMP2IE"]
#[inline(always)]
pub fn itamp2ie(&mut self) -> ITAMP2IE_W {
ITAMP2IE_W { w: self }
}
#[doc = "Bit 18 - ITAMP3IE"]
#[inline(always)]
pub fn itamp3ie(&mut self) -> ITAMP3IE_W {
ITAMP3IE_W { w: self }
}
#[doc = "Bit 20 - ITAMP5IE"]
#[inline(always)]
pub fn itamp5ie(&mut self) -> ITAMP5IE_W {
ITAMP5IE_W { w: self }
}
#[doc = "Bit 23 - ITAMP8IE"]
#[inline(always)]
pub fn itamp8ie(&mut self) -> ITAMP8IE_W {
ITAMP8IE_W { w: self }
}
}
|
use anyhow::{bail, Result};
use glacier::{TestResult, Outcome};
use rayon::prelude::*;
fn main() -> Result<()> {
let failed = glacier::test_all()?
.filter(|res| {
if let Ok(test) = res {
eprint!("{}", test.outcome_token());
test.outcome() != Outcome::ICEd
} else {
true
}
})
.collect::<Result<Vec<TestResult>, _>>()?;
for result in &failed {
eprintln!("\n{}", result);
}
match failed.len() {
0 => eprintln!("\nFinished: No fixed ICEs"),
len => bail!("{} ICEs are now fixed!", len)
}
Ok(())
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::{format_err, Error, Fail};
use fidl_fuchsia_auth::AuthProviderStatus;
use fidl_fuchsia_web::NavigationControllerError;
/// An extension trait to simplify conversion of results based on general errors to
/// AuthProviderErrors.
pub trait ResultExt<T, E> {
/// Wraps the error in an `AuthProviderError` with the supplied `AuthProviderStatus`.
fn auth_provider_status(self, status: AuthProviderStatus) -> Result<T, AuthProviderError>;
}
impl<T, E> ResultExt<T, E> for Result<T, E>
where
E: Into<Error> + Send + Sync + Sized,
{
fn auth_provider_status(self, status: AuthProviderStatus) -> Result<T, AuthProviderError> {
self.map_err(|err| AuthProviderError::new(status).with_cause(err))
}
}
/// An Error type for problems encountered in the auth provider. Each error contains the
/// `fuchsia.auth.AuthProviderStatus` that should be reported back to the client.
/// TODO(satsukiu): This is general across auth providers, once there are multiple
/// providers this should be moved out to a general crate.
#[derive(Debug, Fail)]
#[fail(display = "AuthProvider error, returning {:?}. ({:?})", status, cause)]
pub struct AuthProviderError {
/// The most appropriate `fuchsia.auth.AuthProviderStatus` to describe this problem.
pub status: AuthProviderStatus,
/// The cause of this error, if available.
pub cause: Option<Error>,
}
impl AuthProviderError {
/// Constructs a new non-fatal error based on the supplied `AuthProviderStatus`.
pub fn new(status: AuthProviderStatus) -> Self {
AuthProviderError { status, cause: None }
}
/// Sets a cause on the current error.
pub fn with_cause<T: Into<Error>>(mut self, cause: T) -> Self {
self.cause = Some(cause.into());
self
}
}
impl From<NavigationControllerError> for AuthProviderError {
fn from(navigation_error: NavigationControllerError) -> Self {
AuthProviderError {
status: match navigation_error {
NavigationControllerError::InvalidUrl
| NavigationControllerError::InvalidHeader => AuthProviderStatus::InternalError,
},
cause: Some(format_err!("Web browser navigation error: {:?}", navigation_error)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use failure::format_err;
#[test]
fn test_create_error() {
let error = AuthProviderError::new(AuthProviderStatus::UnknownError);
assert_eq!(error.status, AuthProviderStatus::UnknownError);
assert!(error.cause.is_none());
}
#[test]
fn test_with_cause() {
let error = AuthProviderError::new(AuthProviderStatus::UnknownError)
.with_cause(format_err!("cause"));
assert_eq!(error.status, AuthProviderStatus::UnknownError);
assert_eq!(format!("{:?}", error.cause.unwrap()), format!("{:?}", format_err!("cause")));
}
#[test]
fn test_result_ext() {
let result: Result<(), Error> = Err(format_err!("cause"));
let auth_provider_error =
result.auth_provider_status(AuthProviderStatus::InternalError).unwrap_err();
assert_eq!(auth_provider_error.status, AuthProviderStatus::InternalError);
assert_eq!(
format!("{:?}", auth_provider_error.cause.unwrap()),
format!("{:?}", format_err!("cause"))
);
}
#[test]
fn test_from_navigation_controller_error() {
let auth_provider_error = AuthProviderError::from(NavigationControllerError::InvalidUrl);
assert_eq!(auth_provider_error.status, AuthProviderStatus::InternalError);
assert!(auth_provider_error.cause.is_some());
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use super::column_stat::ColumnStatSet;
use crate::plans::ScalarExpr;
use crate::IndexType;
pub type ColumnSet = HashSet<IndexType>;
pub type TableSet = HashSet<IndexType>;
#[derive(Default, Clone, Debug)]
pub struct RequiredProperty {
pub distribution: Distribution,
}
impl RequiredProperty {
pub fn satisfied_by(&self, physical: &PhysicalProperty) -> bool {
self.distribution.satisfied_by(&physical.distribution)
}
}
#[derive(Default, Clone, Debug)]
pub struct Statistics {
// We can get the precise row count of a table in databend,
// which information is useful to optimize some queries like `COUNT(*)`.
pub precise_cardinality: Option<u64>,
/// Statistics of columns, column index -> column stat
pub column_stats: ColumnStatSet,
/// Statistics info is accurate
pub is_accurate: bool,
}
#[derive(Default, Clone, Debug)]
pub struct RelationalProperty {
/// Output columns of a relational expression
pub output_columns: ColumnSet,
/// Outer references of a relational expression
pub outer_columns: ColumnSet,
/// Used columns of a relational expression
pub used_columns: ColumnSet,
// TODO(leiysky): introduce upper bound of cardinality to
// reduce error in estimation.
pub cardinality: f64,
pub statistics: Statistics,
}
#[derive(Default, Clone)]
pub struct PhysicalProperty {
pub distribution: Distribution,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Distribution {
Any,
Random,
Serial,
Broadcast,
Hash(Vec<ScalarExpr>),
}
impl Default for Distribution {
// Only used for `RequiredProperty`
fn default() -> Self {
Self::Any
}
}
impl Distribution {
/// Check if required distribution is satisfied by given distribution.
pub fn satisfied_by(&self, distribution: &Distribution) -> bool {
// (required, delivered)
match (&self, distribution) {
(Distribution::Any, _)
| (Distribution::Random, _)
| (Distribution::Serial, Distribution::Serial)
| (Distribution::Broadcast, Distribution::Broadcast) => true,
// TODO(leiysky): this is actually broken by https://github.com/datafuselabs/databend/pull/7451
// , would be fixed later.
// (Distribution::Hash(ref keys), Distribution::Hash(ref other_keys)) => keys
// .iter()
// .all(|key| other_keys.iter().any(|other_key| key == other_key)),
_ => false,
}
}
}
|
//! Persistent fs backed repo.
//!
//! Consists of [`FsDataStore`] and [`FsBlockStore`].
use crate::error::Error;
use async_trait::async_trait;
use std::fs::File;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::Semaphore;
use super::{BlockRm, BlockRmError, Column, DataStore, Lock, LockError, RepoCid};
/// The PinStore implementation for FsDataStore
mod pinstore;
/// The FsBlockStore implementation
mod blocks;
pub use blocks::FsBlockStore;
/// Path mangling done for pins and blocks
mod paths;
use paths::{block_path, filestem_to_block_cid, filestem_to_pin_cid, pin_path};
/// FsDataStore which uses the filesystem as a lockable key-value store. Maintains a similar to
/// [`FsBlockStore`] sharded two level storage. Direct have empty files, recursive pins record all of
/// their indirect descendants. Pin files are separated by their file extensions.
///
/// When modifying, single lock is used.
///
/// For the [`crate::repo::PinStore`] implementation see `fs/pinstore.rs`.
#[derive(Debug)]
pub struct FsDataStore {
/// The base directory under which we have a sharded directory structure, and the individual
/// blocks are stored under the shard. See unixfs/examples/cat.rs for read example.
path: PathBuf,
/// Start with simple, conservative solution, allows concurrent queries but single writer.
/// It is assumed the reads do not require permit as non-empty writes are done through
/// tempfiles and the consistency regarding reads is not a concern right now. For garbage
/// collection implementation, it might be needed to hold this permit for the duration of
/// garbage collection, or something similar.
lock: Arc<Semaphore>,
}
/// The column operations are all unimplemented pending at least downscoping of the
/// DataStore trait itself.
#[async_trait]
impl DataStore for FsDataStore {
fn new(mut root: PathBuf) -> Self {
root.push("pins");
FsDataStore {
path: root,
lock: Arc::new(Semaphore::new(1)),
}
}
async fn init(&self) -> Result<(), Error> {
tokio::fs::create_dir_all(&self.path).await?;
Ok(())
}
async fn open(&self) -> Result<(), Error> {
Ok(())
}
async fn contains(&self, _col: Column, _key: &[u8]) -> Result<bool, Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn get(&self, _col: Column, _key: &[u8]) -> Result<Option<Vec<u8>>, Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn put(&self, _col: Column, _key: &[u8], _value: &[u8]) -> Result<(), Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn remove(&self, _col: Column, _key: &[u8]) -> Result<(), Error> {
Err(anyhow::anyhow!("not implemented"))
}
async fn wipe(&self) {
todo!()
}
}
#[derive(Debug)]
pub struct FsLock {
file: Option<File>,
path: PathBuf,
state: State,
}
#[derive(Debug)]
enum State {
Unlocked,
Exclusive,
}
impl Lock for FsLock {
fn new(path: PathBuf) -> Self {
Self {
file: None,
path,
state: State::Unlocked,
}
}
fn try_exclusive(&mut self) -> Result<(), LockError> {
use fs2::FileExt;
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&self.path)?;
file.try_lock_exclusive()?;
self.state = State::Exclusive;
self.file = Some(file);
Ok(())
}
}
#[cfg(test)]
crate::pinstore_interface_tests!(common_tests, crate::repo::fs::FsDataStore::new);
#[cfg(test)]
mod tests {
use super::{FsLock, Lock};
#[test]
fn creates_an_exclusive_repo_lock() {
let temp_dir = std::env::temp_dir();
let lockfile_path = temp_dir.join("repo_lock");
let mut lock = FsLock::new(lockfile_path.clone());
let result = lock.try_exclusive();
assert!(result.is_ok());
let mut failing_lock = FsLock::new(lockfile_path.clone());
let result = failing_lock.try_exclusive();
assert!(result.is_err());
// Clean-up.
std::fs::remove_file(lockfile_path).unwrap();
}
}
|
use serial::SerialPort;
use std::env;
use std::io::{Read, Write};
use std::net::UdpSocket;
const SETTINGS: serial::PortSettings = serial::PortSettings {
baud_rate: serial::Baud115200,
char_size: serial::Bits8,
parity: serial::ParityNone,
stop_bits: serial::Stop1,
flow_control: serial::FlowNone,
};
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().skip(1).collect();
if args.len() < 1 {
panic!("Please provide a serial port as argument (ex: /dev/ttyACM0)");
}
let serial_path = &args[0];
println!("Opening port: {:?}", serial_path);
let mut port = serial::open(&serial_path).unwrap();
port.configure(&SETTINGS).unwrap();
// TODO: set timeout?
let udp = UdpSocket::bind("127.0.0.1:49161")?;
loop {
// Receive the command via socket and display it.
let mut buf = [0; 10];
let (amt, _src) = udp.recv_from(&mut buf)?;
let buf = &buf[0..amt];
println!("received: {}", String::from_utf8_lossy(buf).to_owned());
let idx = dbg!(base36(dbg!(buf[0]))).unwrap_or(0);
let color = base36(buf[1]).unwrap_or(0);
// Write the command into the serial port.
let out_buf = [idx, color, color, color];
println!("{:?}", out_buf);
port.write_all(&out_buf)?;
port.flush()?;
// Read data from the serial port and display it.
let mut read_buf = [0; 10];
if let Ok(size) = port.read(&mut read_buf) {
println!("device sent: {:?}", &read_buf[0..size]);
}
}
}
/// Takes a character encoded in base64 and returns corresponding numeric value.
fn base36(value: u8) -> Option<u8> {
// The index of in the transpose table corresponds to the value encoded by the input.
const TRANSPOSE_TABLE_LOWER: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
const TRANSPOSE_TABLE_UPPER: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
TRANSPOSE_TABLE_LOWER
.iter()
.position(|&x| x == value)
.or_else(|| TRANSPOSE_TABLE_UPPER.iter().position(|&x| x == value))
.map(|x| x as u8)
}
|
//! This module contains code that "unpivots" annotated
//! [`RecordBatch`]es to [`Series`] and [`Group`]s for output by the
//! storage gRPC interface
use arrow::{
self,
array::{downcast_array, Array, BooleanArray, DictionaryArray, StringArray},
compute,
datatypes::{DataType, Int32Type, SchemaRef},
record_batch::RecordBatch,
};
use datafusion::{
error::DataFusionError,
execution::memory_pool::{proxy::VecAllocExt, MemoryConsumer, MemoryPool, MemoryReservation},
physical_plan::SendableRecordBatchStream,
};
use futures::{ready, Stream, StreamExt};
use predicate::rpc_predicate::{GROUP_KEY_SPECIAL_START, GROUP_KEY_SPECIAL_STOP};
use snafu::{OptionExt, Snafu};
use std::{
collections::VecDeque,
future::Future,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use crate::exec::{
field::{self, FieldColumns, FieldIndexes},
seriesset::series::Group,
};
use super::{
series::{Either, Series},
SeriesSet,
};
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("Internal field error while converting series set: {}", source))]
InternalField { source: field::Error },
#[snafu(display("Internal error finding grouping colum: {}", column_name))]
FindingGroupColumn { column_name: String },
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
// Handles converting record batches into SeriesSets
#[derive(Debug, Default)]
pub struct SeriesSetConverter {}
impl SeriesSetConverter {
/// Convert the results from running a DataFusion plan into the
/// appropriate SeriesSetItems.
///
/// The results must be in the logical format described in this
/// module's documentation (i.e. ordered by tag keys)
///
/// table_name: The name of the table
///
/// tag_columns: The names of the columns that define tags
///
/// field_columns: The names of the columns which are "fields"
///
/// it: record batch iterator that produces data in the desired order
pub async fn convert(
&mut self,
table_name: Arc<str>,
tag_columns: Arc<Vec<Arc<str>>>,
field_columns: FieldColumns,
it: SendableRecordBatchStream,
) -> Result<impl Stream<Item = Result<SeriesSet, DataFusionError>>, DataFusionError> {
assert_eq!(
tag_columns.as_ref(),
&{
let mut tmp = tag_columns.as_ref().clone();
tmp.sort();
tmp
},
"Tag column sorted",
);
let schema = it.schema();
let tag_indexes = FieldIndexes::names_to_indexes(&schema, &tag_columns).map_err(|e| {
DataFusionError::Context(
"Internal field error while converting series set".to_string(),
Box::new(DataFusionError::External(Box::new(e))),
)
})?;
let field_indexes =
FieldIndexes::from_field_columns(&schema, &field_columns).map_err(|e| {
DataFusionError::Context(
"Internal field error while converting series set".to_string(),
Box::new(DataFusionError::External(Box::new(e))),
)
})?;
Ok(SeriesSetConverterStream {
result_buffer: VecDeque::default(),
open_batches: Vec::default(),
need_new_batch: true,
we_finished: false,
schema,
it: Some(it),
tag_indexes,
field_indexes,
table_name,
tag_columns,
})
}
/// Returns the row indexes in `batch` where all of the values in the `tag_indexes` columns
/// take on a new value.
///
/// For example:
///
/// ```text
/// tags A, B
/// ```
///
/// If the input is:
///
/// A | B | C
/// - | - | -
/// 1 | 2 | x
/// 1 | 2 | y
/// 2 | 2 | z
/// 3 | 3 | q
/// 3 | 3 | r
///
/// Then this function will return `[3, 4]`:
///
/// - The row at index 3 has values for A and B (2,2) different than the previous row (1,2).
/// - Similarly the row at index 4 has values (3,3) which are different than (2,2).
/// - However, the row at index 5 has the same values (3,3) so is NOT a transition point
fn compute_changepoints(batch: &RecordBatch, tag_indexes: &[usize]) -> Vec<usize> {
let tag_transitions = tag_indexes
.iter()
.map(|&col| Self::compute_transitions(batch, col))
.collect::<Vec<_>>();
// no tag columns, emit a single tagset
if tag_transitions.is_empty() {
vec![]
} else {
// OR bitsets together to to find all rows where the
// keyset (values of the tag keys) changes
let mut tag_transitions_it = tag_transitions.into_iter();
let init = tag_transitions_it.next().expect("not empty");
let intersections =
tag_transitions_it.fold(init, |a, b| compute::or(&a, &b).expect("or operation"));
intersections
.iter()
.enumerate()
.filter(|(_idx, mask)| mask.unwrap_or(true))
.map(|(idx, _mask)| idx)
.collect()
}
}
/// returns a bitset with all row indexes where the value of the
/// batch `col_idx` changes. Does not include row 0, always includes
/// the last row, `batch.num_rows() - 1`
///
/// Note: This may return false positives in the presence of dictionaries
/// containing duplicates
fn compute_transitions(batch: &RecordBatch, col_idx: usize) -> BooleanArray {
let num_rows = batch.num_rows();
if num_rows == 0 {
return BooleanArray::builder(0).finish();
}
let col = batch.column(col_idx);
let arr = compute::concat(&[
&{
let mut b = BooleanArray::builder(1);
b.append_value(false);
b.finish()
},
&compute::neq_dyn(&col.slice(0, col.len() - 1), &col.slice(1, col.len() - 1))
.expect("cmp"),
])
.expect("concat");
downcast_array(&arr)
}
/// Creates (column_name, column_value) pairs for each column
/// named in `tag_column_name` at the corresponding index
/// `tag_indexes`
fn get_tag_keys(
batch: &RecordBatch,
row: usize,
tag_column_names: &[Arc<str>],
tag_indexes: &[usize],
) -> Vec<(Arc<str>, Arc<str>)> {
assert_eq!(tag_column_names.len(), tag_indexes.len());
let mut out = tag_column_names
.iter()
.zip(tag_indexes)
.filter_map(|(column_name, column_index)| {
let col = batch.column(*column_index);
let tag_value = match col.data_type() {
DataType::Utf8 => {
let col = col.as_any().downcast_ref::<StringArray>().unwrap();
if col.is_valid(row) {
Some(col.value(row).to_string())
} else {
None
}
}
DataType::Dictionary(key, value)
if key.as_ref() == &DataType::Int32
&& value.as_ref() == &DataType::Utf8 =>
{
let col = col
.as_any()
.downcast_ref::<DictionaryArray<Int32Type>>()
.expect("Casting column");
if col.is_valid(row) {
let key = col.keys().value(row);
let value = col
.values()
.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(key as _)
.to_string();
Some(value)
} else {
None
}
}
_ => unimplemented!(
"Series get_tag_keys not supported for type {:?} in column {:?}",
col.data_type(),
batch.schema().fields()[*column_index]
),
};
tag_value.map(|tag_value| (Arc::clone(column_name), Arc::from(tag_value.as_str())))
})
.collect::<Vec<_>>();
out.shrink_to_fit();
out
}
}
struct SeriesSetConverterStream {
/// [`SeriesSet`]s that are ready to be emitted by this stream.
///
/// These results must always be emitted before doing any additional work.
result_buffer: VecDeque<SeriesSet>,
/// Batches of data that have NO change point, i.e. they all belong to the same output set. However we have not yet
/// found the next change point (or the end of the stream) so we need to keep them.
///
/// We keep a list of batches instead of a giant concatenated batch to avoid `O(n^2)` complexity due to repeated mem-copies.
open_batches: Vec<RecordBatch>,
/// If `true`, we need to pull a new batch of `it`.
need_new_batch: bool,
/// We (i.e. [`SeriesSetConverterStream`]) completed its work. However there might be data available in
/// [`result_buffer`](Self::result_buffer) which must be drained before returning `Ready(None)`.
we_finished: bool,
/// The schema of the input data.
schema: SchemaRef,
/// Indexes (within [`schema`](Self::schema)) of the tag columns.
tag_indexes: Vec<usize>,
/// Indexes (within [`schema`](Self::schema)) of the field columns.
field_indexes: FieldIndexes,
/// Name of the table we're operating on.
///
/// This is required because this is part of the output [`SeriesSet`]s.
table_name: Arc<str>,
/// Name of the tag columns.
///
/// This is kept in addition to [`tag_indexes`](Self::tag_indexes) because it is part of the output [`SeriesSet`]s.
tag_columns: Arc<Vec<Arc<str>>>,
/// Input data stream.
///
///
/// This may be `None` when the stream was fully drained. We need to remember that fact so we don't pull a
/// finished stream (which may panic).
it: Option<SendableRecordBatchStream>,
}
impl Stream for SeriesSetConverterStream {
type Item = Result<SeriesSet, DataFusionError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = &mut *self;
loop {
// drain results
if let Some(sset) = this.result_buffer.pop_front() {
return Poll::Ready(Some(Ok(sset)));
}
// early exit
if this.we_finished {
return Poll::Ready(None);
}
// do we need more input data?
if this.need_new_batch {
loop {
match ready!(this
.it
.as_mut()
.expect("need new input but input stream is already drained")
.poll_next_unpin(cx))
{
Some(Err(e)) => {
return Poll::Ready(Some(Err(e)));
}
Some(Ok(batch)) => {
// skip empty batches (simplifies our code further down below because we can always assume that
// there's at least one row in the batch)
if batch.num_rows() == 0 {
continue;
}
this.open_batches.push(batch)
}
None => {
this.it = None;
}
}
break;
}
this.need_new_batch = false;
}
// do we only have a single batch or do we "overflow" from the last batch?
let (batch_for_changepoints, extra_first_row) = match this.open_batches.len() {
0 => {
assert!(
this.it.is_none(),
"We have no open batches left, so the input stream should be finished",
);
this.we_finished = true;
return Poll::Ready(None);
}
1 => (
this.open_batches.last().expect("checked length").clone(),
false,
),
_ => {
// `open_batches` contains at least two batches. The last one was added just from the input stream.
// The prev. one was the end of the "open" interval and all before that belong to the same output
// set (because otherwise we would have flushed them earlier).
let batch_last = &this.open_batches[this.open_batches.len() - 2];
let batch_current = &this.open_batches[this.open_batches.len() - 1];
assert!(batch_last.num_rows() > 0);
let batch = match compute::concat_batches(
&this.schema,
&[
batch_last.slice(batch_last.num_rows() - 1, 1),
batch_current.clone(),
],
) {
Ok(batch) => batch,
Err(e) => {
// internal state is broken, end this stream
this.we_finished = true;
return Poll::Ready(Some(Err(DataFusionError::ArrowError(e))));
}
};
(batch, true)
}
};
// compute changepoints
let mut changepoints = SeriesSetConverter::compute_changepoints(
&batch_for_changepoints,
&this.tag_indexes,
);
if this.it.is_none() {
// need to finish last SeriesSet
changepoints.push(batch_for_changepoints.num_rows());
}
let prev_sizes = this.open_batches[..(this.open_batches.len() - 1)]
.iter()
.map(|b| b.num_rows())
.sum::<usize>();
let cp_delta = if extra_first_row {
prev_sizes
.checked_sub(1)
.expect("at least one non-empty prev. batch")
} else {
prev_sizes
};
let changepoints = changepoints
.into_iter()
.map(|x| x + cp_delta)
.collect::<Vec<_>>();
// already change to "needs data" before we start emission
this.need_new_batch = true;
if this.it.is_none() {
this.we_finished = true;
}
if !changepoints.is_empty() {
// `batch_for_changepoints` only contains the last batch and the last row of the prev. one. However we
// need to flush ALL rows in `open_batches` (and keep the ones after the last changepoint as a new open
// batch). So concat again.
let batch_for_flush =
match compute::concat_batches(&this.schema, &this.open_batches) {
Ok(batch) => batch,
Err(e) => {
// internal state is broken, end this stream
this.we_finished = true;
return Poll::Ready(Some(Err(DataFusionError::ArrowError(e))));
}
};
let last_cp = *changepoints.last().expect("checked length");
if last_cp == batch_for_flush.num_rows() {
// fully drained open batches
// This can ONLY happen when the input stream finished because `comput_changepoint` never returns
// the last row as changepoint (so we must have manually added that above).
assert!(
this.it.is_none(),
"Fully flushed all open batches but the input stream still has data?!"
);
this.open_batches.drain(..);
} else {
// need to keep the open bit
// do NOT use `batch` here because it contains data for all open batches, we just need the last one
// (`slice` is zero-copy)
let offset = last_cp.checked_sub(prev_sizes).expect("underflow");
let last_batch = this.open_batches.last().expect("at least one batch");
let last_batch = last_batch.slice(
offset,
last_batch
.num_rows()
.checked_sub(offset)
.expect("underflow"),
);
this.open_batches.drain(..);
this.open_batches.push(last_batch);
}
// emit each series
let mut start_row: usize = 0;
assert!(this.result_buffer.is_empty());
this.result_buffer = changepoints
.into_iter()
.map(|end_row| {
let series_set = SeriesSet {
table_name: Arc::clone(&this.table_name),
tags: SeriesSetConverter::get_tag_keys(
&batch_for_flush,
start_row,
&this.tag_columns,
&this.tag_indexes,
),
field_indexes: this.field_indexes.clone(),
start_row,
num_rows: (end_row - start_row),
// batch clones are super cheap (in contrast to `slice` which has a way higher overhead!)
batch: batch_for_flush.clone(),
};
start_row = end_row;
series_set
})
.collect();
}
}
}
}
/// Reorders and groups a sequence of Series is grouped correctly
#[derive(Debug)]
pub struct GroupGenerator {
group_columns: Vec<Arc<str>>,
memory_pool: Arc<dyn MemoryPool>,
collector_buffered_size_max: usize,
}
impl GroupGenerator {
pub fn new(group_columns: Vec<Arc<str>>, memory_pool: Arc<dyn MemoryPool>) -> Self {
Self::new_with_buffered_size_max(
group_columns,
memory_pool,
Collector::<()>::DEFAULT_ALLOCATION_BUFFER_SIZE,
)
}
fn new_with_buffered_size_max(
group_columns: Vec<Arc<str>>,
memory_pool: Arc<dyn MemoryPool>,
collector_buffered_size_max: usize,
) -> Self {
Self {
group_columns,
memory_pool,
collector_buffered_size_max,
}
}
/// groups the set of `series` into SeriesOrGroups
///
/// TODO: make this truly stream-based, see <https://github.com/influxdata/influxdb_iox/issues/6347>.
pub async fn group<S>(
self,
series: S,
) -> Result<impl Stream<Item = Result<Either, DataFusionError>>, DataFusionError>
where
S: Stream<Item = Result<Series, DataFusionError>> + Send,
{
let series = Box::pin(series);
let mut series = Collector::new(
series,
self.group_columns,
self.memory_pool,
self.collector_buffered_size_max,
)
.await?;
// Potential optimization is to skip this sort if we are
// grouping by a prefix of the tags for a single measurement
//
// Another potential optimization is if we are only grouping on
// tag columns is to change the the actual plan output using
// DataFusion to sort the data in the required group (likely
// only possible with a single table)
// Resort the data according to group key values
series.sort();
// now find the groups boundaries and emit the output
let mut last_partition_key_vals: Option<Vec<Arc<str>>> = None;
// Note that if there are no group columns, we still need to
// sort by the tag keys, so that the output is sorted by tag
// keys, and thus we can't bail out early here
//
// Interesting, it isn't clear flux requires this ordering, but
// it is what TSM does so we preserve the behavior
let mut output = vec![];
// TODO make this more functional (issue is that sometimes the
// loop inserts one item into `output` and sometimes it inserts 2)
for SortableSeries {
series,
tag_vals,
num_partition_keys,
} in series.into_iter()
{
// keep only the values that form the group
let mut partition_key_vals = tag_vals;
partition_key_vals.truncate(num_partition_keys);
// figure out if we are in a new group (partition key values have changed)
let need_group_start = match &last_partition_key_vals {
None => true,
Some(last_partition_key_vals) => &partition_key_vals != last_partition_key_vals,
};
if need_group_start {
last_partition_key_vals = Some(partition_key_vals.clone());
let tag_keys = series.tags.iter().map(|tag| Arc::clone(&tag.key)).collect();
let group = Group {
tag_keys,
partition_key_vals,
};
output.push(group.into());
}
output.push(series.into())
}
Ok(futures::stream::iter(output).map(Ok))
}
}
#[derive(Debug)]
/// Wrapper around a Series that has the values of the group_by columns extracted
struct SortableSeries {
series: Series,
/// All the tag values, reordered so that the group_columns are first
tag_vals: Vec<Arc<str>>,
/// How many of the first N tag_values are used for the partition key
num_partition_keys: usize,
}
impl PartialEq for SortableSeries {
fn eq(&self, other: &Self) -> bool {
self.tag_vals.eq(&other.tag_vals)
}
}
impl Eq for SortableSeries {}
impl PartialOrd for SortableSeries {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.tag_vals.partial_cmp(&other.tag_vals)
}
}
impl Ord for SortableSeries {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.tag_vals.cmp(&other.tag_vals)
}
}
impl SortableSeries {
fn try_new(series: Series, group_columns: &[Arc<str>]) -> Result<Self> {
// Compute the order of new tag values
let tags = &series.tags;
// tag_used_set[i] is true if we have used the value in tag_columns[i]
let mut tag_used_set = vec![false; tags.len()];
// put the group columns first
//
// Note that this is an O(N^2) algorithm. We are assuming the
// number of tag columns is reasonably small
let mut tag_vals: Vec<_> = group_columns
.iter()
.map(|col| {
tags.iter()
.enumerate()
// Searching for columns linearly is likely to be pretty slow....
.find(|(_i, tag)| tag.key == *col)
.map(|(i, tag)| {
assert!(!tag_used_set[i], "repeated group column");
tag_used_set[i] = true;
Arc::clone(&tag.value)
})
.or_else(|| {
// treat these specially and use value "" to mirror what TSM does
// see https://github.com/influxdata/influxdb_iox/issues/2693#issuecomment-947695442
// for more details
if col.as_ref() == GROUP_KEY_SPECIAL_START
|| col.as_ref() == GROUP_KEY_SPECIAL_STOP
{
Some(Arc::from(""))
} else {
None
}
})
.context(FindingGroupColumnSnafu {
column_name: col.as_ref(),
})
})
.collect::<Result<Vec<_>>>()?;
// Fill in all remaining tags
tag_vals.extend(tags.iter().enumerate().filter_map(|(i, tag)| {
let use_tag = !tag_used_set[i];
use_tag.then(|| Arc::clone(&tag.value))
}));
// safe memory
tag_vals.shrink_to_fit();
Ok(Self {
series,
tag_vals,
num_partition_keys: group_columns.len(),
})
}
/// Memory usage in bytes, including `self`.
fn size(&self) -> usize {
std::mem::size_of_val(self) + self.series.size() - std::mem::size_of_val(&self.series)
+ (std::mem::size_of::<Arc<str>>() * self.tag_vals.capacity())
+ self.tag_vals.iter().map(|s| s.len()).sum::<usize>()
}
}
/// [`Future`] that collects [`Series`] objects into a [`SortableSeries`] vector while registering/checking memory
/// allocations with a [`MemoryPool`].
///
/// This avoids unbounded memory growth when merging multiple `Series` in memory
struct Collector<S> {
/// The inner stream was fully drained.
inner_done: bool,
/// This very future finished.
outer_done: bool,
/// Inner stream.
inner: S,
/// Group columns.
///
/// These are required for [`SortableSeries::try_new`].
group_columns: Vec<Arc<str>>,
/// Already collected objects.
collected: Vec<SortableSeries>,
/// Buffered but not-yet-registered allocated size.
///
/// We use an additional buffer here because in contrast to the normal DataFusion processing, the input stream is
/// NOT batched and we want to avoid costly memory allocations checks with the [`MemoryPool`] for every single element.
buffered_size: usize,
/// Maximum [buffered size](Self::buffered_size). Decreasing this
/// value causes allocations to be reported to the [`MemoryPool`]
/// more frequently.
buffered_size_max: usize,
/// Our memory reservation.
mem_reservation: MemoryReservation,
}
impl<S> Collector<S> {
/// Default maximum [buffered size](Self::buffered_size) before updating [`MemoryPool`] reservation
const DEFAULT_ALLOCATION_BUFFER_SIZE: usize = 1024 * 1024;
}
impl<S> Collector<S>
where
S: Stream<Item = Result<Series, DataFusionError>> + Send + Unpin,
{
fn new(
inner: S,
group_columns: Vec<Arc<str>>,
memory_pool: Arc<dyn MemoryPool>,
buffered_size_max: usize,
) -> Self {
let mem_reservation = MemoryConsumer::new("SeriesSet Collector").register(&memory_pool);
Self {
inner_done: false,
outer_done: false,
inner,
group_columns,
collected: Vec::with_capacity(0),
buffered_size: 0,
buffered_size_max,
mem_reservation,
}
}
/// Registers all `self.buffered_size` with the MemoryPool,
/// resetting self.buffered_size to zero. Returns an error if new
/// memory can not be allocated from the pool.
fn alloc(&mut self) -> Result<(), DataFusionError> {
let bytes = std::mem::take(&mut self.buffered_size);
self.mem_reservation.try_grow(bytes)
}
}
impl<S> Future for Collector<S>
where
S: Stream<Item = Result<Series, DataFusionError>> + Send + Unpin,
{
type Output = Result<Vec<SortableSeries>, DataFusionError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = &mut *self;
loop {
assert!(!this.outer_done);
// if the underlying stream is drained and the allocation future is ready (see above), we can finalize this future
if this.inner_done {
this.outer_done = true;
return Poll::Ready(Ok(std::mem::take(&mut this.collected)));
}
match ready!(this.inner.poll_next_unpin(cx)) {
Some(Ok(series)) => match SortableSeries::try_new(series, &this.group_columns) {
Ok(series) => {
// Note: the size of `SortableSeries` itself is already included in the vector allocation
this.buffered_size += series.size() - std::mem::size_of_val(&series);
this.collected
.push_accounted(series, &mut this.buffered_size);
// should we clear our allocation buffer?
if this.buffered_size > this.buffered_size_max {
if let Err(e) = this.alloc() {
return Poll::Ready(Err(e));
}
continue;
}
}
Err(e) => {
// poison this future
this.outer_done = true;
return Poll::Ready(Err(DataFusionError::External(Box::new(e))));
}
},
Some(Err(e)) => {
// poison this future
this.outer_done = true;
return Poll::Ready(Err(e));
}
None => {
// underlying stream drained. now register the final allocation and then we're done
this.inner_done = true;
if this.buffered_size > 0 {
if let Err(e) = this.alloc() {
return Poll::Ready(Err(e));
}
}
continue;
}
}
}
}
}
#[cfg(test)]
mod tests {
use arrow::{
array::{ArrayRef, Float64Array, Int64Array, TimestampNanosecondArray},
csv,
datatypes::DataType,
datatypes::Field,
datatypes::{Schema, SchemaRef},
record_batch::RecordBatch,
};
use arrow_util::assert_batches_eq;
use assert_matches::assert_matches;
use datafusion::execution::memory_pool::GreedyMemoryPool;
use datafusion_util::{stream_from_batch, stream_from_batches, stream_from_schema};
use futures::TryStreamExt;
use itertools::Itertools;
use test_helpers::str_vec_to_arc_vec;
use crate::exec::seriesset::series::{Batch, Data, Tag};
use super::*;
#[tokio::test]
async fn test_convert_empty() {
let schema = test_schema();
let empty_iterator = stream_from_schema(schema);
let table_name = "foo";
let tag_columns = [];
let field_columns = [];
let results = convert(table_name, &tag_columns, &field_columns, empty_iterator).await;
assert_eq!(results.len(), 0);
}
fn test_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("tag_a", DataType::Utf8, true),
Field::new("tag_b", DataType::Utf8, true),
Field::new("float_field", DataType::Float64, true),
Field::new("int_field", DataType::Int64, true),
Field::new("time", DataType::Int64, false),
]))
}
#[tokio::test]
async fn test_convert_single_series_no_tags() {
// single series
let schema = test_schema();
let inputs = parse_to_iterators(schema, &["one,ten,10.0,1,1000", "one,ten,10.1,2,2000"]);
for (i, input) in inputs.into_iter().enumerate() {
println!("Stream {i}");
let table_name = "foo";
let tag_columns = [];
let field_columns = ["float_field"];
let results = convert(table_name, &tag_columns, &field_columns, input).await;
assert_eq!(results.len(), 1);
assert_series_set(
&results[0],
"foo",
[],
FieldIndexes::from_timestamp_and_value_indexes(4, &[2]),
[
"+-------+-------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+-------+-------------+-----------+------+",
"| one | ten | 10.0 | 1 | 1000 |",
"| one | ten | 10.1 | 2 | 2000 |",
"+-------+-------+-------------+-----------+------+",
],
);
}
}
#[tokio::test]
async fn test_convert_single_series_no_tags_nulls() {
// single series
let schema = test_schema();
let inputs = parse_to_iterators(schema, &["one,ten,10.0,,1000", "one,ten,10.1,,2000"]);
// send no values in the int_field colum
for (i, input) in inputs.into_iter().enumerate() {
println!("Stream {i}");
let table_name = "foo";
let tag_columns = [];
let field_columns = ["float_field"];
let results = convert(table_name, &tag_columns, &field_columns, input).await;
assert_eq!(results.len(), 1);
assert_series_set(
&results[0],
"foo",
[],
FieldIndexes::from_timestamp_and_value_indexes(4, &[2]),
[
"+-------+-------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+-------+-------------+-----------+------+",
"| one | ten | 10.0 | | 1000 |",
"| one | ten | 10.1 | | 2000 |",
"+-------+-------+-------------+-----------+------+",
],
);
}
}
#[tokio::test]
async fn test_convert_single_series_one_tag() {
// single series
let schema = test_schema();
let inputs = parse_to_iterators(schema, &["one,ten,10.0,1,1000", "one,ten,10.1,2,2000"]);
for (i, input) in inputs.into_iter().enumerate() {
println!("Stream {i}");
// test with one tag column, one series
let table_name = "bar";
let tag_columns = ["tag_a"];
let field_columns = ["float_field"];
let results = convert(table_name, &tag_columns, &field_columns, input).await;
assert_eq!(results.len(), 1);
assert_series_set(
&results[0],
"bar",
[("tag_a", "one")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[2]),
[
"+-------+-------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+-------+-------------+-----------+------+",
"| one | ten | 10.0 | 1 | 1000 |",
"| one | ten | 10.1 | 2 | 2000 |",
"+-------+-------+-------------+-----------+------+",
],
);
}
}
#[tokio::test]
async fn test_convert_single_series_one_tag_more_rows() {
// single series
let schema = test_schema();
let inputs = parse_to_iterators(
schema,
&[
"one,ten,10.0,1,1000",
"one,ten,10.1,2,2000",
"one,ten,10.2,3,3000",
],
);
for (i, input) in inputs.into_iter().enumerate() {
println!("Stream {i}");
// test with one tag column, one series
let table_name = "bar";
let tag_columns = ["tag_a"];
let field_columns = ["float_field"];
let results = convert(table_name, &tag_columns, &field_columns, input).await;
assert_eq!(results.len(), 1);
assert_series_set(
&results[0],
"bar",
[("tag_a", "one")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[2]),
[
"+-------+-------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+-------+-------------+-----------+------+",
"| one | ten | 10.0 | 1 | 1000 |",
"| one | ten | 10.1 | 2 | 2000 |",
"| one | ten | 10.2 | 3 | 3000 |",
"+-------+-------+-------------+-----------+------+",
],
);
}
}
#[tokio::test]
async fn test_convert_one_tag_multi_series() {
let schema = test_schema();
let inputs = parse_to_iterators(
schema,
&[
"one,ten,10.0,1,1000",
"one,ten,10.1,2,2000",
"one,eleven,10.1,3,3000",
"two,eleven,10.2,4,4000",
"two,eleven,10.3,5,5000",
],
);
for (i, input) in inputs.into_iter().enumerate() {
println!("Stream {i}");
let table_name = "foo";
let tag_columns = ["tag_a"];
let field_columns = ["int_field"];
let results = convert(table_name, &tag_columns, &field_columns, input).await;
assert_eq!(results.len(), 2);
assert_series_set(
&results[0],
"foo",
[("tag_a", "one")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[3]),
[
"+-------+--------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+--------+-------------+-----------+------+",
"| one | ten | 10.0 | 1 | 1000 |",
"| one | ten | 10.1 | 2 | 2000 |",
"| one | eleven | 10.1 | 3 | 3000 |",
"+-------+--------+-------------+-----------+------+",
],
);
assert_series_set(
&results[1],
"foo",
[("tag_a", "two")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[3]),
[
"+-------+--------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+--------+-------------+-----------+------+",
"| two | eleven | 10.2 | 4 | 4000 |",
"| two | eleven | 10.3 | 5 | 5000 |",
"+-------+--------+-------------+-----------+------+",
],
);
}
}
// two tag columns, three series
#[tokio::test]
async fn test_convert_two_tag_multi_series() {
let schema = test_schema();
let inputs = parse_to_iterators(
schema,
&[
"one,ten,10.0,1,1000",
"one,ten,10.1,2,2000",
"one,eleven,10.1,3,3000",
"two,eleven,10.2,4,4000",
"two,eleven,10.3,5,5000",
],
);
for (i, input) in inputs.into_iter().enumerate() {
println!("Stream {i}");
let table_name = "foo";
let tag_columns = ["tag_a", "tag_b"];
let field_columns = ["int_field"];
let results = convert(table_name, &tag_columns, &field_columns, input).await;
assert_eq!(results.len(), 3);
assert_series_set(
&results[0],
"foo",
[("tag_a", "one"), ("tag_b", "ten")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[3]),
[
"+-------+-------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+-------+-------------+-----------+------+",
"| one | ten | 10.0 | 1 | 1000 |",
"| one | ten | 10.1 | 2 | 2000 |",
"+-------+-------+-------------+-----------+------+",
],
);
assert_series_set(
&results[1],
"foo",
[("tag_a", "one"), ("tag_b", "eleven")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[3]),
[
"+-------+--------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+--------+-------------+-----------+------+",
"| one | eleven | 10.1 | 3 | 3000 |",
"+-------+--------+-------------+-----------+------+",
],
);
assert_series_set(
&results[2],
"foo",
[("tag_a", "two"), ("tag_b", "eleven")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[3]),
[
"+-------+--------+-------------+-----------+------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+--------+-------------+-----------+------+",
"| two | eleven | 10.2 | 4 | 4000 |",
"| two | eleven | 10.3 | 5 | 5000 |",
"+-------+--------+-------------+-----------+------+",
],
);
}
}
#[tokio::test]
async fn test_convert_two_tag_with_null_multi_series() {
let tag_a = StringArray::from(vec!["one", "one", "one"]);
let tag_b = StringArray::from(vec![Some("ten"), Some("ten"), None]);
let float_field = Float64Array::from(vec![10.0, 10.1, 10.1]);
let int_field = Int64Array::from(vec![1, 2, 3]);
let time = TimestampNanosecondArray::from(vec![1000, 2000, 3000]);
let batch = RecordBatch::try_from_iter_with_nullable(vec![
("tag_a", Arc::new(tag_a) as ArrayRef, true),
("tag_b", Arc::new(tag_b), true),
("float_field", Arc::new(float_field), true),
("int_field", Arc::new(int_field), true),
("time", Arc::new(time), false),
])
.unwrap();
// Input has one row that has no value (NULL value) for tag_b, which is its own series
let input = stream_from_batch(batch.schema(), batch);
let table_name = "foo";
let tag_columns = ["tag_a", "tag_b"];
let field_columns = ["int_field"];
let results = convert(table_name, &tag_columns, &field_columns, input).await;
assert_eq!(results.len(), 2);
assert_series_set(
&results[0],
"foo",
[("tag_a", "one"), ("tag_b", "ten")],
FieldIndexes::from_timestamp_and_value_indexes(4, &[3]),
[
"+-------+-------+-------------+-----------+-----------------------------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+-------+-------------+-----------+-----------------------------+",
"| one | ten | 10.0 | 1 | 1970-01-01T00:00:00.000001Z |",
"| one | ten | 10.1 | 2 | 1970-01-01T00:00:00.000002Z |",
"+-------+-------+-------------+-----------+-----------------------------+",
],
);
assert_series_set(
&results[1],
"foo",
[("tag_a", "one")], // note no value for tag_b, only one tag
FieldIndexes::from_timestamp_and_value_indexes(4, &[3]),
[
"+-------+-------+-------------+-----------+-----------------------------+",
"| tag_a | tag_b | float_field | int_field | time |",
"+-------+-------+-------------+-----------+-----------------------------+",
"| one | | 10.1 | 3 | 1970-01-01T00:00:00.000003Z |",
"+-------+-------+-------------+-----------+-----------------------------+",
],
);
}
/// Test helper: run conversion and return a Vec
pub async fn convert<'a>(
table_name: &'a str,
tag_columns: &'a [&'a str],
field_columns: &'a [&'a str],
it: SendableRecordBatchStream,
) -> Vec<SeriesSet> {
let mut converter = SeriesSetConverter::default();
let table_name = Arc::from(table_name);
let tag_columns = Arc::new(str_vec_to_arc_vec(tag_columns));
let field_columns = FieldColumns::from(field_columns);
converter
.convert(table_name, tag_columns, field_columns, it)
.await
.expect("Conversion happened without error")
.try_collect()
.await
.expect("Conversion happened without error")
}
/// Test helper: parses the csv content into a single record batch arrow
/// arrays columnar ArrayRef according to the schema
fn parse_to_record_batch(schema: SchemaRef, data: &str) -> RecordBatch {
if data.is_empty() {
return RecordBatch::new_empty(schema);
}
let batch_size = 1000;
let mut reader = csv::ReaderBuilder::new(schema)
.with_batch_size(batch_size)
.build_buffered(data.as_bytes())
.unwrap();
let first_batch = reader.next().expect("Reading first batch");
assert!(
first_batch.is_ok(),
"Can not parse record batch from csv: {first_batch:?}"
);
assert!(
reader.next().is_none(),
"Unexpected batch while parsing csv"
);
println!("batch: \n{first_batch:#?}");
first_batch.unwrap()
}
/// Parses a set of CSV lines into several `RecordBatchStream`s of varying sizes
///
/// For example, with three input lines:
/// line1
/// line2
/// line3
///
/// This will produce two output streams:
/// Stream1: (line1), (line2), (line3)
/// Stream2: (line1, line2), (line3)
fn parse_to_iterators(schema: SchemaRef, lines: &[&str]) -> Vec<SendableRecordBatchStream> {
split_lines(lines)
.into_iter()
.map(|batches| {
let batches = batches
.into_iter()
.map(|chunk| parse_to_record_batch(Arc::clone(&schema), &chunk))
.collect::<Vec<_>>();
stream_from_batches(Arc::clone(&schema), batches)
})
.collect()
}
fn split_lines(lines: &[&str]) -> Vec<Vec<String>> {
println!("** Input data:\n{lines:#?}\n\n");
if lines.is_empty() {
return vec![vec![], vec![String::from("")]];
}
// potential split points for batches
// we keep each split point twice so we may also produce empty batches
let n_lines = lines.len();
let mut split_points = (0..=n_lines).chain(0..=n_lines).collect::<Vec<_>>();
split_points.sort();
let mut split_point_sets = split_points
.into_iter()
.powerset()
.map(|mut split_points| {
split_points.sort();
// ensure that "begin" and "end" are always split points
if split_points.first() != Some(&0) {
split_points.insert(0, 0);
}
if split_points.last() != Some(&n_lines) {
split_points.push(n_lines);
}
split_points
})
.collect::<Vec<_>>();
split_point_sets.sort();
let variants = split_point_sets
.into_iter()
.unique()
.map(|split_points| {
let batches = split_points
.into_iter()
.tuple_windows()
.map(|(begin, end)| lines[begin..end].join("\n"))
.collect::<Vec<_>>();
// stream from those batches
assert!(!batches.is_empty());
batches
})
.collect::<Vec<_>>();
assert!(!variants.is_empty());
variants
}
#[test]
fn test_split_lines() {
assert_eq!(split_lines(&[]), vec![vec![], vec![String::from("")],],);
assert_eq!(
split_lines(&["foo"]),
vec![
vec![String::from(""), String::from("foo")],
vec![String::from(""), String::from("foo"), String::from("")],
vec![String::from("foo")],
vec![String::from("foo"), String::from("")],
],
);
assert_eq!(
split_lines(&["foo", "bar"]),
vec![
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar")
],
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar"),
String::from("")
],
vec![String::from(""), String::from("foo"), String::from("bar")],
vec![
String::from(""),
String::from("foo"),
String::from("bar"),
String::from("")
],
vec![String::from(""), String::from("foo\nbar")],
vec![String::from(""), String::from("foo\nbar"), String::from("")],
vec![String::from("foo"), String::from(""), String::from("bar")],
vec![
String::from("foo"),
String::from(""),
String::from("bar"),
String::from("")
],
vec![String::from("foo"), String::from("bar")],
vec![String::from("foo"), String::from("bar"), String::from("")],
vec![String::from("foo\nbar")],
vec![String::from("foo\nbar"), String::from("")],
],
);
assert_eq!(
split_lines(&["foo", "bar", "xxx"]),
vec![
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar"),
String::from(""),
String::from("xxx")
],
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar"),
String::from(""),
String::from("xxx"),
String::from("")
],
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar"),
String::from("xxx")
],
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar"),
String::from("xxx"),
String::from("")
],
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar\nxxx")
],
vec![
String::from(""),
String::from("foo"),
String::from(""),
String::from("bar\nxxx"),
String::from("")
],
vec![
String::from(""),
String::from("foo"),
String::from("bar"),
String::from(""),
String::from("xxx")
],
vec![
String::from(""),
String::from("foo"),
String::from("bar"),
String::from(""),
String::from("xxx"),
String::from("")
],
vec![
String::from(""),
String::from("foo"),
String::from("bar"),
String::from("xxx")
],
vec![
String::from(""),
String::from("foo"),
String::from("bar"),
String::from("xxx"),
String::from("")
],
vec![
String::from(""),
String::from("foo"),
String::from("bar\nxxx")
],
vec![
String::from(""),
String::from("foo"),
String::from("bar\nxxx"),
String::from("")
],
vec![
String::from(""),
String::from("foo\nbar"),
String::from(""),
String::from("xxx")
],
vec![
String::from(""),
String::from("foo\nbar"),
String::from(""),
String::from("xxx"),
String::from("")
],
vec![
String::from(""),
String::from("foo\nbar"),
String::from("xxx")
],
vec![
String::from(""),
String::from("foo\nbar"),
String::from("xxx"),
String::from("")
],
vec![String::from(""), String::from("foo\nbar\nxxx")],
vec![
String::from(""),
String::from("foo\nbar\nxxx"),
String::from("")
],
vec![
String::from("foo"),
String::from(""),
String::from("bar"),
String::from(""),
String::from("xxx")
],
vec![
String::from("foo"),
String::from(""),
String::from("bar"),
String::from(""),
String::from("xxx"),
String::from("")
],
vec![
String::from("foo"),
String::from(""),
String::from("bar"),
String::from("xxx")
],
vec![
String::from("foo"),
String::from(""),
String::from("bar"),
String::from("xxx"),
String::from("")
],
vec![
String::from("foo"),
String::from(""),
String::from("bar\nxxx")
],
vec![
String::from("foo"),
String::from(""),
String::from("bar\nxxx"),
String::from("")
],
vec![
String::from("foo"),
String::from("bar"),
String::from(""),
String::from("xxx")
],
vec![
String::from("foo"),
String::from("bar"),
String::from(""),
String::from("xxx"),
String::from("")
],
vec![
String::from("foo"),
String::from("bar"),
String::from("xxx")
],
vec![
String::from("foo"),
String::from("bar"),
String::from("xxx"),
String::from("")
],
vec![String::from("foo"), String::from("bar\nxxx")],
vec![
String::from("foo"),
String::from("bar\nxxx"),
String::from("")
],
vec![
String::from("foo\nbar"),
String::from(""),
String::from("xxx")
],
vec![
String::from("foo\nbar"),
String::from(""),
String::from("xxx"),
String::from("")
],
vec![String::from("foo\nbar"), String::from("xxx")],
vec![
String::from("foo\nbar"),
String::from("xxx"),
String::from("")
],
vec![String::from("foo\nbar\nxxx")],
vec![String::from("foo\nbar\nxxx"), String::from("")]
]
);
}
#[tokio::test]
async fn test_group_generator_mem_limit() {
let memory_pool = Arc::new(GreedyMemoryPool::new(1)) as _;
let ggen = GroupGenerator::new(vec![Arc::from("g")], memory_pool);
let input = futures::stream::iter([Ok(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("x"),
}],
data: Data::FloatPoints(vec![Batch {
timestamps: vec![],
values: vec![],
}]),
})]);
let err = match ggen.group(input).await {
Ok(stream) => stream.try_collect::<Vec<_>>().await.unwrap_err(),
Err(e) => e,
};
assert_matches!(err, DataFusionError::ResourcesExhausted(_));
}
#[tokio::test]
async fn test_group_generator_no_mem_limit() {
let memory_pool = Arc::new(GreedyMemoryPool::new(usize::MAX)) as _;
// use a generator w/ a low buffered allocation to force multiple `alloc` calls
let ggen = GroupGenerator::new_with_buffered_size_max(vec![Arc::from("g")], memory_pool, 1);
let input = futures::stream::iter([
Ok(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("x"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![1],
values: vec![1],
}]),
}),
Ok(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("y"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![2],
values: vec![2],
}]),
}),
Ok(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("x"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![3],
values: vec![3],
}]),
}),
Ok(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("x"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![4],
values: vec![4],
}]),
}),
]);
let actual = ggen
.group(input)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let expected = vec![
Either::Group(Group {
tag_keys: vec![Arc::from("g")],
partition_key_vals: vec![Arc::from("x")],
}),
Either::Series(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("x"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![1],
values: vec![1],
}]),
}),
Either::Series(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("x"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![3],
values: vec![3],
}]),
}),
Either::Series(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("x"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![4],
values: vec![4],
}]),
}),
Either::Group(Group {
tag_keys: vec![Arc::from("g")],
partition_key_vals: vec![Arc::from("y")],
}),
Either::Series(Series {
tags: vec![Tag {
key: Arc::from("g"),
value: Arc::from("y"),
}],
data: Data::IntegerPoints(vec![Batch {
timestamps: vec![2],
values: vec![2],
}]),
}),
];
assert_eq!(actual, expected);
}
fn assert_series_set<const N: usize, const M: usize>(
set: &SeriesSet,
table_name: &'static str,
tags: [(&'static str, &'static str); N],
field_indexes: FieldIndexes,
data: [&'static str; M],
) {
assert_eq!(set.table_name.as_ref(), table_name);
let set_tags = set
.tags
.iter()
.map(|(a, b)| (a.as_ref(), b.as_ref()))
.collect::<Vec<_>>();
assert_eq!(set_tags.as_slice(), tags);
assert_eq!(set.field_indexes, field_indexes);
assert_batches_eq!(data, &[set.batch.slice(set.start_row, set.num_rows)]);
}
}
|
pub mod structs;
pub fn new_command(command: structs::CommandType, data: &str) -> structs::Command {
structs::Command {
command: command,
data: String::from(data)
}
}
|
use {
crate::{
controls::{ControlBindings, PlayerControlBundle},
state::MainMenuState,
systems::{CubeSystem, ViewBobbingSystem},
terrain::render::ChunkRenderMesherSystem,
ui::CursorGrabBundle,
},
rough::{
amethyst::{
self,
assets::PrefabLoaderSystemDesc,
controls::HideCursor,
core::{frame_limiter::FrameRateLimitStrategy, TransformBundle},
input::InputBundle,
prelude::*,
renderer::{
plugins::{RenderPbr3D, RenderToWindow},
rendy::mesh::{Normal, Position, TexCoord},
types::DefaultBackend,
RenderingBundle,
},
ui::{RenderUi, UiBundle},
utils::scene::BasicScenePrefab,
},
chrono,
performance::FrameRateSystem,
physics::PhysicsSystem,
serde_yaml,
state::{RoughGameDataBuilder, RoughGameDispatcherBuilder, RoughState},
terrain::ChunkMapSystem,
},
std::{fs::File, io::BufReader, path::PathBuf, time::Duration},
};
#[macro_use]
extern crate rough;
type MyBasicScenePrefab = BasicScenePrefab<(Vec<Position>, Vec<Normal>, Vec<TexCoord>)>;
mod controls;
mod state;
mod systems;
mod terrain;
mod ui;
fn start_logger(config_path: PathBuf) {
let config_file = File::open(&config_path).unwrap();
let mut config_reader = BufReader::new(config_file);
let config = serde_yaml::from_reader(&mut config_reader).unwrap();
amethyst::Logger::from_config_formatter(config, |out, message, record| {
out.finish(format_args!(
"{} [{level}] [{target}] {message}",
chrono::Local::now().format("%F %T%.6f %:z"),
level = record.level(),
target = record.target(),
message = message,
))
})
.start();
}
fn main() -> amethyst::Result<()> {
// assumes running from project root
let app_root = std::env::current_dir()?.join("rough_client");
let assets_dir = app_root.join("assets");
let display_config_path = app_root.join("config/display.ron");
let key_bindings_path = app_root.join("config/control_bindings.ron");
start_logger(app_root.join("config/logger.yaml"));
let mut game_builder = Application::build(assets_dir, MainMenuState::new().adapt())?
.with_fixed_step_length(Duration::from_millis(50))
.with_frame_limit(
FrameRateLimitStrategy::SleepAndYield(Duration::from_millis(2)),
60,
);
// insert this here because other systems require it
game_builder.world.insert(HideCursor::default());
let game_data = RoughGameDataBuilder {
// Universal pre-dispatch systems
pre_dispatcher_builder: RoughGameDispatcherBuilder::default()
.with_system_desc(
&mut game_builder.world,
PrefabLoaderSystemDesc::<MyBasicScenePrefab>::default(),
"",
&[],
)
.with_bundle(&mut game_builder.world, TransformBundle::new())?
.with_bundle(
&mut game_builder.world,
InputBundle::<ControlBindings>::new()
.with_bindings_from_file(&key_bindings_path)?,
)?
.with_bundle(&mut game_builder.world, CursorGrabBundle::new())?
.with_bundle(&mut game_builder.world, UiBundle::<ControlBindings>::new())?,
// Universal post-dispatch systems
post_dispatcher_builder: RoughGameDispatcherBuilder::default()
.with_bundle(
&mut game_builder.world,
RenderingBundle::<DefaultBackend>::new()
.with_plugin(
RenderToWindow::from_config_path(display_config_path)?
.with_clear([0.34, 0.36, 0.52, 1.0]),
)
.with_plugin(RenderPbr3D::default())
.with_plugin(RenderUi::default()),
)?
.add_barrier()
// run performance-tracking systems at the end of the loop
.with_system(FrameRateSystem, FrameRateSystem::NAME, &[]),
// Main game state systems
main_game_dispatcher_builder: RoughGameDispatcherBuilder::default()
.with_bundle(&mut game_builder.world, PlayerControlBundle)?
.add_barrier()
.with_system(PhysicsSystem, PhysicsSystem::NAME, &[])
.add_barrier()
.with_system(ViewBobbingSystem, ViewBobbingSystem::NAME, &[])
.with_system(ChunkMapSystem, ChunkMapSystem::NAME, &[])
.with_system(CubeSystem, CubeSystem::NAME, &[])
.with_system(
ChunkRenderMesherSystem,
ChunkRenderMesherSystem::NAME,
&[ChunkMapSystem::NAME],
),
};
let mut game = game_builder.build(game_data)?;
game.run();
Ok(())
}
|
use chrono::Duration;
use histogram::Histogram;
use request_result::RequestResult;
pub struct RunInfo {
/// Number of requests successfully completed
pub requests_completed: usize,
pub duration: Duration,
pub histogram: Histogram,
/// Number of failed requests
pub num_failed_requests: usize,
}
impl RunInfo {
pub fn new(duration: Duration) -> Self {
RunInfo {
requests_completed: 0,
num_failed_requests: 0,
duration: duration,
histogram: Histogram::new(),
}
}
pub fn requests_per_second(&self) -> f32 {
(self.requests_completed as f32) / (self.duration.num_seconds() as f32)
}
pub fn add_request(&mut self, request: &RequestResult) {
use request_result::RequestResult::*;
match *request {
Success { latency } => {
self.requests_completed += 1;
// update histogram
latency.num_nanoseconds()
.map(|x| self.histogram.increment(x as u64).ok());
}
Failure => {
self.num_failed_requests += 1;
}
}
}
pub fn merge(&mut self, other: &Self) {
self.requests_completed += other.requests_completed;
self.num_failed_requests += other.num_failed_requests;
self.histogram.merge(&other.histogram);
}
}
|
#![allow(unused_variables)]
#![allow(unused_imports)]
use std::env;
fn main()
{
let args: env::Args = env::args();
println!("test");
}
|
#![feature(ascii_ctype)]
use std::ascii::AsciiExt;
pub fn rotate(s: &str, shift: u8) -> String {
s.chars().map(|c| rotate_char(c, shift)).collect()
}
fn rotate_char(c: char, shift: u8) -> char {
if !c.is_ascii_alphabetic() {
return c;
}
let offset = if c.is_ascii_lowercase() { 97 } else { 65 };
(offset + ((c as u8 - offset + shift) % 26)) as char
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Globalization_Collation")]
pub mod Collation;
#[cfg(feature = "Globalization_DateTimeFormatting")]
pub mod DateTimeFormatting;
#[cfg(feature = "Globalization_Fonts")]
pub mod Fonts;
#[cfg(feature = "Globalization_NumberFormatting")]
pub mod NumberFormatting;
#[cfg(feature = "Globalization_PhoneNumberFormatting")]
pub mod PhoneNumberFormatting;
pub struct ApplicationLanguages {}
impl ApplicationLanguages {
pub fn PrimaryLanguageOverride() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IApplicationLanguagesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SetPrimaryLanguageOverride<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(value: Param0) -> ::windows::core::Result<()> {
Self::IApplicationLanguagesStatics(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() })
}
#[cfg(feature = "Foundation_Collections")]
pub fn Languages() -> ::windows::core::Result<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
Self::IApplicationLanguagesStatics(|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::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
})
}
#[cfg(feature = "Foundation_Collections")]
pub fn ManifestLanguages() -> ::windows::core::Result<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
Self::IApplicationLanguagesStatics(|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::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
})
}
#[cfg(all(feature = "Foundation_Collections", feature = "System"))]
pub fn GetLanguagesForUser<'a, Param0: ::windows::core::IntoParam<'a, super::System::User>>(user: Param0) -> ::windows::core::Result<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
Self::IApplicationLanguagesStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), user.into_param().abi(), &mut result__).from_abi::<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
})
}
pub fn IApplicationLanguagesStatics<R, F: FnOnce(&IApplicationLanguagesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ApplicationLanguages, IApplicationLanguagesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IApplicationLanguagesStatics2<R, F: FnOnce(&IApplicationLanguagesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ApplicationLanguages, IApplicationLanguagesStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for ApplicationLanguages {
const NAME: &'static str = "Windows.Globalization.ApplicationLanguages";
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct Calendar(pub ::windows::core::IInspectable);
impl Calendar {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Calendar, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn Clone(&self) -> ::windows::core::Result<Calendar> {
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::<Calendar>(result__)
}
}
pub fn SetToMin(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this)).ok() }
}
pub fn SetToMax(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Languages(&self) -> ::windows::core::Result<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
pub fn NumeralSystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetNumeralSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn GetCalendarSystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ChangeCalendarSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn GetClock(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ChangeClock<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn GetDateTime(&self) -> ::windows::core::Result<super::Foundation::DateTime> {
let this = self;
unsafe {
let mut result__: super::Foundation::DateTime = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Foundation::DateTime>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetDateTime<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::DateTime>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn SetToNow(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this)).ok() }
}
pub fn FirstEra(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastEra(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfEras(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn Era(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetEra(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddEras(&self, eras: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), eras).ok() }
}
pub fn EraAsFullString(&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).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn EraAsString(&self, ideallength: i32) -> ::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).26)(::core::mem::transmute_copy(this), ideallength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FirstYearInThisEra(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastYearInThisEra(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfYearsInThisEra(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn Year(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetYear(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddYears(&self, years: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), years).ok() }
}
pub fn YearAsString(&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).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn YearAsTruncatedString(&self, remainingdigits: i32) -> ::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).34)(::core::mem::transmute_copy(this), remainingdigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn YearAsPaddedString(&self, mindigits: i32) -> ::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).35)(::core::mem::transmute_copy(this), mindigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FirstMonthInThisYear(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).36)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastMonthInThisYear(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).37)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfMonthsInThisYear(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).38)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn Month(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).39)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetMonth(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).40)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddMonths(&self, months: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).41)(::core::mem::transmute_copy(this), months).ok() }
}
pub fn MonthAsFullString(&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).42)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn MonthAsString(&self, ideallength: i32) -> ::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).43)(::core::mem::transmute_copy(this), ideallength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn MonthAsFullSoloString(&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).44)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn MonthAsSoloString(&self, ideallength: i32) -> ::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).45)(::core::mem::transmute_copy(this), ideallength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn MonthAsNumericString(&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).46)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn MonthAsPaddedNumericString(&self, mindigits: i32) -> ::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).47)(::core::mem::transmute_copy(this), mindigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn AddWeeks(&self, weeks: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).48)(::core::mem::transmute_copy(this), weeks).ok() }
}
pub fn FirstDayInThisMonth(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).49)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastDayInThisMonth(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).50)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfDaysInThisMonth(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).51)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn Day(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).52)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetDay(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).53)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddDays(&self, days: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).54)(::core::mem::transmute_copy(this), days).ok() }
}
pub fn DayAsString(&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).55)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DayAsPaddedString(&self, mindigits: i32) -> ::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).56)(::core::mem::transmute_copy(this), mindigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DayOfWeek(&self) -> ::windows::core::Result<DayOfWeek> {
let this = self;
unsafe {
let mut result__: DayOfWeek = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).57)(::core::mem::transmute_copy(this), &mut result__).from_abi::<DayOfWeek>(result__)
}
}
pub fn DayOfWeekAsFullString(&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).58)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DayOfWeekAsString(&self, ideallength: i32) -> ::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).59)(::core::mem::transmute_copy(this), ideallength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DayOfWeekAsFullSoloString(&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).60)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DayOfWeekAsSoloString(&self, ideallength: i32) -> ::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).61)(::core::mem::transmute_copy(this), ideallength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FirstPeriodInThisDay(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).62)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastPeriodInThisDay(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).63)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfPeriodsInThisDay(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).64)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn Period(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).65)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetPeriod(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).66)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddPeriods(&self, periods: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).67)(::core::mem::transmute_copy(this), periods).ok() }
}
pub fn PeriodAsFullString(&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).68)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn PeriodAsString(&self, ideallength: i32) -> ::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).69)(::core::mem::transmute_copy(this), ideallength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FirstHourInThisPeriod(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).70)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastHourInThisPeriod(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).71)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfHoursInThisPeriod(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).72)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn Hour(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).73)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetHour(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).74)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddHours(&self, hours: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).75)(::core::mem::transmute_copy(this), hours).ok() }
}
pub fn HourAsString(&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).76)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn HourAsPaddedString(&self, mindigits: i32) -> ::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).77)(::core::mem::transmute_copy(this), mindigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Minute(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).78)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetMinute(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).79)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddMinutes(&self, minutes: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).80)(::core::mem::transmute_copy(this), minutes).ok() }
}
pub fn MinuteAsString(&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).81)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn MinuteAsPaddedString(&self, mindigits: i32) -> ::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).82)(::core::mem::transmute_copy(this), mindigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Second(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).83)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetSecond(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).84)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddSeconds(&self, seconds: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).85)(::core::mem::transmute_copy(this), seconds).ok() }
}
pub fn SecondAsString(&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).86)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SecondAsPaddedString(&self, mindigits: i32) -> ::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).87)(::core::mem::transmute_copy(this), mindigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Nanosecond(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).88)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetNanosecond(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).89)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddNanoseconds(&self, nanoseconds: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).90)(::core::mem::transmute_copy(this), nanoseconds).ok() }
}
pub fn NanosecondAsString(&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).91)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn NanosecondAsPaddedString(&self, mindigits: i32) -> ::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).92)(::core::mem::transmute_copy(this), mindigits, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Compare<'a, Param0: ::windows::core::IntoParam<'a, Calendar>>(&self, other: Param0) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).93)(::core::mem::transmute_copy(this), other.into_param().abi(), &mut result__).from_abi::<i32>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn CompareDateTime<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::DateTime>>(&self, other: Param0) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).94)(::core::mem::transmute_copy(this), other.into_param().abi(), &mut result__).from_abi::<i32>(result__)
}
}
pub fn CopyTo<'a, Param0: ::windows::core::IntoParam<'a, Calendar>>(&self, other: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).95)(::core::mem::transmute_copy(this), other.into_param().abi()).ok() }
}
pub fn FirstMinuteInThisHour(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).96)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastMinuteInThisHour(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).97)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfMinutesInThisHour(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).98)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn FirstSecondInThisMinute(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).99)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn LastSecondInThisMinute(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).100)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn NumberOfSecondsInThisMinute(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).101)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn ResolvedLanguage(&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).102)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IsDaylightSavingTime(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).103)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn GetTimeZone(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ITimeZoneOnCalendar>(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 ChangeTimeZone<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, timezoneid: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITimeZoneOnCalendar>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), timezoneid.into_param().abi()).ok() }
}
pub fn TimeZoneAsFullString(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ITimeZoneOnCalendar>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn TimeZoneAsString(&self, ideallength: i32) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ITimeZoneOnCalendar>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), ideallength, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreateCalendarDefaultCalendarAndClock<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(languages: Param0) -> ::windows::core::Result<Calendar> {
Self::ICalendarFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languages.into_param().abi(), &mut result__).from_abi::<Calendar>(result__)
})
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreateCalendar<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languages: Param0, calendar: Param1, clock: Param2) -> ::windows::core::Result<Calendar> {
Self::ICalendarFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), languages.into_param().abi(), calendar.into_param().abi(), clock.into_param().abi(), &mut result__).from_abi::<Calendar>(result__)
})
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreateCalendarWithTimeZone<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languages: Param0, calendar: Param1, clock: Param2, timezoneid: Param3) -> ::windows::core::Result<Calendar> {
Self::ICalendarFactory2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languages.into_param().abi(), calendar.into_param().abi(), clock.into_param().abi(), timezoneid.into_param().abi(), &mut result__).from_abi::<Calendar>(result__)
})
}
pub fn ICalendarFactory<R, F: FnOnce(&ICalendarFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Calendar, ICalendarFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ICalendarFactory2<R, F: FnOnce(&ICalendarFactory2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Calendar, ICalendarFactory2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for Calendar {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.Calendar;{ca30221d-86d9-40fb-a26b-d44eb7cf08ea})");
}
unsafe impl ::windows::core::Interface for Calendar {
type Vtable = ICalendar_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca30221d_86d9_40fb_a26b_d44eb7cf08ea);
}
impl ::windows::core::RuntimeName for Calendar {
const NAME: &'static str = "Windows.Globalization.Calendar";
}
impl ::core::convert::From<Calendar> for ::windows::core::IUnknown {
fn from(value: Calendar) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&Calendar> for ::windows::core::IUnknown {
fn from(value: &Calendar) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for Calendar {
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 Calendar {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<Calendar> for ::windows::core::IInspectable {
fn from(value: Calendar) -> Self {
value.0
}
}
impl ::core::convert::From<&Calendar> for ::windows::core::IInspectable {
fn from(value: &Calendar) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for Calendar {
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 Calendar {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for Calendar {}
unsafe impl ::core::marker::Sync for Calendar {}
pub struct CalendarIdentifiers {}
impl CalendarIdentifiers {
pub fn Gregorian() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Hebrew() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Hijri() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Japanese() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Julian() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Korean() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Taiwan() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Thai() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn UmAlQura() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Persian() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ChineseLunar() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn JapaneseLunar() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KoreanLunar() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TaiwanLunar() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn VietnameseLunar() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICalendarIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ICalendarIdentifiersStatics<R, F: FnOnce(&ICalendarIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CalendarIdentifiers, ICalendarIdentifiersStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ICalendarIdentifiersStatics2<R, F: FnOnce(&ICalendarIdentifiersStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CalendarIdentifiers, ICalendarIdentifiersStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ICalendarIdentifiersStatics3<R, F: FnOnce(&ICalendarIdentifiersStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CalendarIdentifiers, ICalendarIdentifiersStatics3> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for CalendarIdentifiers {
const NAME: &'static str = "Windows.Globalization.CalendarIdentifiers";
}
pub struct ClockIdentifiers {}
impl ClockIdentifiers {
pub fn TwelveHour() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IClockIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TwentyFourHour() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IClockIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IClockIdentifiersStatics<R, F: FnOnce(&IClockIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ClockIdentifiers, IClockIdentifiersStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for ClockIdentifiers {
const NAME: &'static str = "Windows.Globalization.ClockIdentifiers";
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct CurrencyAmount(pub ::windows::core::IInspectable);
impl CurrencyAmount {
pub fn Amount(&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 Currency(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(amount: Param0, currency: Param1) -> ::windows::core::Result<CurrencyAmount> {
Self::ICurrencyAmountFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), amount.into_param().abi(), currency.into_param().abi(), &mut result__).from_abi::<CurrencyAmount>(result__)
})
}
pub fn ICurrencyAmountFactory<R, F: FnOnce(&ICurrencyAmountFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CurrencyAmount, ICurrencyAmountFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for CurrencyAmount {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.CurrencyAmount;{74b49942-eb75-443a-95b3-7d723f56f93c})");
}
unsafe impl ::windows::core::Interface for CurrencyAmount {
type Vtable = ICurrencyAmount_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x74b49942_eb75_443a_95b3_7d723f56f93c);
}
impl ::windows::core::RuntimeName for CurrencyAmount {
const NAME: &'static str = "Windows.Globalization.CurrencyAmount";
}
impl ::core::convert::From<CurrencyAmount> for ::windows::core::IUnknown {
fn from(value: CurrencyAmount) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&CurrencyAmount> for ::windows::core::IUnknown {
fn from(value: &CurrencyAmount) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CurrencyAmount {
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 CurrencyAmount {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<CurrencyAmount> for ::windows::core::IInspectable {
fn from(value: CurrencyAmount) -> Self {
value.0
}
}
impl ::core::convert::From<&CurrencyAmount> for ::windows::core::IInspectable {
fn from(value: &CurrencyAmount) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CurrencyAmount {
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 CurrencyAmount {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for CurrencyAmount {}
unsafe impl ::core::marker::Sync for CurrencyAmount {}
pub struct CurrencyIdentifiers {}
impl CurrencyIdentifiers {
pub fn AED() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AFN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ALL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AMD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ANG() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AOA() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ARS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AUD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AWG() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AZN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BAM() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BBD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BDT() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BGN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BHD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BIF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BMD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BND() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BOB() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BRL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BSD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BTN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BWP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BYR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BZD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CAD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CDF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CHF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CLP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CNY() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).35)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn COP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).36)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CRC() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).37)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CUP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).38)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CVE() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).39)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn CZK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).40)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn DJF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).41)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn DKK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).42)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn DOP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).43)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn DZD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).44)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn EGP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).45)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ERN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).46)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ETB() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).47)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn EUR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).48)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn FJD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).49)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn FKP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).50)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GBP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).51)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GEL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).52)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GHS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).53)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GIP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).54)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GMD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).55)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GNF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).56)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GTQ() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).57)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GYD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).58)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn HKD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).59)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn HNL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).60)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn HRK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).61)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn HTG() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).62)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn HUF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).63)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IDR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).64)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ILS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).65)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn INR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).66)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IQD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).67)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IRR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).68)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ISK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).69)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn JMD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).70)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn JOD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).71)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn JPY() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).72)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KES() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).73)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KGS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).74)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KHR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).75)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KMF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).76)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KPW() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).77)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KRW() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).78)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KWD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).79)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KYD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).80)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn KZT() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).81)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LAK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).82)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LBP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).83)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LKR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).84)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LRD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).85)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LSL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).86)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LTL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).87)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LVL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).88)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LYD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).89)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MAD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).90)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MDL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).91)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MGA() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).92)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MKD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).93)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MMK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).94)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MNT() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).95)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MOP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).96)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MRO() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).97)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MUR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).98)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MVR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).99)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MWK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).100)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MXN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).101)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MYR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).102)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MZN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).103)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn NAD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).104)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn NGN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).105)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn NIO() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).106)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn NOK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).107)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn NPR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).108)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn NZD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).109)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn OMR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).110)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn PAB() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).111)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn PEN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).112)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn PGK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).113)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn PHP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).114)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn PKR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).115)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn PLN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).116)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn PYG() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).117)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn QAR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).118)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn RON() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).119)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn RSD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).120)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn RUB() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).121)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn RWF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).122)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SAR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).123)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SBD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).124)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SCR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).125)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SDG() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).126)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SEK() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).127)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SGD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).128)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SHP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).129)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SLL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).130)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SOS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).131)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SRD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).132)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn STD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).133)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SYP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).134)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SZL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).135)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn THB() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).136)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TJS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).137)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TMT() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).138)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TND() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).139)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TOP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).140)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TRY() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).141)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TTD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).142)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TWD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).143)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TZS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).144)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn UAH() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).145)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn UGX() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).146)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn USD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).147)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn UYU() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).148)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn UZS() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).149)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn VEF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).150)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn VND() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).151)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn VUV() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).152)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn WST() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).153)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn XAF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).154)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn XCD() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).155)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn XOF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).156)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn XPF() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).157)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn XXX() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).158)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn YER() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).159)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZAR() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).160)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZMW() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).161)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZWL() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).162)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn BYN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MRU() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn SSP() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn STN() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn VES() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ICurrencyIdentifiersStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ICurrencyIdentifiersStatics<R, F: FnOnce(&ICurrencyIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CurrencyIdentifiers, ICurrencyIdentifiersStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ICurrencyIdentifiersStatics2<R, F: FnOnce(&ICurrencyIdentifiersStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CurrencyIdentifiers, ICurrencyIdentifiersStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ICurrencyIdentifiersStatics3<R, F: FnOnce(&ICurrencyIdentifiersStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CurrencyIdentifiers, ICurrencyIdentifiersStatics3> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for CurrencyIdentifiers {
const NAME: &'static str = "Windows.Globalization.CurrencyIdentifiers";
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DayOfWeek(pub i32);
impl DayOfWeek {
pub const Sunday: DayOfWeek = DayOfWeek(0i32);
pub const Monday: DayOfWeek = DayOfWeek(1i32);
pub const Tuesday: DayOfWeek = DayOfWeek(2i32);
pub const Wednesday: DayOfWeek = DayOfWeek(3i32);
pub const Thursday: DayOfWeek = DayOfWeek(4i32);
pub const Friday: DayOfWeek = DayOfWeek(5i32);
pub const Saturday: DayOfWeek = DayOfWeek(6i32);
}
impl ::core::convert::From<i32> for DayOfWeek {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DayOfWeek {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for DayOfWeek {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Globalization.DayOfWeek;i4)");
}
impl ::windows::core::DefaultType for DayOfWeek {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct GeographicRegion(pub ::windows::core::IInspectable);
impl GeographicRegion {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<GeographicRegion, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn Code(&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 CodeTwoLetter(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn CodeThreeLetter(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn CodeThreeDigit(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn NativeName(&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).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn CurrenciesInUse(&self) -> ::windows::core::Result<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
pub fn CreateGeographicRegion<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(geographicregioncode: Param0) -> ::windows::core::Result<GeographicRegion> {
Self::IGeographicRegionFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), geographicregioncode.into_param().abi(), &mut result__).from_abi::<GeographicRegion>(result__)
})
}
pub fn IsSupported<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(geographicregioncode: Param0) -> ::windows::core::Result<bool> {
Self::IGeographicRegionStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), geographicregioncode.into_param().abi(), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IGeographicRegionFactory<R, F: FnOnce(&IGeographicRegionFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<GeographicRegion, IGeographicRegionFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IGeographicRegionStatics<R, F: FnOnce(&IGeographicRegionStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<GeographicRegion, IGeographicRegionStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for GeographicRegion {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.GeographicRegion;{01e9a621-4a64-4ed9-954f-9edeb07bd903})");
}
unsafe impl ::windows::core::Interface for GeographicRegion {
type Vtable = IGeographicRegion_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x01e9a621_4a64_4ed9_954f_9edeb07bd903);
}
impl ::windows::core::RuntimeName for GeographicRegion {
const NAME: &'static str = "Windows.Globalization.GeographicRegion";
}
impl ::core::convert::From<GeographicRegion> for ::windows::core::IUnknown {
fn from(value: GeographicRegion) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&GeographicRegion> for ::windows::core::IUnknown {
fn from(value: &GeographicRegion) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GeographicRegion {
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 GeographicRegion {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<GeographicRegion> for ::windows::core::IInspectable {
fn from(value: GeographicRegion) -> Self {
value.0
}
}
impl ::core::convert::From<&GeographicRegion> for ::windows::core::IInspectable {
fn from(value: &GeographicRegion) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GeographicRegion {
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 GeographicRegion {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for GeographicRegion {}
unsafe impl ::core::marker::Sync for GeographicRegion {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IApplicationLanguagesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IApplicationLanguagesStatics {
type Vtable = IApplicationLanguagesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x75b40847_0a4c_4a92_9565_fd63c95f7aed);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplicationLanguagesStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IApplicationLanguagesStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IApplicationLanguagesStatics2 {
type Vtable = IApplicationLanguagesStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1df0de4f_072b_4d7b_8f06_cb2db40f2bb5);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplicationLanguagesStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation_Collections", feature = "System"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "System")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICalendar(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICalendar {
type Vtable = ICalendar_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca30221d_86d9_40fb_a26b_d44eb7cf08ea);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendar_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) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::Foundation::DateTime) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::Foundation::DateTime) -> ::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, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eras: 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, ideallength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, years: 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, remainingdigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mindigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, months: 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, ideallength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ideallength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, mindigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, weeks: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, days: 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, mindigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut DayOfWeek) -> ::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, ideallength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ideallength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, periods: 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, ideallength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hours: 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, mindigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, minutes: 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, mindigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, seconds: 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, mindigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, nanoseconds: 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, mindigits: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, other: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, other: super::Foundation::DateTime, result__: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, other: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICalendarFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICalendarFactory {
type Vtable = ICalendarFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x83f58412_e56b_4c75_a66e_0f63d57758a6);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendarFactory_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, languages: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, languages: ::windows::core::RawPtr, calendar: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, clock: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICalendarFactory2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICalendarFactory2 {
type Vtable = ICalendarFactory2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb44b378c_ca7e_4590_9e72_ea2bec1a5115);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendarFactory2_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, languages: ::windows::core::RawPtr, calendar: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, clock: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, timezoneid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICalendarIdentifiersStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICalendarIdentifiersStatics {
type Vtable = ICalendarIdentifiersStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x80653f68_2cb2_4c1f_b590_f0f52bf4fd1a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendarIdentifiersStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICalendarIdentifiersStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICalendarIdentifiersStatics2 {
type Vtable = ICalendarIdentifiersStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7df4d488_5fd0_42a7_95b5_7d98d823075f);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendarIdentifiersStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICalendarIdentifiersStatics3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICalendarIdentifiersStatics3 {
type Vtable = ICalendarIdentifiersStatics3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2c225423_1fad_40c0_9334_a8eb90db04f5);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendarIdentifiersStatics3_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IClockIdentifiersStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IClockIdentifiersStatics {
type Vtable = IClockIdentifiersStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x523805bb_12ec_4f83_bc31_b1b4376b0808);
}
#[repr(C)]
#[doc(hidden)]
pub struct IClockIdentifiersStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyAmount(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyAmount {
type Vtable = ICurrencyAmount_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x74b49942_eb75_443a_95b3_7d723f56f93c);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyAmount_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyAmountFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyAmountFactory {
type Vtable = ICurrencyAmountFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x48d7168f_ef3b_4aee_a6a1_4b036fe03ff0);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyAmountFactory_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, amount: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, currency: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyIdentifiersStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyIdentifiersStatics {
type Vtable = ICurrencyIdentifiersStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f1d091b_d586_4913_9b6a_a9bd2dc12874);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyIdentifiersStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyIdentifiersStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyIdentifiersStatics2 {
type Vtable = ICurrencyIdentifiersStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1814797f_c3b2_4c33_9591_980011950d37);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyIdentifiersStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyIdentifiersStatics3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyIdentifiersStatics3 {
type Vtable = ICurrencyIdentifiersStatics3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4fb23bfa_ed25_4f4d_857f_237f1748c21c);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyIdentifiersStatics3_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IGeographicRegion(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGeographicRegion {
type Vtable = IGeographicRegion_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x01e9a621_4a64_4ed9_954f_9edeb07bd903);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGeographicRegion_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(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 IGeographicRegionFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGeographicRegionFactory {
type Vtable = IGeographicRegionFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x53425270_77b4_426b_859f_81e19d512546);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGeographicRegionFactory_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, geographicregioncode: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IGeographicRegionStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGeographicRegionStatics {
type Vtable = IGeographicRegionStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x29e28974_7ad9_4ef4_8799_b3b44fadec08);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGeographicRegionStatics_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, geographicregioncode: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IJapanesePhoneme(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IJapanesePhoneme {
type Vtable = IJapanesePhoneme_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2f6a9300_e85b_43e6_897d_5d82f862df21);
}
#[repr(C)]
#[doc(hidden)]
pub struct IJapanesePhoneme_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IJapanesePhoneticAnalyzerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IJapanesePhoneticAnalyzerStatics {
type Vtable = IJapanesePhoneticAnalyzerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x88ab9e90_93de_41b2_b4d5_8edb227fd1c2);
}
#[repr(C)]
#[doc(hidden)]
pub struct IJapanesePhoneticAnalyzerStatics_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, input: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, input: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, monoruby: bool, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguage(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguage {
type Vtable = ILanguage_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xea79a752_f7c2_4265_b1bd_c4dec4e4f080);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguage_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguage2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguage2 {
type Vtable = ILanguage2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6a47e5b5_d94d_4886_a404_a5a5b9d5b494);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguage2_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 LanguageLayoutDirection) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguage3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguage3 {
type Vtable = ILanguage3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc6af3d10_641a_5ba4_bb43_5e12aed75954);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguage3_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguageExtensionSubtags(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguageExtensionSubtags {
type Vtable = ILanguageExtensionSubtags_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d7daf45_368d_4364_852b_dec927037b85);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguageExtensionSubtags_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, singleton: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguageFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguageFactory {
type Vtable = ILanguageFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9b0252ac_0c27_44f8_b792_9793fb66c63e);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguageFactory_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, languagetag: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguageStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguageStatics {
type Vtable = ILanguageStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb23cd557_0865_46d4_89b8_d59be8990f0d);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguageStatics_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, languagetag: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguageStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguageStatics2 {
type Vtable = ILanguageStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x30199f6e_914b_4b2a_9d6e_e3b0e27dbe4f);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguageStatics2_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, languagetag: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ILanguageStatics3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ILanguageStatics3 {
type Vtable = ILanguageStatics3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd15ecb5a_71de_5752_9542_fac5b4f27261);
}
#[repr(C)]
#[doc(hidden)]
pub struct ILanguageStatics3_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, languagetags: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct INumeralSystemIdentifiersStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumeralSystemIdentifiersStatics {
type Vtable = INumeralSystemIdentifiersStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5c662c3_68c9_4d3d_b765_972029e21dec);
}
#[repr(C)]
#[doc(hidden)]
pub struct INumeralSystemIdentifiersStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct INumeralSystemIdentifiersStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumeralSystemIdentifiersStatics2 {
type Vtable = INumeralSystemIdentifiersStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7f003228_9ddb_4a34_9104_0260c091a7c7);
}
#[repr(C)]
#[doc(hidden)]
pub struct INumeralSystemIdentifiersStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ITimeZoneOnCalendar(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITimeZoneOnCalendar {
type Vtable = ITimeZoneOnCalendar_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbb3c25e5_46cf_4317_a3f5_02621ad54478);
}
#[repr(C)]
#[doc(hidden)]
pub struct ITimeZoneOnCalendar_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, timezoneid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ideallength: i32, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct JapanesePhoneme(pub ::windows::core::IInspectable);
impl JapanesePhoneme {
pub fn DisplayText(&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 YomiText(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IsPhraseStart(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for JapanesePhoneme {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.JapanesePhoneme;{2f6a9300-e85b-43e6-897d-5d82f862df21})");
}
unsafe impl ::windows::core::Interface for JapanesePhoneme {
type Vtable = IJapanesePhoneme_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2f6a9300_e85b_43e6_897d_5d82f862df21);
}
impl ::windows::core::RuntimeName for JapanesePhoneme {
const NAME: &'static str = "Windows.Globalization.JapanesePhoneme";
}
impl ::core::convert::From<JapanesePhoneme> for ::windows::core::IUnknown {
fn from(value: JapanesePhoneme) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&JapanesePhoneme> for ::windows::core::IUnknown {
fn from(value: &JapanesePhoneme) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for JapanesePhoneme {
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 JapanesePhoneme {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<JapanesePhoneme> for ::windows::core::IInspectable {
fn from(value: JapanesePhoneme) -> Self {
value.0
}
}
impl ::core::convert::From<&JapanesePhoneme> for ::windows::core::IInspectable {
fn from(value: &JapanesePhoneme) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for JapanesePhoneme {
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 JapanesePhoneme {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
pub struct JapanesePhoneticAnalyzer {}
impl JapanesePhoneticAnalyzer {
#[cfg(feature = "Foundation_Collections")]
pub fn GetWords<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(input: Param0) -> ::windows::core::Result<super::Foundation::Collections::IVectorView<JapanesePhoneme>> {
Self::IJapanesePhoneticAnalyzerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), input.into_param().abi(), &mut result__).from_abi::<super::Foundation::Collections::IVectorView<JapanesePhoneme>>(result__)
})
}
#[cfg(feature = "Foundation_Collections")]
pub fn GetWordsWithMonoRubyOption<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(input: Param0, monoruby: bool) -> ::windows::core::Result<super::Foundation::Collections::IVectorView<JapanesePhoneme>> {
Self::IJapanesePhoneticAnalyzerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), input.into_param().abi(), monoruby, &mut result__).from_abi::<super::Foundation::Collections::IVectorView<JapanesePhoneme>>(result__)
})
}
pub fn IJapanesePhoneticAnalyzerStatics<R, F: FnOnce(&IJapanesePhoneticAnalyzerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<JapanesePhoneticAnalyzer, IJapanesePhoneticAnalyzerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for JapanesePhoneticAnalyzer {
const NAME: &'static str = "Windows.Globalization.JapanesePhoneticAnalyzer";
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct Language(pub ::windows::core::IInspectable);
impl Language {
pub fn LanguageTag(&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 DisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn NativeName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Script(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn GetExtensionSubtags<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, singleton: Param0) -> ::windows::core::Result<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = &::windows::core::Interface::cast::<ILanguageExtensionSubtags>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), singleton.into_param().abi(), &mut result__).from_abi::<super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
pub fn CreateLanguage<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languagetag: Param0) -> ::windows::core::Result<Language> {
Self::ILanguageFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languagetag.into_param().abi(), &mut result__).from_abi::<Language>(result__)
})
}
pub fn IsWellFormed<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languagetag: Param0) -> ::windows::core::Result<bool> {
Self::ILanguageStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languagetag.into_param().abi(), &mut result__).from_abi::<bool>(result__)
})
}
pub fn CurrentInputMethodLanguageTag() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::ILanguageStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TrySetInputMethodLanguageTag<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languagetag: Param0) -> ::windows::core::Result<bool> {
Self::ILanguageStatics2(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languagetag.into_param().abi(), &mut result__).from_abi::<bool>(result__)
})
}
pub fn LayoutDirection(&self) -> ::windows::core::Result<LanguageLayoutDirection> {
let this = &::windows::core::Interface::cast::<ILanguage2>(self)?;
unsafe {
let mut result__: LanguageLayoutDirection = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<LanguageLayoutDirection>(result__)
}
}
pub fn AbbreviatedName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ILanguage3>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn GetMuiCompatibleLanguageListFromLanguageTags<'a, Param0: ::windows::core::IntoParam<'a, super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(languagetags: Param0) -> ::windows::core::Result<super::Foundation::Collections::IVector<::windows::core::HSTRING>> {
Self::ILanguageStatics3(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languagetags.into_param().abi(), &mut result__).from_abi::<super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__)
})
}
pub fn ILanguageFactory<R, F: FnOnce(&ILanguageFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Language, ILanguageFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ILanguageStatics<R, F: FnOnce(&ILanguageStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Language, ILanguageStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ILanguageStatics2<R, F: FnOnce(&ILanguageStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Language, ILanguageStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ILanguageStatics3<R, F: FnOnce(&ILanguageStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Language, ILanguageStatics3> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for Language {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.Language;{ea79a752-f7c2-4265-b1bd-c4dec4e4f080})");
}
unsafe impl ::windows::core::Interface for Language {
type Vtable = ILanguage_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xea79a752_f7c2_4265_b1bd_c4dec4e4f080);
}
impl ::windows::core::RuntimeName for Language {
const NAME: &'static str = "Windows.Globalization.Language";
}
impl ::core::convert::From<Language> for ::windows::core::IUnknown {
fn from(value: Language) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&Language> for ::windows::core::IUnknown {
fn from(value: &Language) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for Language {
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 Language {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<Language> for ::windows::core::IInspectable {
fn from(value: Language) -> Self {
value.0
}
}
impl ::core::convert::From<&Language> for ::windows::core::IInspectable {
fn from(value: &Language) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for Language {
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 Language {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for Language {}
unsafe impl ::core::marker::Sync for Language {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct LanguageLayoutDirection(pub i32);
impl LanguageLayoutDirection {
pub const Ltr: LanguageLayoutDirection = LanguageLayoutDirection(0i32);
pub const Rtl: LanguageLayoutDirection = LanguageLayoutDirection(1i32);
pub const TtbLtr: LanguageLayoutDirection = LanguageLayoutDirection(2i32);
pub const TtbRtl: LanguageLayoutDirection = LanguageLayoutDirection(3i32);
}
impl ::core::convert::From<i32> for LanguageLayoutDirection {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for LanguageLayoutDirection {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for LanguageLayoutDirection {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Globalization.LanguageLayoutDirection;i4)");
}
impl ::windows::core::DefaultType for LanguageLayoutDirection {
type DefaultType = Self;
}
pub struct NumeralSystemIdentifiers {}
impl NumeralSystemIdentifiers {
pub fn Arab() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ArabExt() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Bali() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Beng() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Cham() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Deva() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn FullWide() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Gujr() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Guru() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn HaniDec() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Java() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Kali() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Khmr() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Knda() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Lana() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn LanaTham() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Laoo() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Latn() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Lepc() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Limb() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mlym() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mong() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mtei() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mymr() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MymrShan() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Nkoo() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Olck() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Orya() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Saur() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Sund() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).35)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Talu() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).36)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn TamlDec() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).37)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Telu() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).38)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Thai() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).39)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Tibt() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).40)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Vaii() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).41)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Brah() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Osma() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MathBold() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MathDbl() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MathSans() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MathSanb() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn MathMono() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZmthBold() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZmthDbl() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZmthSans() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZmthSanb() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn ZmthMono() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::INumeralSystemIdentifiersStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn INumeralSystemIdentifiersStatics<R, F: FnOnce(&INumeralSystemIdentifiersStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<NumeralSystemIdentifiers, INumeralSystemIdentifiersStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn INumeralSystemIdentifiersStatics2<R, F: FnOnce(&INumeralSystemIdentifiersStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<NumeralSystemIdentifiers, INumeralSystemIdentifiersStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for NumeralSystemIdentifiers {
const NAME: &'static str = "Windows.Globalization.NumeralSystemIdentifiers";
}
|
use std::path::PathBuf;
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, PrintDiagnosticsPlugin},
math::{vec2, vec3, vec4},
prelude::*,
render::{
camera::{Camera, OrthographicProjection, PerspectiveProjection, WindowOrigin},
pipeline::{DynamicBinding, PipelineDescriptor, PipelineSpecialization, RenderPipeline},
render_graph::{base, AssetRenderResourcesNode, RenderGraph},
shader::{ShaderStage, ShaderStages},
},
};
use camera::{camera_movement, update_camera_distance, CameraMarker, MouseState};
use material::{GlobalMaterial, MeshMaterial, StarMaterial};
use mega_mesh::plugin::MegaMeshPlugin;
use mesh::{EditableMesh, MeshMaker};
use meshie::generator::{DistributionFn, MeshBuilder, MeshConfig};
use node_graph::{Graph, Ship};
use shape::Quad;
// use shapes::Skybox;
use skybox::plugin::SkyboxPlugin;
use texture_atlas::{load_atlas, ta_setup, AtlasInfo, AtlasSpriteHandles};
// mod bevy_lyon;
mod camera;
use camera::*;
// mod starscape;
mod dds_import;
mod material;
mod mesh;
mod node_graph;
mod othercamera;
// mod shapes;
mod texture_atlas;
use othercamera::*;
#[derive(Default, Debug)]
pub struct Handles {
pub mesh_handle: Handle<Mesh>,
pub ship_texture_mat: Handle<MeshMaterial>,
pub global_mat: Handle<GlobalMaterial>,
}
fn main() {
App::build()
.add_resource(Msaa { samples: 4 })
.add_resource(ClearColor(Color::BLACK))
.add_default_plugins()
.init_resource::<MouseState>()
.init_resource::<Handles>()
.init_resource::<MeshHandles>()
// .init_resource::<AtlasSpriteHandles>()
.add_asset::<MeshMaterial>()
// .add_asset::<SkyboxMaterial>()
.add_asset::<GlobalMaterial>()
.add_asset::<StarMaterial>()
.add_asset::<ColorMaterial>()
.add_plugin(FrameTimeDiagnosticsPlugin::default())
.add_plugin(PrintDiagnosticsPlugin::default())
// .add_plugin(SkyboxPlugin {
// size: 30000.,
// texture: Some(PathBuf::from("E:/Rust/Projects/dark_sky_editor/assets/STSCI-H-p1917b-q-5198x4801.png")),
// ..Default::default()
// })
// .add_plugin(MegaMeshPlugin::default())
.add_startup_system(setup.system())
.add_startup_system(setup_player.system())
// .add_startup_system(background.system())
// .add_startup_system(ta_setup.system())
// .add_system(load_atlas.system())
.add_system(camera_movement.system())
.add_system(camera_fucking_blows.system())
.add_system(update_camera_distance.system())
.add_system(move_ship.system())
.add_system(move_player.system())
// .add_system(rts_camera_system.system())
// .add_system(aspect_ratio.system())
.add_system_to_stage(
stage::POST_UPDATE,
bevy::render::shader::asset_shader_defs_system::<MeshMaterial>.system(),
)
.add_system_to_stage(
stage::POST_UPDATE,
bevy::render::shader::asset_shader_defs_system::<StarMaterial>.system(),
)
// .add_system_to_stage(
// stage::POST_UPDATE,
// bevy::render::shader::asset_shader_defs_system::<SkyboxMaterial>.system(),
// )
.run();
}
// TODO
// Generate Quad with texture references on vertex points (see if you can import a texture on vertex??)
// Connect 2D texture to Quad so that we can connect multiple different textures
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut handle_res: ResMut<Handles>,
mut pipelines: ResMut<Assets<PipelineDescriptor>>,
mut shaders: ResMut<Assets<Shader>>,
mut render_graph: ResMut<RenderGraph>,
mut materials: ResMut<Assets<MeshMaterial>>,
mut star_materials: ResMut<Assets<StarMaterial>>,
// mut skymaterials: ResMut<Assets<SkyboxMaterial>>,
mut globalmat: ResMut<Assets<GlobalMaterial>>,
mut textures: ResMut<Assets<Texture>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
handle_res.global_mat = globalmat.add(GlobalMaterial { distance: 0.0 });
let pipeline_handle = pipelines.add(PipelineDescriptor::default_config(ShaderStages {
vertex: shaders.add(Shader::from_glsl(
ShaderStage::Vertex,
include_str!("../../shaders/forward.vert"),
)),
fragment: Some(shaders.add(Shader::from_glsl(
ShaderStage::Fragment,
include_str!("../../shaders/forward.frag"),
))),
}));
render_graph.add_system_node(
"mesh_material",
AssetRenderResourcesNode::<MeshMaterial>::new(true),
);
render_graph
.add_node_edge("mesh_material", base::node::MAIN_PASS)
.unwrap();
let specialized_pipeline = RenderPipelines::from_pipelines(vec![RenderPipeline::specialized(
pipeline_handle,
PipelineSpecialization {
dynamic_bindings: vec![
// Transform
DynamicBinding {
bind_group: 2,
binding: 0,
},
// MeshMaterial_basecolor
DynamicBinding {
bind_group: 3,
binding: 0,
},
// MeshMaterial_distance
DynamicBinding {
bind_group: 3,
binding: 1,
},
],
..Default::default()
},
)]);
commands
.spawn(Camera2dComponents {
// global_transform
transform: Transform::new(Mat4::face_toward(
Vec3::new(0.0, -1000.01, 15000.0),
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(0.0, 0.0, 1.0),
)),
// perspective_projection: PerspectiveProjection {
// far: f32::MAX,
// ..Default::default()
// },
orthographic_projection: OrthographicProjection {
far: f32::MAX,
..Default::default()
},
..Default::default()
})
.with(CameraMarker);
let mut texture_handles = Vec::new();
for h in dds_import::dds_to_texture("assets/texture_atlas.dds") {
texture_handles.push(textures.add(h))
}
// let atlas_handle = asset_server.load("assets/texture_atlas.png").unwrap();
// let fly_handle = asset_server.load("assets/ship/model 512.png").unwrap();
// let quail_handle = asset_server.load("assets/quail-color.png").unwrap();
// NOT ACTUALLY AVAILABLE BECAUSE IT'S NOT LOADED YET
// using values that I checked from the png details....
// let atlas_size = textures.get(&atlas_handle).unwrap().size;
let atlas_size = vec2(4096., 4096.);
let atlas_info = AtlasInfo::import_from_file("assets/texture_atlas.ron");
let material = materials.add(MeshMaterial {
basecolor: Color::from(vec4(1.0, 1.0, 1.0, 1.0)),
texture1: Some(texture_handles[0]),
texture2: Some(texture_handles[1]),
texture3: Some(texture_handles[2]),
texture4: Some(texture_handles[3]),
texture5: Some(texture_handles[4]),
shaded: false,
distance: 0.0,
});
handle_res.ship_texture_mat = material;
let mut z_value: f32 = 0.0;
for seed in 1..2 {
let graph = Graph::new(10, 60, 60, seed);
println!("nodes: {}", graph.nodes.len());
let mut meshmakers = Vec::new();
let mut m_maker = MeshMaker::new();
let mut count = 0;
for node in &graph.nodes {
let rect = atlas_info.textures[node.texture as usize].rect;
let quad = Mesh::from(shape::Quad {
size: vec2(rect.max[0] - rect.min[0], rect.max[1] - rect.min[1]),
flip: false,
});
// positions
for position in quad.get_vertex_positions().unwrap() {
let pos = [
node.position.x() + position[0],
node.position.y() + position[1],
z_value,
];
z_value += 0.5;
m_maker.vert_pos.push(pos);
}
// normals
for norm in quad.get_vertex_normals().unwrap() {
m_maker.vert_norm.push(norm);
}
// uvs
for uv in quad.get_vertex_uvs().unwrap() {
m_maker.vert_uvs.push([
match uv[0] {
x if x < 0.0001 => rect.min[0] / atlas_size[0],
_ => rect.max[0] / atlas_size[0],
},
match uv[1] {
y if y < 0.0001 => rect.min[1] / atlas_size[1],
_ => rect.max[1] / atlas_size[1],
},
]);
// m_maker.vert_uvs.push(uv);
}
match quad.indices.unwrap() {
bevy::render::mesh::Indices::U16(_) => {}
bevy::render::mesh::Indices::U32(i) => {
for ind in i {
m_maker.indices.push(ind + count as u32);
}
}
}
commands.spawn((Ship {
vert_indices: count..(count + 4),
texture_index: 1.0,
},));
count += 4;
if count >= 64000 {
meshmakers.push(m_maker);
m_maker = MeshMaker::new();
count = 0;
}
}
meshmakers.push(m_maker);
println!("meshmakers: {}", meshmakers.len());
for meshmaker in &meshmakers {
let mesh_handle = meshes.add(meshmaker.generate_mesh());
handle_res.mesh_handle = mesh_handle;
commands
.spawn(MeshComponents {
mesh: mesh_handle,
render_pipelines: specialized_pipeline.clone(),
draw: Draw {
is_transparent: true,
..Default::default()
},
transform: Transform::from_rotation(Quat::from_rotation_z(
std::f32::consts::PI,
)),
// global_transform: GlobalTransform::from_rotation(Quat::from_rotation_y(2.0)),
..Default::default()
})
.with(handle_res.global_mat)
.with(material);
}
}
let star_pipeline_handle = pipelines.add(PipelineDescriptor::default_config(ShaderStages {
vertex: shaders.add(Shader::from_glsl(
ShaderStage::Vertex,
include_str!("../../shaders/star_vert_shader.vert"),
)),
fragment: Some(shaders.add(Shader::from_glsl(
ShaderStage::Fragment,
include_str!("../../shaders/star_frag_shader.frag"),
))),
}));
render_graph.add_system_node(
"star_material",
AssetRenderResourcesNode::<StarMaterial>::new(true),
);
render_graph
.add_node_edge("star_material", base::node::MAIN_PASS)
.unwrap();
let star_specialized_pipeline =
RenderPipelines::from_pipelines(vec![RenderPipeline::specialized(
star_pipeline_handle,
PipelineSpecialization {
dynamic_bindings: vec![
// Transform
DynamicBinding {
bind_group: 2,
binding: 0,
},
// StarMaterial_basecolor
DynamicBinding {
bind_group: 3,
binding: 0,
},
],
..Default::default()
},
)]);
let mat_handle = asset_server
.load("../assets/STSCI-H-p1917b-q-5198x4801.png")
.unwrap();
let mut mesh_builder = MeshBuilder {
texture_size: vec2(5198., 4807.),
config: vec![],
};
mesh_builder.config.push(MeshConfig {
count: 1000000,
texture_position: bevy::sprite::Rect {
min: vec2(592., 863.),
max: vec2(601., 871.),
},
area: vec3(100000., 100000., 1000.),
distribution: DistributionFn::Random,
});
mesh_builder.config.push(MeshConfig {
count: 500000,
texture_position: bevy::sprite::Rect {
min: vec2(674., 857.),
max: vec2(685., 869.),
},
area: vec3(100000., 100000., 1000.),
distribution: DistributionFn::Random,
});
mesh_builder.config.push(MeshConfig {
count: 500000,
texture_position: bevy::sprite::Rect {
min: vec2(526., 854.),
max: vec2(543., 871.),
},
area: vec3(100000., 100000., 1000.),
distribution: DistributionFn::Random,
});
mesh_builder.config.push(MeshConfig {
count: 100000,
texture_position: bevy::sprite::Rect {
min: vec2(613., 880.),
max: vec2(656., 917.),
},
area: vec3(100000., 100000., 1000.),
distribution: DistributionFn::Random,
});
let mesh = mesh_builder.gen_mesh();
// let mut rng = StdRng::from_entropy();
let mesh_handle = meshes.add(mesh);
commands
.spawn(MeshComponents {
mesh: mesh_handle,
render_pipelines: star_specialized_pipeline,
transform: Transform::from_scale(0.1),
..Default::default()
})
.with(star_materials.add(StarMaterial {
texture: Some(mat_handle),
..Default::default()
}));
}
#[derive(Default)]
struct MeshHandles {
background: Option<Handle<Mesh>>,
}
fn aspect_ratio(mut meshes: ResMut<Assets<Mesh>>, handle: Res<MeshHandles>, windows: Res<Windows>) {
if let Some(h) = &handle.background {
if let Some(mesh) = meshes.get_mut(&h) {
let Window { width, height, .. } = windows.get_primary().expect("No primary window");
let width = *width as f32 * 3_f32;
let height = *height as f32 * 3_f32;
let left = -width;
let right = width;
let bottom = -height;
let top = height;
match mesh.attributes[0].values {
bevy::render::mesh::VertexAttributeValues::Float3(ref mut vertices) => {
vertices[2] = [left, top, 0.0];
vertices[3] = [right, top, 0.0];
vertices[1] = [left, bottom, 0.0];
vertices[0] = [right, bottom, 0.0];
}
_ => (),
}
}
}
}
fn setup_player(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut textures: ResMut<Assets<Texture>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let texture_handle = asset_server
.load_sync(&mut textures, "assets/flycatcher.png")
.unwrap();
let texture = textures.get(&texture_handle).unwrap();
let aspect = texture.aspect();
let quad_handle = meshes.add(Mesh::from(shape::Quad::new(Vec2::new(
texture.size.x(),
texture.size.y(),
))));
let material_handle = materials.add(StandardMaterial {
albedo_texture: Some(texture_handle),
shaded: false,
..Default::default()
});
commands
// textured quad - normal
.spawn(PbrComponents {
mesh: quad_handle,
material: material_handle,
transform: Transform::from_translation_rotation(
Vec3::new(0.0, -1000.01, 8000.),
Quat::from_rotation_x(-std::f32::consts::PI / 5.0),
),
draw: Draw {
is_transparent: true,
..Default::default()
},
..Default::default()
})
.with(Player);
}
struct Player;
fn move_player(key: Res<Input<KeyCode>>, mut query: Query<(&Player, &mut Transform)>) {
for (_, mut trans) in &mut query.iter() {
if key.pressed(KeyCode::W) {
trans.translate(vec3(0.0, 2.0, 0.0))
}
if key.pressed(KeyCode::A) {
trans.translate(vec3(-2.0, 0.0, 0.0))
}
if key.pressed(KeyCode::S) {
trans.translate(vec3(0.0, -2.0, 0.0))
}
if key.pressed(KeyCode::D) {
trans.translate(vec3(2.0, 0.0, 0.0))
}
}
}
// fn background(
// mut commands: Commands,
// asset_server: Res<AssetServer>,
// mut backgroundhandle: ResMut<MeshHandles>,
// mut meshes: ResMut<Assets<Mesh>>,
// mut textures: ResMut<Assets<Texture>>,
// mut materials: ResMut<Assets<StandardMaterial>>,
// ) {
// let mut mesh = Mesh::from(shapes::Skybox { size: 10000000. });
// let quad_handle = meshes.add(mesh);
// let red_material_handle = materials.add(StandardMaterial {
// albedo: Color::rgba(0.0, 0.0, 0.0, 1.0),
// // albedo_texture: Some(texture_handle),
// shaded: false,
// ..Default::default()
// });
// backgroundhandle.background = Some(quad_handle);
// commands
// // textured quad - normal
// .spawn(PbrComponents {
// mesh: quad_handle,
// material: red_material_handle,
// draw: Draw {
// is_transparent: true,
// ..Default::default()
// },
// ..Default::default()
// });
// }
fn move_ship(mut meshes: ResMut<Assets<Mesh>>, handles: Res<Handles>, mut query: Query<&Ship>) {
if let Some(mesh) = meshes.get_mut(&handles.mesh_handle) {
if let Some(positions) = mesh.get_mut_vertex_positions() {
for ship in &mut query.iter() {
// if ship.texture_index < 1.5 {
for index in ship.vert_indices.clone() {
positions[index as usize][1] += 0.7;
}
// }
}
}
}
}
|
use crate::stdio_server::input::{PluginAction, PluginEvent};
use crate::stdio_server::plugin::{Action, ActionType, ClapAction, ClapPlugin, PluginId};
use crate::stdio_server::vim::Vim;
use anyhow::{anyhow, Result};
#[derive(Debug, Clone)]
pub struct SystemPlugin {
vim: Vim,
}
impl SystemPlugin {
pub const ID: PluginId = PluginId::System;
const NOTE_RECENT_FILES: &'static str = "note_recent_files";
const NOTE_RECENT_FILES_ACTION: Action = Action::callable(Self::NOTE_RECENT_FILES);
const OPEN_CONFIG: &'static str = "open-config";
const OPEN_CONFIG_ACTION: Action = Action::callable(Self::OPEN_CONFIG);
const LIST_PLUGINS: &'static str = "list-plugins";
const LIST_PLUGINS_ACTION: Action = Action::callable(Self::LIST_PLUGINS);
const CALLABLE_ACTIONS: &[Action] = &[Self::OPEN_CONFIG_ACTION, Self::LIST_PLUGINS_ACTION];
const ACTIONS: &[Action] = &[
Self::NOTE_RECENT_FILES_ACTION,
Self::OPEN_CONFIG_ACTION,
Self::LIST_PLUGINS_ACTION,
];
pub fn new(vim: Vim) -> Self {
Self { vim }
}
}
impl ClapAction for SystemPlugin {
fn actions(&self, action_type: ActionType) -> &[Action] {
match action_type {
ActionType::Callable => Self::CALLABLE_ACTIONS,
ActionType::All => Self::ACTIONS,
}
}
}
#[async_trait::async_trait]
impl ClapPlugin for SystemPlugin {
fn id(&self) -> PluginId {
Self::ID
}
async fn on_plugin_event(&mut self, plugin_event: PluginEvent) -> Result<()> {
match plugin_event {
PluginEvent::Autocmd(_) => Ok(()),
PluginEvent::Action(plugin_action) => {
let PluginAction { method, params } = plugin_action;
match method.as_str() {
Self::NOTE_RECENT_FILES => {
let bufnr: Vec<usize> = params.parse()?;
let bufnr = bufnr
.first()
.ok_or(anyhow!("bufnr not found in `note_recent_files`"))?;
let file_path: String = self.vim.expand(format!("#{bufnr}:p")).await?;
crate::stdio_server::handler::messages::note_recent_file(file_path)
}
Self::OPEN_CONFIG => {
let config_file = crate::config::config_file();
self.vim
.exec("execute", format!("edit {}", config_file.display()))
}
Self::LIST_PLUGINS => {
// Handled upper level.
Ok(())
}
_ => Ok(()),
}
}
}
}
}
|
pub use VkGeometryFlagsNV::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkGeometryFlagsNV {
VK_GEOMETRY_OPAQUE_BIT_NV = 0x0000_0001,
VK_GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION_BIT_NV = 0x0000_0002,
}
use crate::SetupVkFlags;
#[repr(C)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct VkGeometryFlagBitsNV(u32);
SetupVkFlags!(VkGeometryFlagsNV, VkGeometryFlagBitsNV);
|
use crate::reader::get_lines;
#[derive(Debug)]
enum Error {
Unmatched(char, char),
Missing(Vec<char>),
}
fn get_error_score_for_line(line: &str) -> Option<u64> {
if let Err(Error::Unmatched(expected, _found)) = parse_line(line) {
match expected {
'>' => Some(25137),
'}' => Some(1197),
']' => Some(57),
')' => Some(3),
_ => panic!("unexpected char"),
}
} else {
None
}
}
fn get_missing_score_for_line(line: &str) -> Option<u64> {
if let Err(Error::Missing(mut chars)) = parse_line(line) {
chars.reverse();
return Some(chars.iter().fold(0, |score, character| {
let points: u64 = match character {
'>' => 4,
'}' => 3,
']' => 2,
')' => 1,
_ => panic!("unexpected char"),
};
score * 5 + points
}));
}
None
}
fn parse_line(line: &str) -> Result<bool, Error> {
let mut stack = Vec::new();
for char in line.chars().collect::<Vec<char>>() {
match char {
'(' => stack.push(')'),
'{' => stack.push('}'),
'[' => stack.push(']'),
'<' => stack.push('>'),
')' | ']' | '}' | '>' => {
if let Some(expected) = stack.pop() {
if char != expected {
return Err(Error::Unmatched(char, expected));
}
}
}
_ => println!("error unknown input"),
}
}
if stack.is_empty() {
Ok(true)
} else {
Err(Error::Missing(stack))
}
}
pub fn part_1(filename: &str) -> u64 {
get_lines(filename)
.flatten()
.filter_map(|line| get_error_score_for_line(&line))
.sum()
}
pub fn part_2(filename: &str) -> u64 {
let mut scores: Vec<u64> = get_lines(filename)
.flatten()
.map(|line| get_missing_score_for_line(&line))
.flatten()
.collect();
scores.sort();
*scores.get(scores.len() / 2).unwrap()
}
#[cfg(test)]
mod tests {
use crate::day10::{
get_error_score_for_line, get_missing_score_for_line, parse_line, part_1, part_2, Error,
};
#[test]
fn test_parse_line() {
let line = "{([(<{}[<>[]}>{[]{[(<()>";
assert!(matches!(parse_line(line), Err(Error::Unmatched(_, _))));
let line = "[({(<(())[]>[[{[]{<()<>>";
assert!(matches!(parse_line(line), Err(Error::Missing(_))));
let line = "<>";
assert!(matches!(parse_line(line), Ok(true)));
}
#[test]
fn test_unmatched_score() {
let line = "{([(<{}[<>[]}>{[]{[(<()>";
assert_eq!(Some(1197), get_error_score_for_line(line))
}
#[test]
fn test_missing_score() {
let line = "<{([{{}}[<[[[<>{}]]]>[]]";
assert_eq!(Some(294), get_missing_score_for_line(line))
}
#[test]
fn test_part1() {
assert_eq!(26397, part_1("./resources/inputs/day10-example.txt"));
assert_eq!(415953, part_1("./resources/inputs/day10-input.txt"));
}
#[test]
fn test_part2() {
assert_eq!(288957, part_2("./resources/inputs/day10-example.txt"));
assert_eq!(2292863731, part_2("./resources/inputs/day10-input.txt"));
}
}
|
/// Main modules to perform the low-level operations
/// described in the Olin specs. In particular the basic
/// "actions": open, read, write, close, flush on files.
///
/// Modules:
/// * sys
/// * err
/// * log
/// * env
/// * runtime
/// * startup
/// * time
/// * stdio
/// * random
///
/// The ```Resource``` struct defines a high level wrapper
/// to the more low level IO calls in sys.
extern crate chrono;
use std::io::{self, Read, Write};
pub mod http;
pub mod panic;
// Replace the allocator
extern crate wee_alloc;
// Use `wee_alloc` as the global allocator.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
/// system-level operations, interface and FFI access:
/// * setup and low-level operations
/// * bindings to environment variables
/// * bindings for system calls
pub mod sys {
extern "C" {
// https://github.com/CommonWA/cwa-spec/blob/master/ns/log.md#write
pub fn log_write(level: i32, text_ptr: *const u8, text_len: usize);
// https://github.com/CommonWA/cwa-spec/blob/master/ns/env.md#get
pub fn env_get(
key_ptr: *const u8,
key_len: usize,
value_buf_ptr: *mut u8,
value_buf_len: usize,
) -> i32;
pub fn runtime_exit(status: i32) -> !;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/runtime.md#spec_major
pub fn runtime_spec_major() -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/runtime.md#spec_minor
pub fn runtime_spec_minor() -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/runtime.md#name
pub fn runtime_name(out_ptr: *mut u8, out_len: usize) -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/runtime.md#msleep
pub fn runtime_msleep(ms: i32);
// https://github.com/CommonWA/cwa-spec/blob/master/ns/startup.md#arg_len
pub fn startup_arg_len() -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/startup.md#art_at
pub fn startup_arg_at(id: i32, out_ptr: *mut u8, out_len: usize) -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/resource.md#open
pub fn resource_open(url_ptr: *const u8, url_len: usize) -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/resource.md#read
pub fn resource_read(id: i32, data_ptr: *mut u8, data_len: usize) -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/resource.md#write
pub fn resource_write(id: i32, data_ptr: *const u8, data_len: usize) -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/resource.md#close
pub fn resource_close(id: i32);
// https://github.com/CommonWA/cwa-spec/blob/master/ns/resource.md#flush
pub fn resource_flush(id: i32) -> i32;
// https://github.com/Xe/cwa-spec/blob/Xe/time/ns/time.md#now
// This is special-snowflaked at the moment because there's a disagreement
// about how to do this in the spec at https://github.com/CommonWA/cwa-spec/pull/8
pub fn time_now() -> i64;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/random.md#i32
pub fn random_i32() -> i32;
// https://github.com/CommonWA/cwa-spec/blob/master/ns/random.md#i64
pub fn random_i64() -> i64;
// This api is a nonce.
// https://github.com/Xe/olin/blob/master/docs/cwa-spec/ns/io.md#io_get_stdin
pub fn io_get_stdin() -> i32;
// https://github.com/Xe/olin/blob/master/docs/cwa-spec/ns/io.md#io_get_stdout
pub fn io_get_stdout() -> i32;
// https://github.com/Xe/olin/blob/master/docs/cwa-spec/ns/io.md#io_get_stderr
pub fn io_get_stderr() -> i32;
}
}
mod err {
use std::fmt;
use std::io;
// https://github.com/CommonWA/cwa-spec/blob/master/errors.md
pub const UNKNOWN: i32 = -1;
pub const INVALID_ARGUMENT: i32 = -2;
pub const PERMISSION_DENIED: i32 = -3;
pub const NOT_FOUND: i32 = -4;
pub const EOF: i32 = -5;
/// An error abstraction, all of the following values are copied from the spec at:
/// https://github.com/CommonWA/cwa-spec/blob/master/errors.md
#[repr(i32)]
#[derive(Debug)]
pub enum Error {
Unknown = UNKNOWN,
InvalidArgument = INVALID_ARGUMENT,
PermissionDenied = PERMISSION_DENIED,
NotFound = NOT_FOUND,
EOF = EOF,
}
impl Error {
pub fn check(n: i32) -> Result<i32, Error> {
match n {
n if n >= 0 => Ok(n),
INVALID_ARGUMENT => Err(Error::InvalidArgument),
PERMISSION_DENIED => Err(Error::PermissionDenied),
NOT_FOUND => Err(Error::NotFound),
EOF => Err(Error::EOF),
_ => Err(Error::Unknown),
}
}
}
/// pretty-print the error using Debug-derived code
/// XXX(Xe): is this a mistake?
impl self::fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::error::Error for Error {}
pub fn check_io(error: i32) -> Result<i32, io::ErrorKind> {
match error {
n if n >= 0 => Ok(n),
INVALID_ARGUMENT => Err(io::ErrorKind::InvalidInput),
PERMISSION_DENIED => Err(io::ErrorKind::PermissionDenied),
NOT_FOUND => Err(io::ErrorKind::NotFound),
EOF => Err(io::ErrorKind::UnexpectedEof),
_ => Err(io::ErrorKind::Other),
}
}
}
pub mod log;
/// Access to environment variables
pub mod env {
use super::{err, sys};
/// https://github.com/CommonWA/cwa-spec/blob/master/ns/env.md#get
#[derive(Debug)]
pub enum Error {
NotFound,
TooSmall(u32),
}
pub fn get_buf<'a>(key: &[u8], value: &'a mut [u8]) -> Result<&'a mut [u8], Error> {
let ret = unsafe { sys::env_get(key.as_ptr(), key.len(), value.as_mut_ptr(), value.len()) };
match ret {
err::NOT_FOUND => Err(Error::NotFound),
n if (n as usize) <= value.len() => {
Ok(unsafe { value.get_unchecked_mut(0..n as usize) })
}
n => Err(Error::TooSmall(n as u32)),
}
}
/// Return the value of an environment variable or the reason why we can't.
pub fn get(key: &str) -> Result<String, Error> {
const ENVVAR_LEN: usize = 4096; // at work we don't see longer than 128 usually
let key = key.as_bytes();
let mut val = [0u8; ENVVAR_LEN];
let val = get_buf(&key, &mut val).map_err(|e| {
crate::log::error(&format!("can't get envvar: {:?}", e));
e
})?;
let mut s: String = ::std::string::String::from("");
s.push_str(::std::str::from_utf8(&val).unwrap());
Ok(s)
}
}
pub mod runtime {
use super::{err, sys};
pub fn exit(status: i32) -> ! {
unsafe { sys::runtime_exit(status) }
}
pub fn spec_major() -> i32 {
unsafe { sys::runtime_spec_major() }
}
pub fn spec_minor() -> i32 {
unsafe { sys::runtime_spec_minor() }
}
pub fn name_buf(out: &mut [u8]) -> Option<&mut str> {
let ret = unsafe { sys::runtime_name(out.as_mut_ptr(), out.len()) };
match ret {
err::INVALID_ARGUMENT => None,
len => {
let out = unsafe { out.get_unchecked_mut(0..len as usize) };
Some(unsafe { ::std::str::from_utf8_unchecked_mut(out) })
}
}
}
pub fn name() -> String {
const MAX_LEN: usize = 32;
let mut out = Vec::with_capacity(MAX_LEN);
{
let len = unsafe { sys::runtime_name(out.as_mut_ptr(), MAX_LEN) };
unsafe { out.set_len(len as usize) };
}
unsafe { String::from_utf8_unchecked(out) }
}
pub fn msleep(ms: i32) {
unsafe { sys::runtime_msleep(ms) }
}
}
/// used to fetch argv/argc
pub mod startup {
use super::{err, sys};
use std::str;
pub fn arg_len() -> i32 {
unsafe { sys::startup_arg_len() }
}
pub fn arg_os_at_buf(id: i32, out: &mut [u8]) -> Option<&mut [u8]> {
let ret = unsafe { sys::startup_arg_at(id, out.as_mut_ptr(), out.len()) };
match ret {
err::INVALID_ARGUMENT => None,
bytes_written => Some(unsafe { out.get_unchecked_mut(0..bytes_written as usize) }),
}
}
pub fn arg_os_at(id: i32, capacity: usize) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(capacity);
let ret = unsafe { sys::startup_arg_at(id, out.as_mut_ptr(), out.len()) };
match ret {
err::INVALID_ARGUMENT => None,
bytes_written => {
unsafe { out.set_len(bytes_written as usize) };
Some(out)
}
}
}
pub fn arg_at_buf(id: i32, out: &mut [u8]) -> Option<&mut str> {
arg_os_at_buf(id, out).map(|s| str::from_utf8_mut(s).expect("arg isn't UTF-8"))
}
pub fn arg_at(id: i32, capacity: usize) -> Option<String> {
arg_os_at(id, capacity).map(|s| String::from_utf8(s).expect("arg isn't UTF-8"))
}
}
///
/// Resources are maybe readable, maybe writable, maybe flushable and closable
/// streams of bytes. A resource is backed by implementation in the containing
/// runtime based on the URL scheme used in the `open` call.
///
/// Resources do not always have to be backed by things that exist. Resources
/// may contain the transient results of API calls. Once the data in a Resource
/// has been read, that may be the only time that data can ever be read.
///
/// Please take this into consideration when consuming the results of Resources.
///
/// The implementation of this type uses the functions at https://github.com/CommonWA/cwa-spec/blob/master/ns/resource.md
///
#[derive(Debug)]
pub struct Resource(i32);
impl Resource {
pub fn open(url: &str) -> Result<Resource, err::Error> {
let res = unsafe { sys::resource_open(url.as_ptr(), url.len()) };
err::Error::check(res).map(Resource)
}
/// For the few times you _actually_ do know the file descriptor.
///
/// The CommonWA spec doesn't mandate any properties about file descriptors.
/// The implementation in Olin uses random file descriptors, meaning that
/// unless the stdio module is used, this function should probably never be
/// called unless you really know what you are doing.
///
/// Passing an invalid file descriptor to this function will result in a
/// handle that returns errors on every call to it. This behavior may be
/// useful.
pub unsafe fn from_raw(handle: i32) -> Resource {
Resource(handle)
}
}
impl Drop for Resource {
fn drop(&mut self) {
unsafe { sys::resource_close(self.0) };
}
}
impl Read for Resource {
fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
let len = out.len();
if len == 0 {
Ok(0)
} else {
let ret = unsafe { sys::resource_read(self.0, out.as_mut_ptr(), len) };
err::check_io(ret)
.map(|b| b as usize)
.map_err(io::Error::from)
}
}
}
impl Write for Resource {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let len = data.len();
if len == 0 {
Ok(0)
} else {
let ret = unsafe { sys::resource_write(self.0, data.as_ptr(), len) };
err::check_io(ret)
.map(|b| b as usize)
.map_err(io::Error::from)
}
}
fn flush(&mut self) -> io::Result<()> {
let ret: i32 = unsafe { sys::resource_flush(self.0) };
if ret == 0 {
Ok(())
} else {
err::check_io(ret).map(|_| ()).map_err(io::Error::from)
}
}
}
pub mod time {
use super::sys;
use chrono::{self, TimeZone};
pub fn now() -> chrono::DateTime<chrono::Utc> {
chrono::Utc.timestamp(ts(), 0)
}
pub fn ts() -> i64 {
unsafe { sys::time_now() }
}
}
/// Bindings from semantic I/O targets to Resources
pub mod stdio {
use super::Resource;
pub fn inp() -> Resource {
unsafe { Resource::from_raw(crate::sys::io_get_stdin()) }
}
pub fn out() -> Resource {
unsafe { Resource::from_raw(crate::sys::io_get_stdout()) }
}
pub fn err() -> Resource {
unsafe { Resource::from_raw(crate::sys::io_get_stderr()) }
}
}
pub mod random {
use super::sys;
pub fn i31() -> i32 {
unsafe { sys::random_i32() }
}
pub fn i63() -> i64 {
unsafe { sys::random_i64() }
}
}
#[macro_export]
macro_rules! entrypoint {
() => {
#[no_mangle]
#[start]
extern "C" fn _start() {
::olin::panic::set_hook();
let _ = ::olin::log::init();
if let Err(e) = main() {
::log::error!("Application error: {:?}", e);
::olin::runtime::exit(1);
}
::olin::runtime::exit(0);
}
};
}
|
pub struct Solution;
impl Solution {
pub fn is_number(s: String) -> bool {
let mut iter = s.chars().peekable();
consume_spaces(&mut iter);
consume_sign(&mut iter);
let mut has_digits = consume_digits(&mut iter);
if consume_point(&mut iter) {
has_digits |= consume_digits(&mut iter);
}
if !has_digits {
return false;
}
if consume_e(&mut iter) {
consume_sign(&mut iter);
if !consume_digits(&mut iter) {
return false;
}
}
consume_spaces(&mut iter);
iter.next() == None
}
}
fn consume_spaces(iter: &mut std::iter::Peekable<std::str::Chars>) -> bool {
let mut res = false;
while iter.peek() == Some(&' ') {
iter.next();
res = true;
}
res
}
fn consume_sign(iter: &mut std::iter::Peekable<std::str::Chars>) -> bool {
match iter.peek() {
Some(&'+') => {
iter.next();
true
}
Some(&'-') => {
iter.next();
true
}
_ => false,
}
}
fn consume_digits(iter: &mut std::iter::Peekable<std::str::Chars>) -> bool {
let mut res = false;
while match iter.peek() {
Some(&('0'..='9')) => true,
_ => false,
} {
iter.next();
res = true;
}
res
}
fn consume_point(iter: &mut std::iter::Peekable<std::str::Chars>) -> bool {
if iter.peek() == Some(&'.') {
iter.next();
true
} else {
false
}
}
fn consume_e(iter: &mut std::iter::Peekable<std::str::Chars>) -> bool {
if iter.peek() == Some(&'e') {
iter.next();
true
} else {
false
}
}
#[test]
fn test0065() {
assert_eq!(Solution::is_number("0".to_string()), true);
assert_eq!(Solution::is_number(" 0.1 ".to_string()), true);
assert_eq!(Solution::is_number("abc".to_string()), false);
assert_eq!(Solution::is_number("1 a".to_string()), false);
assert_eq!(Solution::is_number("2e10".to_string()), true);
assert_eq!(Solution::is_number(" -90e3 ".to_string()), true);
assert_eq!(Solution::is_number(" 1e".to_string()), false);
assert_eq!(Solution::is_number("e3".to_string()), false);
assert_eq!(Solution::is_number(" 6e-1".to_string()), true);
assert_eq!(Solution::is_number(" 99e2.5 ".to_string()), false);
assert_eq!(Solution::is_number("53.5e93".to_string()), true);
assert_eq!(Solution::is_number(" --6 ".to_string()), false);
assert_eq!(Solution::is_number("-+3".to_string()), false);
assert_eq!(Solution::is_number("95a54e53".to_string()), false);
}
|
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#![feature(test)]
extern crate test;
extern crate unsigned_varint;
#[cfg(feature = "codec")]
extern crate bytes;
#[cfg(feature = "codec")]
extern crate tokio_codec;
use std::u64;
use test::Bencher;
use unsigned_varint::{decode, encode};
#[bench]
fn bench_decode(b: &mut Bencher) {
let mut buf = [0; 10];
let bytes = encode::u64(u64::MAX, &mut buf);
b.iter(|| {
assert_eq!(u64::MAX, decode::u64(bytes).unwrap().0)
});
}
#[bench]
fn bench_encode(b: &mut Bencher) {
let mut buf = [0; 10];
let encoded = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 1];
b.iter(|| {
assert_eq!(&encoded, encode::u64(u64::MAX, &mut buf));
});
}
#[cfg(feature = "codec")]
#[bench]
fn bench_codec(b: &mut Bencher) {
use bytes::{Bytes, BytesMut};
use tokio_codec::{Decoder, Encoder};
use unsigned_varint::codec::UviBytes;
let data = Bytes::from(vec![1; 8192]);
let mut bytes = BytesMut::with_capacity(9000);
let mut uvi_bytes = UviBytes::default();
b.iter(move || {
uvi_bytes.encode(data.clone(), &mut bytes).unwrap();
assert_eq!(data, uvi_bytes.decode(&mut bytes.take()).unwrap().unwrap())
});
}
|
use gameboy;
use cart;
const WRAM_SIZE: usize = 0xDFFF - 0xC000 + 1;
const VRAM_SIZE: usize = 0x9FFF - 0x8000 + 1;
const XRAM_SIZE: usize = 0xBFFF - 0xA000 + 1;
const HRAM_SIZE: usize = 0xFFFE - 0xFF80 + 1;
const IO_SIZE: usize = 0xFF7F - 0xFF01 + 1;
use std::ops::{Index, IndexMut, Range};
pub struct Memory {
count: u16,
boot: [u8; gameboy::BOOTROM_SIZE],
cart: cart::Cart,
wram: [u8; WRAM_SIZE],
vram: [u8; VRAM_SIZE],
xram: [u8; XRAM_SIZE],
input: [u8; 1],
io: [u8; IO_SIZE],
hram: [u8; HRAM_SIZE],
interrupt: [u8; 1],
zero: [u8; 1],
}
impl Memory {
pub fn new(boot: [u8; gameboy::BOOTROM_SIZE], cart: cart::Cart) -> Memory {
Memory {
count: 0xFFFF,
boot: boot,
cart: cart,
wram: [127; WRAM_SIZE],
vram: [127; VRAM_SIZE],
xram: [0; XRAM_SIZE],
input: [0],
io: [0; IO_SIZE],
hram: [0; HRAM_SIZE],
interrupt: [0],
zero: [0],
}
}
}
impl Index<u16> for Memory {
type Output = u8;
fn index(&self, index: u16) -> &Self::Output {
match index {
0xFF00 => &self.input[0],
0xFFFF => &self.interrupt[0],
_ => &self[index..index + 1][0],
}
}
}
impl Index<usize> for Memory {
type Output = u8;
fn index(&self, index: usize) -> &Self::Output {
&self[index..index + 1][0]
}
}
impl IndexMut<u16> for Memory {
fn index_mut(&mut self, index: u16) -> &mut u8 {
&mut self[index as usize]
}
}
impl IndexMut<usize> for Memory {
fn index_mut(&mut self, index: usize) -> &mut u8 {
match index {
0x0000...0x00FF => &mut self.boot[index - 0x0000],
0x0100...0x7FFF => &mut self.cart[index - 0x0100],
0x8000...0x9FFF => &mut self.vram[index - 0x8000],
0xA000...0xBFFF => &mut self.xram[index - 0xA000],
0xC000...0xDFFF => &mut self.wram[index - 0xC000],
0xE000...0xFDFF => &mut self.wram[index - 0xE000],
0xFF00 => &mut self.input[index - 0xFF00],
0xFF01...0xFF7F => &mut self.io[index - 0xFF01],
0xFF80...0xFFFE => &mut self.hram[index - 0xFF80],
0xFFFF => &mut self.interrupt[index - 0xFFFF],
_ => panic!("Address {:0>2X} has no known mapping!", index),
}
}
}
impl Index<Range<u16>> for Memory {
type Output = [u8];
fn index(&self, range: Range<u16>) -> &Self::Output {
let usize_range = (range.start as usize)..(range.end as usize);
&self[usize_range]
}
}
impl Index<Range<usize>> for Memory {
type Output = [u8];
fn index(&self, range: Range<usize>) -> &Self::Output {
let end = if range.end.wrapping_sub(range.start) == 1 {
range.start
} else {
range.end
};
match (range.start, end) {
(0x0000...0x00FF, 0x0000...0x00FF) => {
&self.boot[(range.start - 0x0000)..(range.end - 0x0000)]
}
(0x0100...0x7FFF, 0x0100...0x7FFF) => {
&self.cart[(range.start - 0x0100)..(range.end - 0x0100)]
}
(0x8000...0x9FFF, 0x8000...0x9FFF) => {
&self.vram[(range.start - 0x8000)..(range.end - 0x8000)]
}
(0xA000...0xBFFF, 0xA000...0xBFFF) => {
&self.xram[(range.start - 0xA000)..(range.end - 0xA000)]
}
(0xC000...0xDFFF, 0xC000...0xDFFF) => {
&self.wram[(range.start - 0xC000)..(range.end - 0xC000)]
}
(0xE000...0xFDFF, 0xE000...0xFDFF) => {
&self.wram[(range.start - 0xE000)..(range.end - 0xE000)]
}
(0xFE00...0xFEFF, 0xFE00...0xFEFF) => &self.zero[..],
(0xFF00, 0xFF00) => &self.input[..],
(0xFF01...0xFF7F, 0xFF01...0xFF7F) => {
&self.io[(range.start - 0xFF01)..(range.end - 0xFF01)]
}
(0xFF80...0xFFFF, 0xFF80...0xFFFE) => {
&self.hram[(range.start - 0xFF80)..(range.end - 0xFF80)]
}
(0xFFFF, 0x0000) => &self.interrupt[..],
_ => {
panic!("Address {:0>4X}..{:0>4X} has no known mapping!",
range.start,
end)
}
}
}
}
impl Iterator for Memory {
// we will be counting with usize
type Item = u8;
// next() is the only required method
fn next(&mut self) -> Option<u8> {
// increment our count. This is why we started at zero.
self.count -= 1;
// check to see if we've finished counting or not.
if self.count > 0 {
Some(self[self.count])
} else {
None
}
}
}
|
use core::fmt;
use std::io;
use serde::{de, ser};
// derive nothing here by now
pub struct Error {
err: Box<ErrorImpl>,
}
pub type Result<T> = core::result::Result<T, Error>;
struct ErrorImpl {
code: ErrorCode,
index: usize, // index == 0: index is not necessary
}
pub(crate) enum ErrorCode {
Message(Box<str>),
Io(io::Error),
UnsupportedType,
UnsupportedListInnerType,
InvalidStringLength,
KeyMustBeAString,
SequenceSizeUnknown,
SequenceDifferentType,
InvalidBoolByte,
}
impl Error {
pub(crate) fn syntax(code: ErrorCode, index: usize) -> Self {
Self::from_inner(code, index)
}
pub(crate) fn io(error: io::Error) -> Self {
let code = ErrorCode::Io(error);
Self::from_inner(code, 0)
}
#[inline]
fn from_inner(code: ErrorCode, index: usize) -> Self {
Error {
err: Box::new(ErrorImpl { code, index }),
}
}
}
impl fmt::Debug for Error {
// todo: improve error message format
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.err.index == 0 {
fmt::Display::fmt(&self.err.code, f)
} else {
write!(f, "{} at index {}", self.err.code, self.err.index)
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&*self.err, f)
}
}
impl fmt::Display for ErrorImpl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.index == 0 {
fmt::Display::fmt(&self.code, f)
} else {
// todo: improve message format
write!(f, "{} at index {}", self.code, self.index)
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &*self {
ErrorCode::Message(ref msg) => f.write_str(msg),
ErrorCode::Io(ref err) => fmt::Display::fmt(err, f),
ErrorCode::UnsupportedType => f.write_str("unsupported nbt type"),
ErrorCode::UnsupportedListInnerType => f.write_str("unsupported list-wrapped type"),
ErrorCode::InvalidStringLength => f.write_str("invalid string length"),
ErrorCode::KeyMustBeAString => f.write_str("key must be a string"),
ErrorCode::SequenceSizeUnknown => f.write_str("size of sequence is unknown"),
ErrorCode::SequenceDifferentType => {
f.write_str("elements of one sequence do not have the same type")
}
ErrorCode::InvalidBoolByte => f.write_str("invalid boolean byte"),
}
}
}
impl std::error::Error for Error {}
impl ser::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
let string = msg.to_string();
let code = ErrorCode::Message(string.into_boxed_str());
Self::from_inner(code, 0)
}
}
impl de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
let string = msg.to_string();
let code = ErrorCode::Message(string.into_boxed_str());
Self::from_inner(code, 0)
}
}
impl From<io::Error> for Error {
fn from(src: io::Error) -> Error {
Error::io(src)
}
}
|
use crate::blog::Blog;
use crate::shared::path_title;
use crate::tag::Tag;
use std::collections::HashMap;
use std::str;
use std::string::String;
// Currently just index of a blog or tag in vector
pub type BlogHandle = usize;
pub type TagHandle = usize;
// Construction procedure:
// BlogCluster construction
// Add tags
// Insert blogs(after tags were added because tags in metadata of articles needs validation)
// Squash time to comparable format
fn time_squash<T: Into<u64>>(year: T, month: T, day: T) -> u64 {
year.into() * 1024 + month.into() * 64 + day.into()
}
pub struct BlogClusters {
//blog_map: HashMap<String, BlogHandle>, // currently not used
tag_map: HashMap<String, TagHandle>, // map tag name to index of tag in tag vector
tags: Vec<Tag>, // Follow the order of tags in tag file
blogs: Vec<Blog>, // Follow the order of blog creation date
tag_blog_map: HashMap<TagHandle, Vec<BlogHandle>>, // map tag handle to handles of blog referencing it
}
impl BlogClusters {
pub fn new() -> BlogClusters {
BlogClusters {
tag_map: HashMap::new(),
tags: Vec::new(),
blogs: Vec::new(),
tag_blog_map: HashMap::new(),
}
}
// used when parse tag file
// return if add successfully
// when tag_name is present, description is not updated
fn add_tag(&mut self, tag_name: String, tag_desc: String) -> Option<TagHandle> {
if self.tag_map.contains_key(&tag_name) {
None
} else {
let tag_handle = self.tags.len();
self.tags.push(Tag::new(tag_name.clone(), tag_desc));
self.tag_map.insert(tag_name, tag_handle);
Some(tag_handle)
}
}
// Assume there is a overall tags file
// contains things like this:
// ```
// tagname
// description
// (serveral no letter lines)
// tagname
// description
// (serveral no letter lines)
// tagname
// description
// ...
// (serveral no letter lines)
// tagname
// description
// ```
pub fn add_tags(&mut self, tags_raw: &str) {
let mut name_found = false;
let mut tag_name = String::new();
let lines: Vec<&str> = tags_raw.lines().map(|x| x.trim()).collect();
for line in lines {
if !line.is_empty() {
let line = line.to_string();
if name_found {
// actually this `.clone()` is just useless, rust lifetime
// analyzer is broken on complicated situation like this.
// :-/
match self.add_tag(tag_name.clone(), line) {
Some(tag_handle) => {
self.tag_blog_map.insert(tag_handle, Vec::new());
}
None => panic!("Duplicate tag name found."),
}
} else {
tag_name = line;
}
name_found = !name_found;
}
}
}
// Should call add_tags before calling this.
// blog_mds: blog filename and blog content in markdown with metadata
// PS: blog_name is used for checking if the title in the file is corresponding
pub fn add_blogs(&mut self, blog_mds: &[(String, String)]) {
// Insert blogs to blog vector
for (blog_path_title, blog) in blog_mds {
let mut line_it = blog.lines();
// First line is title
let title = line_it.next().unwrap().trim();
// We need to ensure title in content is roughly the same as file
// name. The path_title is only used for validation, the title
// stored is unprocessed.
assert_eq!(
&path_title(title),
&path_title(blog_path_title),
"Incorrespondence between filename and title"
);
// Second line is time: `2000 / 9 / 27`
let time = line_it
.next()
.unwrap()
.split('/')
.map(|x| x.trim().parse().expect("Invalid time."))
.collect::<Vec<i64>>();
assert_eq!(3, time.len(), "Invalid time format.");
// Third line is tags: `aaa | bbb | ccc | ...`
let tag_names = line_it
.next()
.unwrap()
.split('|')
.map(|x| x.trim()) // permits arbitrary spaces between time and seperator
.collect::<Vec<&str>>();
let tag_handles = tag_names
.into_iter()
.map(|x| *self.get_tag_handle(x).expect("Invalid tag name."))
.collect::<Vec<TagHandle>>();
// Assme there is no "---" in article content.
// Emmm.... This is not a legit assumption, we can change it later
let mut parts = blog.split("---");
// Assume there always three parts:
// Meta Data
// ---
// Preview
// ---
// Content
// Just ignore the metadata, because we have parsed it.
parts.next().expect("Where is the meta data?");
// Wrapping white spaces in preview and content is legal.
// Get the preview part
let preview = parts.next().expect("Where is the preview?").trim();
// Get the content part
let content = parts.next().expect("Where is the content?").trim();
self.blogs.push(Blog::new(
time[0],
time[1],
time[2],
title.to_string(),
tag_handles.clone(),
preview.to_string(),
content.to_string(),
));
}
// Sort blog vector by time, from new to old
self.blogs.sort_by(|a, b| {
time_squash(b.year, b.month, b.day).cmp(&time_squash(a.year, a.month, a.day))
});
// Map tag_handle-blog_handle pair
for (i, blog) in self.blogs.iter().enumerate() {
// Gen handle of current blog(just the index)
let blog_handle = i;
for tag_handle in &blog.tags {
// We know this tag_handle is always valid
self.tag_blog_map
.get_mut(&tag_handle)
.unwrap()
.push(blog_handle);
}
}
}
fn get_tag_handle(&self, tag_name: &str) -> Option<&TagHandle> {
self.tag_map.get(tag_name)
}
pub fn get_tag(&self, tag_handle: TagHandle) -> Option<&Tag> {
self.tags.get(tag_handle)
}
pub fn get_tags(&self) -> &Vec<Tag> {
&self.tags
}
pub fn get_blogs(&self) -> &Vec<Blog> {
&self.blogs
}
pub fn num_blog(&self) -> usize {
self.blogs.len()
}
pub fn num_tag(&self) -> usize {
self.tags.len()
}
}
#[cfg(test)]
mod blog_cluster_tests {
use super::*;
#[test]
fn test_time_squashing() {
assert!(time_squash(2000u64, 9, 27) < time_squash(2001u64, 8, 13));
assert!(time_squash(2000u64, 9, 27) > time_squash(1997u64, 5, 27));
}
#[test]
fn test_tag_parsing() {
let mut clusters = BlogClusters::new();
clusters.add_tags(
"life
things about current life
work
about my works
fun
maybe some gameplay
tech
be geek about hardware and software
proramming
programming techniques",
);
assert_eq!(5, clusters.num_tag());
}
#[test]
#[should_panic]
fn test_tag_duplication() {
let mut clusters = BlogClusters::new();
clusters.add_tags(
"
life
things about current life
life
things about current life
",
);
}
#[test]
fn test_blog_adding() {
let mut clusters = BlogClusters::new();
clusters.add_tags(
"life
things about current life
work
about my works
fun
maybe some gameplay",
);
clusters.add_blogs(&vec![(
"test-blog".to_string(),
"Test Blog
2000/9/27
life | work | fun
---
lolololololol
---
ololololololo
"
.to_string(),
)]);
let blogs = clusters.get_blogs();
assert_eq!(blogs.len(), 1);
let blog = &blogs[0];
assert_eq!(blog.year, 2000);
assert_eq!(blog.month, 9);
assert_eq!(blog.day, 27);
assert_eq!(blog.tags.len(), 3);
assert_eq!(blog.title, "Test Blog");
assert_eq!(blog.preview, "lolololololol");
assert_eq!(blog.content, "ololololololo");
}
}
|
pub mod nacp;
pub mod nxo;
pub mod pfs0;
pub mod romfs;
pub mod npdm;
mod utils;
|
use crate::prelude::*;
use std::os::raw::c_void;
use std::ptr;
#[repr(C)]
#[derive(Debug)]
pub struct VkMacOSSurfaceCreateInfoMVK {
pub sType: VkStructureType,
pub pNext: *const c_void,
pub flags: VkMacOSSurfaceCreateFlagBitsMVK,
pub pView: *const c_void,
}
impl VkMacOSSurfaceCreateInfoMVK {
// TODO: replace 'U' with the actual type of a macos view
pub fn new<T, U>(flags: T, view: &U) -> Self
where
T: Into<VkMacOSSurfaceCreateFlagBitsMVK>,
{
VkMacOSSurfaceCreateInfoMVK {
sType: VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK,
pNext: ptr::null(),
flags: flags.into(),
pView: view as *const U as *const c_void,
}
}
}
|
//! Task notification.
#[macro_use]
mod poll;
mod spawn;
pub use self::spawn::{Spawn, LocalSpawn, SpawnError};
#[doc(hidden)]
pub mod __internal;
pub use core::task::{Context, Poll, Waker, RawWaker, RawWakerVTable};
|
use super::super::types::DBConnection;
use super::super::ClientExtra;
pub fn get(conn: &DBConnection, node_name: &str) -> postgres::Result<Option<ClientExtra>> {
ctrace!("Query client extra by name {}", node_name);
let rows = conn.query("SELECT * FROM client_extra WHERE name=$1;", &[&node_name])?;
if rows.is_empty() {
return Ok(None)
}
let row = rows.get(0);
Ok(Some(ClientExtra {
prev_env: row.get("prev_env"),
prev_args: row.get("prev_args"),
}))
}
pub fn upsert(conn: &DBConnection, node_name: &str, client_extra: &ClientExtra) -> postgres::Result<()> {
ctrace!("Upsert client extra {:?}", client_extra);
let result = conn.execute(
"INSERT INTO client_extra (name, prev_env, prev_args) VALUES ($1, $2, $3) \
ON CONFLICT (name) DO UPDATE \
SET prev_env=excluded.prev_env, \
prev_args=excluded.prev_args",
&[&node_name, &client_extra.prev_env, &client_extra.prev_args],
)?;
ctrace!("Upsert result {}", result);
Ok(())
}
|
use std::fmt;
use std::ops::{
Add,
AddAssign,
Div,
DivAssign,
Index,
Mul,
MulAssign,
Neg,
Sub,
};
use crate::util::{random_double, random_double_range};
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Vec3(f64, f64, f64);
pub type Point3 = Vec3;
pub type Color = Vec3;
impl Vec3 {
pub fn new(x: f64, y: f64, z: f64) -> Self {
Vec3(x, y, z)
}
pub fn x(self) -> f64 { self.0 }
pub fn y(self) -> f64 { self.1 }
pub fn z(self) -> f64 { self.2 }
pub fn length(self) -> f64 {
self.length_squared().sqrt()
}
pub fn length_squared(self) -> f64 {
self.0*self.0 + self.1*self.1 + self.2*self.2
}
pub fn dot(self, other: Self) -> f64 {
self.0 * other.0 +
self.1 * other.1 +
self.2 * other.2
}
pub fn cross(self, other: Self) -> Self {
Vec3(
self.1 * other.2 - self.2 * other.1,
self.2 * other.0 - self.0 * other.2,
self.0 * other.1 - self.1 * other.0,
)
}
pub fn unit_vector(self) -> Self {
self / self.length()
}
pub fn near_zero(self) -> bool {
let s = 1e-8;
self.0.abs() < s && self.1.abs() < s && self.2.abs() < s
}
pub fn reflect(self, normal: Vec3) -> Self {
self - 2.0 * self.dot(normal) * normal
}
pub fn refract(self, n: Vec3, etai_over_etat: f64) -> Self {
let cos_theta = n.dot(-self).min(1.0);
let r_out_perp = etai_over_etat * (self + cos_theta*n);
let r_out_parallel = -(1.0 - r_out_perp.length_squared()).abs().sqrt() * n;
r_out_perp + r_out_parallel
}
pub fn random() -> Self {
Vec3(random_double(), random_double(), random_double())
}
pub fn random_range(min: f64, max: f64) -> Self {
Vec3(
random_double_range(min, max),
random_double_range(min, max),
random_double_range(min, max),
)
}
pub fn random_in_unit_sphere() -> Self {
loop {
let p = Self::random_range(-1.0, 1.0);
if p.length_squared() < 1.0 { return p; }
}
}
pub fn random_unit_vector() -> Self {
Self::random_in_unit_sphere().unit_vector()
}
pub fn random_in_hemisphere(normal: Vec3) -> Self {
let in_unit_sphere = Self::random_in_unit_sphere();
if in_unit_sphere.dot(normal) > 0.0 { // In the same hemisphere as the normal
in_unit_sphere
} else {
-in_unit_sphere
}
}
pub fn random_in_unit_disk() -> Self {
loop {
let p = Vec3::new(random_double_range(-1.0, 1.0), random_double_range(-1.0, 1.0), 0.0);
if p.length_squared() < 1.0 { return p; }
}
}
}
impl fmt::Display for Vec3 {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {}", self.0, self.1, self.2)
}
}
impl Neg for Vec3 {
type Output = Self;
fn neg(self) -> Self::Output {
Vec3(-self.0, -self.1, -self.2)
}
}
impl Index<usize> for Vec3 {
type Output = f64;
fn index(&self, i: usize) -> &Self::Output {
match i {
0 => &self.0,
1 => &self.1,
2 => &self.2,
_ => panic!("index for out of bounds for Vec3"),
}
}
}
impl Add for Vec3 {
type Output = Vec3;
fn add(self, other: Self) -> Self {
Vec3(self.0 + other.0, self.1 + other.1, self.2 + other.2)
}
}
impl AddAssign for Vec3 {
fn add_assign(&mut self, other: Self) {
self.0 += other.0;
self.1 += other.1;
self.2 += other.2;
}
}
impl Sub for Vec3 {
type Output = Vec3;
fn sub(self, other: Self) -> Self {
Vec3(self.0 - other.0, self.1 - other.1, self.2 - other.2)
}
}
impl Mul for Vec3 {
type Output = Vec3;
fn mul(self, other: Self) -> Self {
Vec3(self.0 * other.0, self.1 * other.1, self.2 * other.2)
}
}
impl Mul<Vec3> for f64 {
type Output = Vec3;
fn mul(self, other: Vec3) -> Vec3 {
Vec3(self * other.0, self * other.1, self * other.2)
}
}
impl Mul<f64> for Vec3 {
type Output = Self;
fn mul(self, t: f64) -> Vec3 {
t * self
}
}
impl MulAssign<f64> for Vec3 {
fn mul_assign(&mut self, t: f64) {
self.0 *= t;
self.1 *= t;
self.2 *= t;
}
}
impl Div<f64> for Vec3 {
type Output = Self;
fn div(self, t: f64) -> Vec3 {
(1.0/t) * self
}
}
impl DivAssign<f64> for Vec3 {
fn div_assign(&mut self, t: f64) {
*self *= 1.0/t;
}
}
|
//! Массив этажей
//!
//! Каждый элемент массива - отдельный этаж, со всеми графическими элементами
mod beam;
mod column;
mod diagram;
mod f_beam;
mod f_slab;
mod found;
mod lean_on_slab;
mod load;
mod node;
mod openings;
mod part;
mod pile;
mod poly;
mod sec;
mod sigs_raw;
mod slab;
mod unification_found;
mod unification_slab;
mod unification_wall_slit;
mod wall;
pub mod rab_e;
pub mod rab_e_raw;
use crate::sig::HasWrite;
use nom::{number::complete::le_f32, IResult};
use std::fmt;
#[derive(Debug)]
pub struct Point {
pub(crate) x: f32, //Координата, м
pub(crate) y: f32, //Координата, м
}
impl HasWrite for Point {
fn write(&self) -> Vec<u8> {
let mut out = vec![];
out.extend(&self.x.to_le_bytes());
out.extend(&self.y.to_le_bytes());
out
}
fn name(&self) -> &str {
""
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "x: {:.3}, y: {:.3}", &self.x, &self.y)
}
}
pub fn read_point(i: &[u8]) -> IResult<&[u8], Point> {
let (i, x) = le_f32(i)?;
let (i, y) = le_f32(i)?;
Ok((i, Point { x, y }))
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use libc;
use std::io;
use std::os::unix::io::{AsRawFd, RawFd};
use alloc::string::ToString;
use super::super::qlib::common::*;
use super::super::qlib::cstring::*;
const DEFAULT_PTMX: &'static str = "/dev/ptmx";
pub fn NewPty() -> Result<(Master, Slave)> {
let master = NewMaster()?;
master.grantpt()?;
master.unlockpt()?;
let slave = master.NewSlave()?;
return Ok((master, slave))
}
pub fn NewMaster() -> Result<Master> {
let cstr = CString::New(DEFAULT_PTMX);
return Master::new(cstr.Ptr() as * const libc::c_char)
}
pub trait Descriptor: AsRawFd {
/// The constructor function `open` opens the path
/// and returns the fd.
fn open(path: *const libc::c_char,
flag: i32,
mode: Option<i32>)
-> Result<RawFd> {
unsafe {
match libc::open(path, flag, mode.unwrap_or_default()) {
-1 => Err(Error::SysError(-errno::errno().0)),
fd => {
Ok(fd)
},
}
}
}
/// The function `close` leaves the fd.
fn close(&self) -> Result<()> {
unsafe {
match libc::close(self.as_raw_fd()) {
-1 => Err(Error::SysError(-errno::errno().0)),
_ => Ok(()),
}
}
}
/// The destructor function `drop` call the method `close`
/// and panic if a error is occurred.
fn drop(&self) {
if self.close().is_err() {
unimplemented!();
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Master {
pub pty: RawFd,
}
impl Master {
pub fn new(path: *const ::libc::c_char) -> Result<Self> {
info!("before open");
let res = match Self::open(path, libc::O_RDWR, None) {
Err(e) => Err(e),
Ok(fd) => Ok(Master { pty: fd }),
};
info!("after open");
return res;
}
/// Change UID and GID of slave pty associated with master pty whose
/// fd is provided, to the real UID and real GID of the calling thread.
pub fn grantpt(&self) -> Result<i32> {
unsafe {
match libc::grantpt(self.as_raw_fd()) {
-1 => Err(Error::SysError(-errno::errno().0)),
c => Ok(c),
}
}
}
/// Unlock the slave pty associated with the master to which fd refers.
pub fn unlockpt(&self) -> Result<i32> {
unsafe {
match libc::unlockpt(self.as_raw_fd()) {
-1 => Err(Error::SysError(-errno::errno().0)),
c => Ok(c),
}
}
}
/// Returns a pointer to a static buffer, which will be overwritten on
/// subsequent calls.
pub fn ptsname(&self) -> Result<*const libc::c_char> {
unsafe {
match libc::ptsname(self.as_raw_fd()) {
c if c.is_null() => Err(Error::Common("ptsname fail with NULL".to_string())),
c => Ok(c),
}
}
}
pub fn NewSlave(&self) -> Result<Slave> {
let ptsname = self.ptsname()?;
let res = Slave::new(ptsname);
return res;
}
}
impl Descriptor for Master {}
impl AsRawFd for Master {
/// The accessor function `as_raw_fd` returns the fd.
fn as_raw_fd(&self) -> RawFd {
self.pty
}
}
impl io::Read for Master {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
unsafe {
match libc::read(self.as_raw_fd(),
buf.as_mut_ptr() as *mut libc::c_void,
buf.len()) {
-1 => Ok(0),
len => Ok(len as usize),
}
}
}
}
impl io::Write for Master {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
unsafe {
match libc::write(self.as_raw_fd(),
buf.as_ptr() as *const libc::c_void,
buf.len()) {
-1 => Err(io::Error::last_os_error()),
ret => Ok(ret as usize),
}
}
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct Slave {
pub pty: RawFd,
}
impl Slave {
/// The constructor function `new` returns the Slave interface.
pub fn new(path: *const ::libc::c_char) -> Result<Self> {
info!("Slave::new");
match Self::open(path, libc::O_RDWR, None) {
Err(e) => Err(e),
Ok(fd) => Ok(Slave { pty: fd }),
}
}
pub fn dup2(&self, std: i32) -> Result<i32> {
unsafe {
match libc::dup2(self.as_raw_fd(), std) {
-1 => Err(Error::SysError(-errno::errno().0)),
d => Ok(d),
}
}
}
pub fn dup(&self) -> Result<i32> {
unsafe {
match libc::dup(self.as_raw_fd()) {
-1 => Err(Error::SysError(-errno::errno().0)),
d => Ok(d),
}
}
}
}
impl Descriptor for Slave {}
impl AsRawFd for Slave {
/// The accessor function `as_raw_fd` returns the fd.
fn as_raw_fd(&self) -> RawFd {
self.pty
}
}
/*
impl Drop for Slave {
fn drop(&mut self) {
Descriptor::drop(self);
}
}*/ |
// Copyright (c) 2017 Martijn Rijkeboer <mrr@sru-systems.com>
//
// 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 crate::error::Error;
use crate::result::Result;
use std::fmt;
/// The Argon2 version.
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub enum Version {
/// Version 0x10.
Version10 = 0x10,
/// Version 0x13 (Recommended).
Version13 = 0x13,
}
impl Version {
/// Gets the u32 representation of the version.
pub fn as_u32(&self) -> u32 {
*self as u32
}
/// Attempts to create a version from a string slice.
pub fn from_str(str: &str) -> Result<Version> {
match str {
"16" => Ok(Version::Version10),
"19" => Ok(Version::Version13),
_ => Err(Error::DecodingFail),
}
}
/// Attempts to create a version from an u32.
pub fn from_u32(val: u32) -> Result<Version> {
match val {
0x10 => Ok(Version::Version10),
0x13 => Ok(Version::Version13),
_ => Err(Error::IncorrectVersion),
}
}
}
impl Default for Version {
fn default() -> Version {
Version::Version13
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_u32())
}
}
#[cfg(test)]
mod tests {
use crate::error::Error;
use crate::version::Version;
#[test]
fn as_u32_returns_correct_u32() {
assert_eq!(Version::Version10.as_u32(), 0x10);
assert_eq!(Version::Version13.as_u32(), 0x13);
}
#[test]
fn default_returns_correct_version() {
assert_eq!(Version::default(), Version::Version13);
}
#[test]
fn display_returns_correct_string() {
assert_eq!(format!("{}", Version::Version10), "16");
assert_eq!(format!("{}", Version::Version13), "19");
}
#[test]
fn from_str_returns_correct_result() {
assert_eq!(Version::from_str("16"), Ok(Version::Version10));
assert_eq!(Version::from_str("19"), Ok(Version::Version13));
assert_eq!(Version::from_str("11"), Err(Error::DecodingFail));
}
#[test]
fn from_u32_returns_correct_result() {
assert_eq!(Version::from_u32(0x10), Ok(Version::Version10));
assert_eq!(Version::from_u32(0x13), Ok(Version::Version13));
assert_eq!(Version::from_u32(0), Err(Error::IncorrectVersion));
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// From <linux/futex.h> and <sys/time.h>.
// Flags are used in syscall futex(2).
pub const FUTEX_WAIT: i32 = 0;
pub const FUTEX_WAKE: i32 = 1;
pub const FUTEX_FD: i32 = 2;
pub const FUTEX_REQUEUE: i32 = 3;
pub const FUTEX_CMP_REQUEUE: i32 = 4;
pub const FUTEX_WAKE_OP: i32 = 5;
pub const FUTEX_LOCK_PI: i32 = 6;
pub const FUTEX_UNLOCK_PI: i32 = 7;
pub const FUTEX_TRYLOCK_PI: i32 = 8;
pub const FUTEX_WAIT_BITSET: i32 = 9;
pub const FUTEX_WAKE_BITSET: i32 = 10;
pub const FUTEX_WAIT_REQUEUE_PI: i32 = 11;
pub const FUTEX_CMP_REQUEUE_PI: i32 = 12;
pub const FUTEX_PRIVATE_FLAG: i32 = 128;
pub const FUTEX_CLOCK_REALTIME: i32 = 256;
// These are flags are from <linux/futex.h> and are used in FUTEX_WAKE_OP
// to define the operations.
pub const FUTEX_OP_SET: u32 = 0;
pub const FUTEX_OP_ADD: u32 = 1;
pub const FUTEX_OP_OR: u32 = 2;
pub const FUTEX_OP_ANDN: u32 = 3;
pub const FUTEX_OP_XOR: u32 = 4;
pub const FUTEX_OP_OPARG_SHIFT: u32 = 8;
pub const FUTEX_OP_CMP_EQ: u32 = 0;
pub const FUTEX_OP_CMP_NE: u32 = 1;
pub const FUTEX_OP_CMP_LT: u32 = 2;
pub const FUTEX_OP_CMP_LE: u32 = 3;
pub const FUTEX_OP_CMP_GT: u32 = 4;
pub const FUTEX_OP_CMP_GE: u32 = 5;
// FUTEX_TID_MASK is the TID portion of a PI futex word.
pub const FUTEX_TID_MASK: u32 = 0x3fffffff;
// Constants used for priority-inheritance futexes.
pub const FUTEX_WAITERS: u32 = 0x80000000;
pub const FUTEX_OWNER_DIED: u32 = 0x40000000;
// FUTEX_BITSET_MATCH_ANY has all bits set.
pub const FUTEX_BITSET_MATCH_ANY : u32 = 0xffffffff;
// ROBUST_LIST_LIMIT protects against a deliberately circular list.
pub const ROBUST_LIST_LIMIT : u32 = 2048;
// RobustListHead corresponds to Linux's struct robust_list_head.
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct RobustListHead {
pub List : u64,
pub FutexOffset : u64,
pub ListOpPending : u64,
} |
use crate::backend::c;
/// A signal number for use with [`kill_process`], [`kill_process_group`],
/// and [`kill_current_process_group`].
///
/// [`kill_process`]: crate::process::kill_process
/// [`kill_process_group`]: crate::process::kill_process_group
/// [`kill_current_process_group`]: crate::process::kill_current_process_group
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(i32)]
pub enum Signal {
/// `SIGHUP`
Hup = c::SIGHUP,
/// `SIGINT`
Int = c::SIGINT,
/// `SIGQUIT`
Quit = c::SIGQUIT,
/// `SIGILL`
Ill = c::SIGILL,
/// `SIGTRAP`
Trap = c::SIGTRAP,
/// `SIGABRT`, aka `SIGIOT`
#[doc(alias = "Iot")]
#[doc(alias = "Abrt")]
Abort = c::SIGABRT,
/// `SIGBUS`
Bus = c::SIGBUS,
/// `SIGFPE`
Fpe = c::SIGFPE,
/// `SIGKILL`
Kill = c::SIGKILL,
/// `SIGUSR1`
Usr1 = c::SIGUSR1,
/// `SIGSEGV`
Segv = c::SIGSEGV,
/// `SIGUSR2`
Usr2 = c::SIGUSR2,
/// `SIGPIPE`
Pipe = c::SIGPIPE,
/// `SIGALRM`
#[doc(alias = "Alrm")]
Alarm = c::SIGALRM,
/// `SIGTERM`
Term = c::SIGTERM,
/// `SIGSTKFLT`
#[cfg(not(any(
bsd,
solarish,
target_os = "aix",
target_os = "haiku",
target_os = "nto",
all(
linux_kernel,
any(
target_arch = "mips",
target_arch = "mips32r6",
target_arch = "mips64",
target_arch = "mips64r6",
target_arch = "sparc",
target_arch = "sparc64"
),
)
)))]
Stkflt = c::SIGSTKFLT,
/// `SIGCHLD`
#[doc(alias = "Chld")]
Child = c::SIGCHLD,
/// `SIGCONT`
Cont = c::SIGCONT,
/// `SIGSTOP`
Stop = c::SIGSTOP,
/// `SIGTSTP`
Tstp = c::SIGTSTP,
/// `SIGTTIN`
Ttin = c::SIGTTIN,
/// `SIGTTOU`
Ttou = c::SIGTTOU,
/// `SIGURG`
Urg = c::SIGURG,
/// `SIGXCPU`
Xcpu = c::SIGXCPU,
/// `SIGXFSZ`
Xfsz = c::SIGXFSZ,
/// `SIGVTALRM`
#[doc(alias = "Vtalrm")]
Vtalarm = c::SIGVTALRM,
/// `SIGPROF`
Prof = c::SIGPROF,
/// `SIGWINCH`
Winch = c::SIGWINCH,
/// `SIGIO`, aka `SIGPOLL`
#[doc(alias = "Poll")]
#[cfg(not(target_os = "haiku"))]
Io = c::SIGIO,
/// `SIGPWR`
#[cfg(not(any(bsd, target_os = "haiku")))]
#[doc(alias = "Pwr")]
Power = c::SIGPWR,
/// `SIGSYS`, aka `SIGUNUSED`
#[doc(alias = "Unused")]
Sys = c::SIGSYS,
/// `SIGEMT`
#[cfg(any(
bsd,
solarish,
target_os = "aix",
target_os = "hermit",
all(
linux_kernel,
any(
target_arch = "mips",
target_arch = "mips32r6",
target_arch = "mips64",
target_arch = "mips64r6",
target_arch = "sparc",
target_arch = "sparc64"
)
)
))]
Emt = c::SIGEMT,
/// `SIGINFO`
#[cfg(bsd)]
Info = c::SIGINFO,
/// `SIGTHR`
#[cfg(target_os = "freebsd")]
#[doc(alias = "Lwp")]
Thr = c::SIGTHR,
/// `SIGLIBRT`
#[cfg(target_os = "freebsd")]
Librt = c::SIGLIBRT,
}
impl Signal {
/// Convert a raw signal number into a `Signal`, if possible.
pub fn from_raw(sig: c::c_int) -> Option<Self> {
match sig {
c::SIGHUP => Some(Self::Hup),
c::SIGINT => Some(Self::Int),
c::SIGQUIT => Some(Self::Quit),
c::SIGILL => Some(Self::Ill),
c::SIGTRAP => Some(Self::Trap),
c::SIGABRT => Some(Self::Abort),
c::SIGBUS => Some(Self::Bus),
c::SIGFPE => Some(Self::Fpe),
c::SIGKILL => Some(Self::Kill),
c::SIGUSR1 => Some(Self::Usr1),
c::SIGSEGV => Some(Self::Segv),
c::SIGUSR2 => Some(Self::Usr2),
c::SIGPIPE => Some(Self::Pipe),
c::SIGALRM => Some(Self::Alarm),
c::SIGTERM => Some(Self::Term),
#[cfg(not(any(
bsd,
solarish,
target_os = "aix",
target_os = "haiku",
target_os = "nto",
all(
linux_kernel,
any(
target_arch = "mips",
target_arch = "mips32r6",
target_arch = "mips64",
target_arch = "mips64r6",
target_arch = "sparc",
target_arch = "sparc64"
),
)
)))]
c::SIGSTKFLT => Some(Self::Stkflt),
c::SIGCHLD => Some(Self::Child),
c::SIGCONT => Some(Self::Cont),
c::SIGSTOP => Some(Self::Stop),
c::SIGTSTP => Some(Self::Tstp),
c::SIGTTIN => Some(Self::Ttin),
c::SIGTTOU => Some(Self::Ttou),
c::SIGURG => Some(Self::Urg),
c::SIGXCPU => Some(Self::Xcpu),
c::SIGXFSZ => Some(Self::Xfsz),
c::SIGVTALRM => Some(Self::Vtalarm),
c::SIGPROF => Some(Self::Prof),
c::SIGWINCH => Some(Self::Winch),
#[cfg(not(target_os = "haiku"))]
c::SIGIO => Some(Self::Io),
#[cfg(not(any(bsd, target_os = "haiku")))]
c::SIGPWR => Some(Self::Power),
c::SIGSYS => Some(Self::Sys),
#[cfg(any(
bsd,
solarish,
target_os = "aix",
target_os = "hermit",
all(
linux_kernel,
any(
target_arch = "mips",
target_arch = "mips32r6",
target_arch = "mips64",
target_arch = "mips64r6",
target_arch = "sparc",
target_arch = "sparc64"
)
)
))]
c::SIGEMT => Some(Self::Emt),
#[cfg(bsd)]
c::SIGINFO => Some(Self::Info),
#[cfg(target_os = "freebsd")]
c::SIGTHR => Some(Self::Thr),
#[cfg(target_os = "freebsd")]
c::SIGLIBRT => Some(Self::Librt),
_ => None,
}
}
}
#[test]
fn test_sizes() {
assert_eq_size!(Signal, c::c_int);
}
|
//!
//! Create `enum` objects
//!
//!
//! Example
//! -------
//! ```
//! use proffer::*;
//!
//! let e = Enum::new("Foo")
//! .add_variant(Variant::new("A"))
//! .add_variant(Variant::new("B").set_inner(Some("(T)")).to_owned())
//! .add_generic(Generic::new("T"))
//! .to_owned();
//!
//! let src_code = e.generate();
//! let expected = r#"
//! enum Foo<T>
//! where
//! T: ,
//! {
//! A,
//! B(T),
//! }
//! "#;
//! assert_eq!(norm_whitespace(expected), norm_whitespace(&src_code))
//! ```
use serde::Serialize;
use crate::*;
use tera::{Context, Tera};
/// Represent an `enum` object
#[derive(Default, Serialize, Clone)]
pub struct Enum {
name: String,
generics: Vec<Generic>,
is_pub: bool,
variants: Vec<Variant>,
}
/// Represent an enum variant/arm
#[derive(Default, Serialize, Clone)]
pub struct Variant {
name: String,
inner: Option<String>,
}
impl Enum {
/// Create a new `Enum`
pub fn new(name: impl ToString) -> Self {
Self {
name: name.to_string(),
..Self::default()
}
}
/// Set if this is public
pub fn set_is_pub(&mut self, is_pub: bool) -> &mut Self {
self.is_pub = is_pub;
self
}
/// Add a variant
pub fn add_variant(&mut self, variant: Variant) -> &mut Self {
self.variants.push(variant);
self
}
}
impl Variant {
/// Create a new variant to add to an `Enum`
pub fn new(name: impl ToString) -> Self {
Self {
name: name.to_string(),
..Self::default()
}
}
/// Set the inner portion of this variant, expected to be valid Rust source code.
pub fn set_inner(&mut self, inner: Option<impl ToString>) -> &mut Self {
self.inner = inner.map(|s| s.to_string());
self
}
}
impl SrcCode for Variant {
fn generate(&self) -> String {
let template = r#"{{ self.name }}{{ inner }}"#;
let mut ctx = Context::new();
ctx.insert("self", &self);
ctx.insert("inner", &self.inner.as_ref().unwrap_or(&"".to_string()));
Tera::one_off(template, &ctx, false).unwrap()
}
}
impl internal::Generics for Enum {
fn generics_mut(&mut self) -> &mut Vec<Generic> {
&mut self.generics
}
fn generics(&self) -> &[Generic] {
self.generics.as_slice()
}
}
impl SrcCode for Enum {
fn generate(&self) -> String {
let template = r#"
{% if self.is_pub %}pub {% endif %}enum {{ self.name }}{{ generics }}
{
{% for variant in variants %}{{ variant }},
{% endfor %}
}
"#;
let mut ctx = Context::new();
ctx.insert("self", &self);
ctx.insert("generics", &self.generics.generate());
ctx.insert("variants", &self.variants.to_src_vec());
Tera::one_off(template, &ctx, false).unwrap()
}
}
|
#[macro_use]
mod macros;
mod core;
pub use crate::core::TestDir;
|
/* multi-line comment */
// fn is keyword for function
// main is a mandatory function name, similar to C, C++, Java
// repl.it can be used as a web-based compiler to avoid having to compile on your computer each time
// play.rust-lang.org is also provided by the creators of Rust as a sandbox
fn main () {
println!("Hello, World!");
// print with placeholder
println!("{}", "Hello, World!");
// placeholder can also be used to print numeric values
println!("{}", "2");
// placeholders can also be used to print variables
let a = "This is an arbitrary variable.";
println!("{}", a);
let be = false;
println!("{}", be);
println!("{}", !be);
const MAX:i32 = 127;
println!("MAX = {}", MAX);
const MIN:i32 = MAX - 4;
println!("MIN = {}", MIN);
// this is a string from the Rust standard library
let mut s = String::new();
println!("This is the value of a new string s: {}", s);
/*
If you are going to create a string in this way, where an empty string is instantiated above and defined later,
the only way to properly define its value is to use the String::from() method - if you attempt to strictly
define a new value, it will not compile because defining the value of a string directly is defining a string
slice while instantiating an empty string above is the string type from the standard Rust library
*/
s = String::from("Hello");
println!("This is the new value assigned to the string s: {}", s);
// this is a string slice
let str = "Hello";
println!("{}", str);
// below illustrates simple operators in action as well as passing multiple values to a println! function
let mut c = 10;
println!("The initial value of c is {}. In the next line,
it will be incremented by a previously specified value
'MAX', whose value is {}.", c, MAX);
c += MAX;
println!("The new value of c is {}", c);
// shadowing
let d:f32 = 1.32;
println!("The value of d1 - an f32 variable - is {}", d);
let d:i8 = 4;
println!("The value of d2 - an i8 variable - is {}", d);
let d:char = 'c';
println!("The value of d3 - a char variable - is {}", d);
let d:f64 = 1.32;
println!("The value of d4 - an f64 variable - is {}", d);
// typecasting
let f:i32 = 10;
println!("The value of f - an i32 variable - is {}", f);
let g:i64 = f.into();
println!("The value of g - an i64 variable - is {}", g);
let h:i32 = 10;
println!("The value of f - an i32 variable - is {}", h);
let i:f64 = h.into();
println!("The value of g - an f64 variable - is {}", i);
let j:f64 = 47.12485720981247;
println!("The sum of i (which is an f64 variable typecast from h -
an i32 variable with a value of 10) and j (another f64 variable
with a value of 47.12485720981247) is {}", i+j);
// asd
}
|
#![allow(non_upper_case_globals)]
use Word;
// Destination opcodes
const OPCODE_DST_Null : Word = 0b000;
const OPCODE_DST_M : Word = 0b001;
const OPCODE_DST_D : Word = 0b010;
const OPCODE_DST_MD : Word = 0b011;
const OPCODE_DST_A : Word = 0b100;
const OPCODE_DST_AM : Word = 0b101;
const OPCODE_DST_AD : Word = 0b110;
const OPCODE_DST_AMD : Word = 0b111;
// Jump opcodes
const OPCODE_JMP_Null : Word = 0b000;
const OPCODE_JMP_JGT : Word = 0b001;
const OPCODE_JMP_JEQ : Word = 0b010;
const OPCODE_JMP_JGE : Word = 0b011;
const OPCODE_JMP_JLT : Word = 0b100;
const OPCODE_JMP_JNE : Word = 0b101;
const OPCODE_JMP_JLE : Word = 0b110;
const OPCODE_JMP_JMP : Word = 0b111;
// Compute opcodes
const OPCODE_CMP_Zero : Word = 0b0_101010;
const OPCODE_CMP_One : Word = 0b0_111111;
const OPCODE_CMP_NegativeOne : Word = 0b0_111010;
const OPCODE_CMP_D : Word = 0b0_001100;
const OPCODE_CMP_A : Word = 0b0_110000;
const OPCODE_CMP_M : Word = 0b1_110000;
const OPCODE_CMP_NotD : Word = 0b0_001101;
const OPCODE_CMP_NotA : Word = 0b0_110001;
const OPCODE_CMP_NotM : Word = 0b1_110001;
const OPCODE_CMP_NegativeD : Word = 0b0_001111;
const OPCODE_CMP_NegativeA : Word = 0b0_110011;
const OPCODE_CMP_NegativeM : Word = 0b1_110011;
const OPCODE_CMP_DPlusOne : Word = 0b0_011111;
const OPCODE_CMP_APlusOne : Word = 0b0_110111;
const OPCODE_CMP_MPlusOne : Word = 0b1_110111;
const OPCODE_CMP_DMinusOne : Word = 0b0_001110;
const OPCODE_CMP_AMinusOne : Word = 0b0_110010;
const OPCODE_CMP_MMinusOne : Word = 0b1_110010;
const OPCODE_CMP_DPlusA : Word = 0b0_000010;
const OPCODE_CMP_DPlusM : Word = 0b1_000010;
const OPCODE_CMP_DMinusA : Word = 0b0_010011;
const OPCODE_CMP_DMinusM : Word = 0b1_010011;
const OPCODE_CMP_AMinusD : Word = 0b0_000111;
const OPCODE_CMP_MMinusD : Word = 0b1_000111;
const OPCODE_CMP_DAndA : Word = 0b0_000000;
const OPCODE_CMP_DAndM : Word = 0b1_000000;
const OPCODE_CMP_DOrA : Word = 0b0_010101;
const OPCODE_CMP_DOrM : Word = 0b1_010101;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Instruction {
Compute(ComputeInstruction),
Address(Word),
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ComputeInstruction {
pub compute: ComputeOpcode,
pub destination: DestinationOpcode,
pub jump: JumpOpcode,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DestinationOpcode {
Null,
M,
D,
MD,
A,
AM,
AD,
AMD,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum JumpOpcode {
Null,
JGT,
JEQ,
JGE,
JLT,
JNE,
JLE,
JMP,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ComputeOpcode {
Zero,
One,
NegativeOne,
D,
A,
M,
NotD,
NotA,
NotM,
NegativeD,
NegativeA,
NegativeM,
DPlusOne,
APlusOne,
MPlusOne,
DMinusOne,
AMinusOne,
MMinusOne,
DPlusA,
DPlusM,
DMinusA,
DMinusM,
AMinusD,
MMinusD,
DAndA,
DAndM,
DOrA,
DOrM,
}
impl From<ComputeOpcode> for Word {
fn from(opcode: ComputeOpcode) -> Self {
let com_bits = match opcode {
ComputeOpcode::Zero => OPCODE_CMP_Zero,
ComputeOpcode::One => OPCODE_CMP_One,
ComputeOpcode::NegativeOne => OPCODE_CMP_NegativeOne,
ComputeOpcode::D => OPCODE_CMP_D,
ComputeOpcode::A => OPCODE_CMP_A,
ComputeOpcode::M => OPCODE_CMP_M,
ComputeOpcode::NotD => OPCODE_CMP_NotD,
ComputeOpcode::NotA => OPCODE_CMP_NotA,
ComputeOpcode::NotM => OPCODE_CMP_NotM,
ComputeOpcode::NegativeD => OPCODE_CMP_NegativeD,
ComputeOpcode::NegativeA => OPCODE_CMP_NegativeA,
ComputeOpcode::NegativeM => OPCODE_CMP_NegativeM,
ComputeOpcode::DPlusOne => OPCODE_CMP_DPlusOne,
ComputeOpcode::APlusOne => OPCODE_CMP_APlusOne,
ComputeOpcode::MPlusOne => OPCODE_CMP_MPlusOne,
ComputeOpcode::DMinusOne => OPCODE_CMP_DMinusOne,
ComputeOpcode::AMinusOne => OPCODE_CMP_AMinusOne,
ComputeOpcode::MMinusOne => OPCODE_CMP_MMinusOne,
ComputeOpcode::DPlusA => OPCODE_CMP_DPlusA,
ComputeOpcode::DPlusM => OPCODE_CMP_DPlusM,
ComputeOpcode::DMinusA => OPCODE_CMP_DMinusA,
ComputeOpcode::DMinusM => OPCODE_CMP_DMinusM,
ComputeOpcode::AMinusD => OPCODE_CMP_AMinusD,
ComputeOpcode::MMinusD => OPCODE_CMP_MMinusD,
ComputeOpcode::DAndA => OPCODE_CMP_DAndA,
ComputeOpcode::DAndM => OPCODE_CMP_DAndM,
ComputeOpcode::DOrA => OPCODE_CMP_DOrA,
ComputeOpcode::DOrM => OPCODE_CMP_DOrM,
};
(com_bits << 6) | 0xE000
}
}
impl From<Word> for ComputeOpcode {
fn from(word: Word) -> Self {
let com_bits = (word >> 6) & 0b1111111;
match com_bits {
OPCODE_CMP_Zero => ComputeOpcode::Zero,
OPCODE_CMP_One => ComputeOpcode::One,
OPCODE_CMP_NegativeOne => ComputeOpcode::NegativeOne,
OPCODE_CMP_D => ComputeOpcode::D,
OPCODE_CMP_A => ComputeOpcode::A,
OPCODE_CMP_M => ComputeOpcode::M,
OPCODE_CMP_NotD => ComputeOpcode::NotD,
OPCODE_CMP_NotA => ComputeOpcode::NotA,
OPCODE_CMP_NotM => ComputeOpcode::NotM,
OPCODE_CMP_NegativeD => ComputeOpcode::NegativeD,
OPCODE_CMP_NegativeA => ComputeOpcode::NegativeA,
OPCODE_CMP_NegativeM => ComputeOpcode::NegativeM,
OPCODE_CMP_DPlusOne => ComputeOpcode::DPlusOne,
OPCODE_CMP_APlusOne => ComputeOpcode::APlusOne,
OPCODE_CMP_MPlusOne => ComputeOpcode::MPlusOne,
OPCODE_CMP_DMinusOne => ComputeOpcode::DMinusOne,
OPCODE_CMP_AMinusOne => ComputeOpcode::AMinusOne,
OPCODE_CMP_MMinusOne => ComputeOpcode::MMinusOne,
OPCODE_CMP_DPlusA => ComputeOpcode::DPlusA,
OPCODE_CMP_DPlusM => ComputeOpcode::DPlusM,
OPCODE_CMP_DMinusA => ComputeOpcode::DMinusA,
OPCODE_CMP_DMinusM => ComputeOpcode::DMinusM,
OPCODE_CMP_AMinusD => ComputeOpcode::AMinusD,
OPCODE_CMP_MMinusD => ComputeOpcode::MMinusD,
OPCODE_CMP_DAndA => ComputeOpcode::DAndA,
OPCODE_CMP_DAndM => ComputeOpcode::DAndM,
OPCODE_CMP_DOrA => ComputeOpcode::DOrA,
OPCODE_CMP_DOrM => ComputeOpcode::DOrM,
_ => unreachable!(),
}
}
}
impl From<DestinationOpcode> for Word {
fn from(opcode: DestinationOpcode) -> Self {
let dst_bits = match opcode {
DestinationOpcode::Null => OPCODE_DST_Null,
DestinationOpcode::M => OPCODE_DST_M,
DestinationOpcode::D => OPCODE_DST_D,
DestinationOpcode::MD => OPCODE_DST_MD,
DestinationOpcode::A => OPCODE_DST_A,
DestinationOpcode::AM => OPCODE_DST_AM,
DestinationOpcode::AD => OPCODE_DST_AD,
DestinationOpcode::AMD => OPCODE_DST_AMD,
};
(dst_bits << 3) | 0xE000
}
}
impl From<Word> for DestinationOpcode {
fn from(word: Word) -> DestinationOpcode {
let dst_bits = (word >> 3) & 0b111;
match dst_bits {
OPCODE_DST_Null => DestinationOpcode::Null,
OPCODE_DST_M => DestinationOpcode::M,
OPCODE_DST_D => DestinationOpcode::D,
OPCODE_DST_MD => DestinationOpcode::MD,
OPCODE_DST_A => DestinationOpcode::A,
OPCODE_DST_AM => DestinationOpcode::AM,
OPCODE_DST_AD => DestinationOpcode::AD,
OPCODE_DST_AMD => DestinationOpcode::AMD,
_ => unreachable!(),
}
}
}
impl From<JumpOpcode> for Word {
fn from(opcode: JumpOpcode) -> Self {
let jmp_bits = match opcode {
JumpOpcode::Null => OPCODE_JMP_Null,
JumpOpcode::JGT => OPCODE_JMP_JGT,
JumpOpcode::JEQ => OPCODE_JMP_JEQ,
JumpOpcode::JGE => OPCODE_JMP_JGE,
JumpOpcode::JLT => OPCODE_JMP_JLT,
JumpOpcode::JNE => OPCODE_JMP_JNE,
JumpOpcode::JLE => OPCODE_JMP_JLE,
JumpOpcode::JMP => OPCODE_JMP_JMP,
};
jmp_bits | 0xE000
}
}
impl From<Word> for JumpOpcode {
fn from(word: Word) -> Self {
let jmp_op = word & 0b111;
match jmp_op {
OPCODE_JMP_Null => JumpOpcode::Null,
OPCODE_JMP_JGT => JumpOpcode::JGT,
OPCODE_JMP_JEQ => JumpOpcode::JEQ,
OPCODE_JMP_JGE => JumpOpcode::JGE,
OPCODE_JMP_JLT => JumpOpcode::JLT,
OPCODE_JMP_JNE => JumpOpcode::JNE,
OPCODE_JMP_JLE => JumpOpcode::JLE,
OPCODE_JMP_JMP => JumpOpcode::JMP,
_ => unreachable!(),
}
}
}
impl From<ComputeInstruction> for Word {
fn from(instruction: ComputeInstruction) -> Self {
let com_op = Word::from(instruction.compute);
let dst_op = Word::from(instruction.destination);
let jmp_op = Word::from(instruction.jump);
com_op | dst_op | jmp_op
}
}
impl From<Word> for ComputeInstruction {
fn from(word: Word) -> Self {
ComputeInstruction {
compute: word.into(),
destination: word.into(),
jump: word.into(),
}
}
}
impl From<Instruction> for Word {
fn from(instruction: Instruction) -> Self {
match instruction {
Instruction::Address(address) => address,
Instruction::Compute(instruction) => instruction.into(),
}
}
}
impl From<Word> for Instruction {
fn from(word: Word) -> Self {
if word & 0x8000 == 0x8000 {
Instruction::Compute(word.into())
}
else {
Instruction::Address(word)
}
}
}
#[cfg(test)]
mod tests {
use instruction::*;
#[test]
fn translate_compute_instructions() {
// TODO: Implement
}
#[test]
fn translate_address_instructions() {
let tests = vec![
(0b0000_0000_0000_0000, Instruction::Address(0b0000_0000_0000_0000)),
(0b0111_1111_1111_1111, Instruction::Address(0b0111_1111_1111_1111)),
];
for (word, instruction) in tests.into_iter() {
assert_eq!(word, Word::from(instruction));
assert_eq!(Instruction::from(word), instruction);
}
}
#[test]
fn translate_destination_opcodes() {
let tests = vec![
(0b1110000000_000_000, DestinationOpcode::Null),
(0b1110000000_001_000, DestinationOpcode::M),
(0b1110000000_010_000, DestinationOpcode::D),
(0b1110000000_011_000, DestinationOpcode::MD),
(0b1110000000_100_000, DestinationOpcode::A),
(0b1110000000_101_000, DestinationOpcode::AM),
(0b1110000000_110_000, DestinationOpcode::AD),
(0b1110000000_111_000, DestinationOpcode::AMD),
];
for (word, opcode) in tests.into_iter() {
assert_eq!(word, Word::from(opcode));
assert_eq!(DestinationOpcode::from(word), opcode);
}
}
#[test]
fn translate_jump_opcodes() {
let tests = vec![
(0b1110000000000_000, JumpOpcode::Null),
(0b1110000000000_001, JumpOpcode::JGT),
(0b1110000000000_010, JumpOpcode::JEQ),
(0b1110000000000_011, JumpOpcode::JGE),
(0b1110000000000_100, JumpOpcode::JLT),
(0b1110000000000_101, JumpOpcode::JNE),
(0b1110000000000_110, JumpOpcode::JLE),
(0b1110000000000_111, JumpOpcode::JMP),
];
for (word, opcode) in tests.into_iter() {
assert_eq!(word, Word::from(opcode));
assert_eq!(JumpOpcode::from(word), opcode);
}
}
#[test]
fn translate_compute_opcodes() {
let tests = vec![
(0b111_0101010_000000, ComputeOpcode::Zero),
(0b111_0111111_000000, ComputeOpcode::One),
(0b111_0111010_000000, ComputeOpcode::NegativeOne),
(0b111_0001100_000000, ComputeOpcode::D),
(0b111_0110000_000000, ComputeOpcode::A),
(0b111_1110000_000000, ComputeOpcode::M),
(0b111_0001101_000000, ComputeOpcode::NotD),
(0b111_0110001_000000, ComputeOpcode::NotA),
(0b111_1110001_000000, ComputeOpcode::NotM),
(0b111_0001111_000000, ComputeOpcode::NegativeD),
(0b111_0110011_000000, ComputeOpcode::NegativeA),
(0b111_1110011_000000, ComputeOpcode::NegativeM),
(0b111_0011111_000000, ComputeOpcode::DPlusOne),
(0b111_0110111_000000, ComputeOpcode::APlusOne),
(0b111_1110111_000000, ComputeOpcode::MPlusOne),
(0b111_0001110_000000, ComputeOpcode::DMinusOne),
(0b111_0110010_000000, ComputeOpcode::AMinusOne),
(0b111_1110010_000000, ComputeOpcode::MMinusOne),
(0b111_0000010_000000, ComputeOpcode::DPlusA),
(0b111_1000010_000000, ComputeOpcode::DPlusM),
(0b111_0010011_000000, ComputeOpcode::DMinusA),
(0b111_1010011_000000, ComputeOpcode::DMinusM),
(0b111_0000111_000000, ComputeOpcode::AMinusD),
(0b111_1000111_000000, ComputeOpcode::MMinusD),
(0b111_0000000_000000, ComputeOpcode::DAndA),
(0b111_1000000_000000, ComputeOpcode::DAndM),
(0b111_0010101_000000, ComputeOpcode::DOrA),
(0b111_1010101_000000, ComputeOpcode::DOrM),
];
for (word, opcode) in tests.into_iter() {
assert_eq!(word, Word::from(opcode));
assert_eq!(ComputeOpcode::from(word), opcode);
}
}
#[test]
#[should_panic]
fn translate_bad_compute_opcode_should_panic() {
ComputeOpcode::from(0b111_111000_000000);
}
}
|
use semver;
use url;
use url::Url;
use std::fmt;
use std::fmt::{Show,Formatter};
use serialize::{
Encodable,
Encoder,
Decodable,
Decoder
};
use util::{CargoError, FromError};
trait ToVersion {
fn to_version(self) -> Option<semver::Version>;
}
impl ToVersion for semver::Version {
fn to_version(self) -> Option<semver::Version> {
Some(self)
}
}
impl<'a> ToVersion for &'a str {
fn to_version(self) -> Option<semver::Version> {
semver::parse(self)
}
}
trait ToUrl {
fn to_url(self) -> Option<Url>;
}
impl<'a> ToUrl for &'a str {
fn to_url(self) -> Option<Url> {
url::from_str(self).ok()
}
}
impl ToUrl for Url {
fn to_url(self) -> Option<Url> {
Some(self)
}
}
impl<'a> ToUrl for &'a Url {
fn to_url(self) -> Option<Url> {
Some(self.clone())
}
}
#[deriving(Clone,PartialEq)]
pub struct PackageId {
name: String,
version: semver::Version,
namespace: Url
}
impl PackageId {
pub fn new<T: ToVersion, U: ToUrl>(name: &str, version: T,
namespace: U) -> PackageId {
PackageId {
name: name.to_str(),
version: version.to_version().unwrap(),
namespace: namespace.to_url().unwrap()
}
}
pub fn get_name<'a>(&'a self) -> &'a str {
self.name.as_slice()
}
pub fn get_version<'a>(&'a self) -> &'a semver::Version {
&self.version
}
pub fn get_namespace<'a>(&'a self) -> &'a Url {
&self.namespace
}
}
static central_repo: &'static str = "http://rust-lang.org/central-repo";
impl Show for PackageId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!(write!(f, "{} v{}", self.name, self.version));
if self.namespace.to_str().as_slice() != central_repo {
try!(write!(f, " ({})", self.namespace));
}
Ok(())
}
}
impl<E: CargoError + FromError<E>, D: Decoder<E>> Decodable<D,E> for PackageId {
fn decode(d: &mut D) -> Result<PackageId, E> {
let vector: Vec<String> = try!(Decodable::decode(d));
Ok(PackageId::new(
vector.get(0).as_slice(),
vector.get(1).as_slice(),
vector.get(2).as_slice()))
}
}
impl<E, S: Encoder<E>> Encodable<S,E> for PackageId {
fn encode(&self, e: &mut S) -> Result<(), E> {
(vec!(self.name.clone(), self.version.to_str()),
self.namespace.to_str()).encode(e)
}
}
|
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use crate::platform::traits::*;
use crate::units::{ElectricPotential, Energy, Power, Ratio, ThermodynamicTemperature};
use crate::{Error, Result, State, Technology};
use super::sysfs::{fs, DataBuilder, InstantData, Scope, Type};
pub struct SysFsDevice {
root: PathBuf,
source: InstantData,
// These fields are "cached" outside from DataBuilder/InstantData,
// since they're can't change with refresh
vendor: Option<String>,
model: Option<String>,
serial_number: Option<String>,
technology: Technology,
}
impl SysFsDevice {
pub fn is_system_battery<T: AsRef<Path>>(path: T) -> Result<bool> {
let path = path.as_ref();
if fs::type_(path.join("type"))? == Type::Battery && fs::scope(path.join("scope"))? == Scope::System {
return Ok(true);
}
Ok(false)
}
pub fn try_from(root: PathBuf) -> Result<SysFsDevice> {
let builder = DataBuilder::new(&root);
let vendor = builder.manufacturer()?;
let model = builder.model()?;
let serial_number = builder.serial_number()?;
let technology = builder.technology()?;
let source = builder.collect()?;
Ok(SysFsDevice {
root,
source,
vendor,
model,
serial_number,
technology,
})
}
pub fn refresh(&mut self) -> Result<()> {
// It is necessary to ensure that `self.root`
// still exists and accessible.
// See https://github.com/svartalf/rust-battery/issues/29
if self.root.is_dir() {
let builder = DataBuilder::new(&self.root);
self.source = builder.collect()?;
Ok(())
} else {
let inner = io::Error::from(io::ErrorKind::NotFound);
let e = Error::new(inner, format!("Device directory `{:?}` is missing", self.root));
Err(e)
}
}
}
impl BatteryDevice for SysFsDevice {
fn state_of_health(&self) -> Ratio {
self.source.state_of_health
}
fn state_of_charge(&self) -> Ratio {
self.source.state_of_charge
}
fn energy(&self) -> Energy {
self.source.energy
}
fn energy_full(&self) -> Energy {
self.source.energy_full
}
fn energy_full_design(&self) -> Energy {
self.source.energy_full_design
}
fn energy_rate(&self) -> Power {
self.source.energy_rate
}
fn state(&self) -> State {
self.source.state
}
fn voltage(&self) -> ElectricPotential {
self.source.voltage
}
fn temperature(&self) -> Option<ThermodynamicTemperature> {
self.source.temperature
}
fn vendor(&self) -> Option<&str> {
self.vendor.as_ref().map(AsRef::as_ref)
}
fn model(&self) -> Option<&str> {
self.model.as_ref().map(AsRef::as_ref)
}
fn serial_number(&self) -> Option<&str> {
self.serial_number.as_ref().map(AsRef::as_ref)
}
fn technology(&self) -> Technology {
self.technology
}
fn cycle_count(&self) -> Option<u32> {
self.source.cycle_count
}
}
impl fmt::Debug for SysFsDevice {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("LinuxDevice").field("root", &self.root).finish()
}
}
|
#[doc = "Reader of register FLTCR"]
pub type R = crate::R<u32, super::FLTCR>;
#[doc = "Writer for register FLTCR"]
pub type W = crate::W<u32, super::FLTCR>;
#[doc = "Register FLTCR `reset()`'s with value 0"]
impl crate::ResetValue for super::FLTCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TAMPFREQ`"]
pub type TAMPFREQ_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TAMPFREQ`"]
pub struct TAMPFREQ_W<'a> {
w: &'a mut W,
}
impl<'a> TAMPFREQ_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "Reader of field `TAMPFLT`"]
pub type TAMPFLT_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TAMPFLT`"]
pub struct TAMPFLT_W<'a> {
w: &'a mut W,
}
impl<'a> TAMPFLT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 3)) | (((value as u32) & 0x03) << 3);
self.w
}
}
#[doc = "Reader of field `TAMPPRCH`"]
pub type TAMPPRCH_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TAMPPRCH`"]
pub struct TAMPPRCH_W<'a> {
w: &'a mut W,
}
impl<'a> TAMPPRCH_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 5)) | (((value as u32) & 0x03) << 5);
self.w
}
}
#[doc = "Reader of field `TAMPPUDIS`"]
pub type TAMPPUDIS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TAMPPUDIS`"]
pub struct TAMPPUDIS_W<'a> {
w: &'a mut W,
}
impl<'a> TAMPPUDIS_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
}
}
impl R {
#[doc = "Bits 0:2 - TAMPFREQ"]
#[inline(always)]
pub fn tampfreq(&self) -> TAMPFREQ_R {
TAMPFREQ_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bits 3:4 - TAMPFLT"]
#[inline(always)]
pub fn tampflt(&self) -> TAMPFLT_R {
TAMPFLT_R::new(((self.bits >> 3) & 0x03) as u8)
}
#[doc = "Bits 5:6 - TAMPPRCH"]
#[inline(always)]
pub fn tampprch(&self) -> TAMPPRCH_R {
TAMPPRCH_R::new(((self.bits >> 5) & 0x03) as u8)
}
#[doc = "Bit 7 - TAMPPUDIS"]
#[inline(always)]
pub fn tamppudis(&self) -> TAMPPUDIS_R {
TAMPPUDIS_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - TAMPFREQ"]
#[inline(always)]
pub fn tampfreq(&mut self) -> TAMPFREQ_W {
TAMPFREQ_W { w: self }
}
#[doc = "Bits 3:4 - TAMPFLT"]
#[inline(always)]
pub fn tampflt(&mut self) -> TAMPFLT_W {
TAMPFLT_W { w: self }
}
#[doc = "Bits 5:6 - TAMPPRCH"]
#[inline(always)]
pub fn tampprch(&mut self) -> TAMPPRCH_W {
TAMPPRCH_W { w: self }
}
#[doc = "Bit 7 - TAMPPUDIS"]
#[inline(always)]
pub fn tamppudis(&mut self) -> TAMPPUDIS_W {
TAMPPUDIS_W { w: self }
}
}
|
/*
The following bug was in Rule v0.5.12.
This bug is fixed in v0.6 but is incompatible with past releases.
For easier reading we're using the Grammer API.
We add two new rules:
grammer.add("block", "(<stmt>( <stmt>)*)?", Some(Box::new(block)));
grammer.add("root", " <block> ", Some(Box::new(entry)));
The first rule is surrounded by a "maybe" which was causing invalid results. When given the scanner
an empty string the "root" rule was returning 0 branches which isn't correct because we have
given it a branch function. The problem was that the branch function wasn't handling the empty result
but it should have.
*/
use rule::Rule;
#[test]
fn bug_0_5_12_test_empty_string() {
let block_fn = |b: Vec<u32>, _: &str| {
assert_eq!(b.len(), 0);
Ok(1)
};
let root_fn = |b: Vec<u32>, _: &str| {
assert_eq!(b.len(), 1);
Ok(b[0])
};
let stmt_fn = |b: Vec<u32>, _: &str| {
assert_eq!(b.len(), 0);
Ok(7)
};
let ws = Rule::default();
ws.literal(" ");
let none_or_many_ws = Rule::default();
none_or_many_ws.none_or_many(&ws);
let stmt = Rule::new(stmt_fn);
stmt.literal("stmt");
let ws_plus_stmt = Rule::default();
ws_plus_stmt.one(&none_or_many_ws).one(&stmt);
let stmts = Rule::default();
stmts.one(&stmt).none_or_many(&ws_plus_stmt);
let block = Rule::new(block_fn);
block.maybe(&stmts);
let root = Rule::new(root_fn);
root.one(&none_or_many_ws).one(&block).one(&none_or_many_ws);
let code = "";
if let Ok(branches) = root.scan(code) {
assert!(branches.len() == 1);
}
else {
assert!(false);
}
}
#[test]
fn bug_0_5_12_test_with_content() {
let block_fn = |b: Vec<u32>, _: &str| {
assert_eq!(b.len(), 3);
Ok(1)
};
let root_fn = |b: Vec<u32>, _: &str| {
assert_eq!(b.len(), 1);
Ok(b[0])
};
let stmt_fn = |b: Vec<u32>, _: &str| {
assert_eq!(b.len(), 0);
Ok(7)
};
let ws = Rule::default();
ws.literal(" ");
let none_or_many_ws = Rule::default();
none_or_many_ws.none_or_many(&ws);
let stmt = Rule::new(stmt_fn);
stmt.literal("stmt");
let ws_plus_stmt = Rule::default();
ws_plus_stmt.one(&none_or_many_ws).one(&stmt);
let stmts = Rule::default();
stmts.one(&stmt).none_or_many(&ws_plus_stmt);
let block = Rule::new(block_fn);
block.maybe(&stmts);
let root = Rule::new(root_fn);
root.one(&none_or_many_ws).one(&block).one(&none_or_many_ws);
let code = " stmt stmt stmt ";
if let Ok(branches) = root.scan(code) {
assert!(branches.len() == 1);
}
else {
assert!(false);
}
} |
use aws_lambda_events::{
encodings::Body,
event::apigw::{
ApiGatewayProxyRequest, ApiGatewayProxyResponse,
},
};
use http::HeaderMap;
use lambda_runtime::{handler_fn, Context, Error};
#[tokio::main]
async fn main() -> Result<(), Error> {
dbg!("cold start");
let handler_fn = handler_fn(handler);
lambda_runtime::run(handler_fn).await?;
Ok(())
}
async fn handler(
event: ApiGatewayProxyRequest,
_: Context,
) -> Result<ApiGatewayProxyResponse, Error> {
dbg!("in main", &event);
let world = "world".to_string();
let first_name = event
.query_string_parameters
.get("firstName")
.unwrap_or(&world);
dbg!(&first_name);
Ok(ApiGatewayProxyResponse {
status_code: 200,
headers: HeaderMap::new(),
multi_value_headers: HeaderMap::new(),
body: Some(Body::Text(format!(
"Hello, {}!",
first_name
))),
is_base64_encoded: Some(false),
})
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Win32_Storage_Packaging_Appx")]
pub mod Appx;
#[cfg(feature = "Win32_Storage_Packaging_Opc")]
pub mod Opc;
|
#![feature(c_variadic)]
#![feature(sgx_platform)]
pub mod file;
pub mod thread;
pub mod mutex;
pub mod other;
|
#[cfg(feature = "libm")]
#[allow(unused_imports)]
use num_traits::Float;
pub(crate) trait FloatEx {
/// Returns a very close approximation of `self.clamp(-1.0, 1.0).acos()`.
fn acos_approx(self) -> Self;
}
impl FloatEx for f32 {
#[inline(always)]
fn acos_approx(self) -> Self {
// Based on https://github.com/microsoft/DirectXMath `XMScalarAcos`
// Clamp input to [-1,1].
let nonnegative = self >= 0.0;
let x = self.abs();
let mut omx = 1.0 - x;
if omx < 0.0 {
omx = 0.0;
}
let root = omx.sqrt();
// 7-degree minimax approximation
#[allow(clippy::approx_constant)]
let mut result = ((((((-0.001_262_491_1 * x + 0.006_670_09) * x - 0.017_088_126) * x
+ 0.030_891_88)
* x
- 0.050_174_303)
* x
+ 0.088_978_99)
* x
- 0.214_598_8)
* x
+ 1.570_796_3;
result *= root;
// acos(x) = pi - acos(-x) when x < 0
if nonnegative {
result
} else {
core::f32::consts::PI - result
}
}
}
impl FloatEx for f64 {
#[inline(always)]
fn acos_approx(self) -> Self {
f64::acos(self.max(-1.0).min(1.0))
}
}
|
// 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.
macro_rules! iterator_next_label
{
($self: ident) =>
{
{
let pointer_to_label = $self.pointer_to_label;
let label = Label::label(pointer_to_label);
if unlikely!(label.is_root())
{
return None
}
(label, pointer_to_label)
}
}
}
|
// pathfinder/path-utils/src/cubic.rs
//
// Copyright © 2017 The Pathfinder Project Developers.
//
// 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.
//! Utilities for cubic Bézier curves.
use euclid::Point2D;
use curve::Curve;
use PathCommand;
const MAX_APPROXIMATION_ITERATIONS: u8 = 32;
/// A cubic Bézier curve.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct CubicCurve {
/// The endpoints of the curve.
pub endpoints: [Point2D<f32>; 2],
/// The control points of the curve.
pub control_points: [Point2D<f32>; 2],
}
impl CubicCurve {
/// Constructs a new cubic Bézier curve from the given points.
#[inline]
pub fn new(endpoint_0: &Point2D<f32>,
control_point_0: &Point2D<f32>,
control_point_1: &Point2D<f32>,
endpoint_1: &Point2D<f32>)
-> CubicCurve {
CubicCurve {
endpoints: [*endpoint_0, *endpoint_1],
control_points: [*control_point_0, *control_point_1],
}
}
/// Returns the curve point at the given t value (from 0.0 to 1.0).
pub fn sample(&self, t: f32) -> Point2D<f32> {
let (p0, p3) = (&self.endpoints[0], &self.endpoints[1]);
let (p1, p2) = (&self.control_points[0], &self.control_points[1]);
let (p0p1, p1p2, p2p3) = (p0.lerp(*p1, t), p1.lerp(*p2, t), p2.lerp(*p3, t));
let (p0p1p2, p1p2p3) = (p0p1.lerp(p1p2, t), p1p2.lerp(p2p3, t));
p0p1p2.lerp(p1p2p3, t)
}
/// De Casteljau subdivides this curve into two at the given t value (from 0.0 to 1.0).
pub fn subdivide(&self, t: f32) -> (CubicCurve, CubicCurve) {
let (p0, p3) = (&self.endpoints[0], &self.endpoints[1]);
let (p1, p2) = (&self.control_points[0], &self.control_points[1]);
let (p0p1, p1p2, p2p3) = (p0.lerp(*p1, t), p1.lerp(*p2, t), p2.lerp(*p3, t));
let (p0p1p2, p1p2p3) = (p0p1.lerp(p1p2, t), p1p2.lerp(p2p3, t));
let p0p1p2p3 = p0p1p2.lerp(p1p2p3, t);
(CubicCurve::new(&p0, &p0p1, &p0p1p2, &p0p1p2p3),
CubicCurve::new(&p0p1p2p3, &p1p2p3, &p2p3, &p3))
}
/// Approximates this curve with a series of quadratic Bézier curves.
///
/// The quadratic curves are guaranteed not to deviate from this cubic curve by more than
/// `error_bound`.
pub fn approx_curve(&self, error_bound: f32) -> ApproxCurveIter {
ApproxCurveIter::new(self, error_bound)
}
}
/// A series of path commands that can contain cubic Bézier segments.
#[derive(Clone, Copy, Debug)]
pub enum CubicPathCommand {
/// Moves the pen to the given point.
MoveTo(Point2D<f32>),
/// Draws a line to the given point.
LineTo(Point2D<f32>),
/// Draws a quadratic curve with the control point to the endpoint, respectively.
QuadCurveTo(Point2D<f32>, Point2D<f32>),
/// Draws a cubic cubic curve with the two control points to the endpoint, respectively.
CubicCurveTo(Point2D<f32>, Point2D<f32>, Point2D<f32>),
/// Closes the current subpath by drawing a line from the current point to the first point of
/// the subpath.
ClosePath,
}
/// Converts a series of path commands that can contain cubic Bézier segments to a series of path
/// commands that contain only quadratic Bézier segments.
pub struct CubicPathCommandApproxStream<I> {
inner: I,
error_bound: f32,
last_endpoint: Point2D<f32>,
approx_curve_iter: Option<ApproxCurveIter>,
}
impl<I> CubicPathCommandApproxStream<I> where I: Iterator<Item = CubicPathCommand> {
/// Creates a stream that approximates the given path commands by converting all cubic Bézier
/// curves to quadratic Bézier curves.
///
/// The resulting path command stream is guaranteed not to deviate more than a distance of
/// `error_bound` from the original path command stream.
#[inline]
pub fn new(inner: I, error_bound: f32) -> CubicPathCommandApproxStream<I> {
CubicPathCommandApproxStream {
inner: inner,
error_bound: error_bound,
last_endpoint: Point2D::zero(),
approx_curve_iter: None,
}
}
}
impl<I> Iterator for CubicPathCommandApproxStream<I> where I: Iterator<Item = CubicPathCommand> {
type Item = PathCommand;
fn next(&mut self) -> Option<PathCommand> {
loop {
if let Some(ref mut approx_curve_iter) = self.approx_curve_iter {
if let Some(curve) = approx_curve_iter.next() {
return Some(curve.to_path_command())
}
}
self.approx_curve_iter = None;
let next_command = match self.inner.next() {
None => return None,
Some(next_command) => next_command,
};
match next_command {
CubicPathCommand::ClosePath => {
self.last_endpoint = Point2D::zero();
return Some(PathCommand::ClosePath)
}
CubicPathCommand::MoveTo(endpoint) => {
self.last_endpoint = endpoint;
return Some(PathCommand::MoveTo(endpoint))
}
CubicPathCommand::LineTo(endpoint) => {
self.last_endpoint = endpoint;
return Some(PathCommand::LineTo(endpoint))
}
CubicPathCommand::QuadCurveTo(control_point, endpoint) => {
self.last_endpoint = endpoint;
return Some(PathCommand::CurveTo(control_point, endpoint))
}
CubicPathCommand::CubicCurveTo(control_point_0, control_point_1, endpoint) => {
let curve = CubicCurve::new(&self.last_endpoint,
&control_point_0,
&control_point_1,
&endpoint);
self.last_endpoint = endpoint;
self.approx_curve_iter = Some(ApproxCurveIter::new(&curve, self.error_bound));
}
}
}
}
}
/// Approximates a single cubic Bézier curve with a series of quadratic Bézier curves.
pub struct ApproxCurveIter {
curves: Vec<CubicCurve>,
error_bound: f32,
iteration: u8,
}
impl ApproxCurveIter {
fn new(cubic: &CubicCurve, error_bound: f32) -> ApproxCurveIter {
let (curve_a, curve_b) = cubic.subdivide(0.5);
ApproxCurveIter {
curves: vec![curve_b, curve_a],
error_bound: error_bound,
iteration: 0,
}
}
}
impl Iterator for ApproxCurveIter {
type Item = Curve;
fn next(&mut self) -> Option<Curve> {
let mut cubic = match self.curves.pop() {
Some(cubic) => cubic,
None => return None,
};
while self.iteration < MAX_APPROXIMATION_ITERATIONS {
self.iteration += 1;
// See Sederberg § 2.6, "Distance Between Two Bézier Curves".
let delta_control_point_0 = (cubic.endpoints[0] - cubic.control_points[0] * 3.0) +
(cubic.control_points[1] * 3.0 - cubic.endpoints[1]);
let delta_control_point_1 = (cubic.control_points[0] * 3.0 - cubic.endpoints[0]) +
(cubic.endpoints[1] - cubic.control_points[1] * 3.0);
let max_error = f32::max(delta_control_point_1.length(),
delta_control_point_0.length()) / 6.0;
if max_error < self.error_bound {
break
}
let (cubic_a, cubic_b) = cubic.subdivide(0.5);
self.curves.push(cubic_b);
cubic = cubic_a
}
let approx_control_point_0 = (cubic.control_points[0] * 3.0 - cubic.endpoints[0]) * 0.5;
let approx_control_point_1 = (cubic.control_points[1] * 3.0 - cubic.endpoints[1]) * 0.5;
Some(Curve::new(&cubic.endpoints[0],
&approx_control_point_0.lerp(approx_control_point_1, 0.5).to_point(),
&cubic.endpoints[1]))
}
}
|
//! File system with block support
//!
//! Create a filesystem that only has a notion of blocks, by implementing the [`FileSysSupport`] and
//! the [`BlockSupport`] traits together (you have no other choice, as the first one is a supertrait of the second).
//!
//! [`FileSysSupport`]: ../../cplfs_api/fs/trait.FileSysSupport.html
//! [`BlockSupport`]: ../../cplfs_api/fs/trait.BlockSupport.html
//! Make sure this file does not contain any unaddressed
//!
//! # Status
//!
//! indicate the status of this assignment. If you want to tell something
//! about this assignment to the grader, e.g., you have a bug you can't fix,
//! or you want to explain your approach, write it down after the comments
//! section. If you had no major issues and everything works, there is no need to write any comments.
//!
//! COMPLETED: YES
//!
//! COMMENTS: I realized to late that i could have used the sup_get function when wanting to use the superblock,
//! Instead i kept the parameter superblock in the structure
//!
//! ...
//!
// Turn off the warnings we get from the below example imports, which are currently unused.
// If you want to import things from the API crate, do so as follows:
use cplfs_api::controller::Device;
use cplfs_api::fs::{BlockSupport, FileSysSupport};
use cplfs_api::types::{Block, SuperBlock};
use std::path::Path;
use crate::filesystem_errors::FileSystemError;
use crate::helpers::*;
/// You are free to choose the name for your file system. As we will use
/// automated tests when grading your assignment, indicate here the name of
/// your file system data type so we can just use `FSName` instead of
/// having to manually figure out your file system name.
pub type FSName = FileSystem;
#[derive(Debug)]
/// This is the filesystem structure that wa are going to use in the whole project
pub struct FileSystem {
/// We keep a reference to the superblock cause it can come in hand
pub superblock: SuperBlock,
/// This is the device we work on, it is optional at the start and can be filled in later
pub device: Option<Device>,
}
impl FileSystem {
/// This function creates a filesystem struct given a superblock and a optional device
pub fn create_filesystem(superblock: SuperBlock, device: Option<Device>) -> FileSystem {
FileSystem { superblock, device }
}
}
impl FileSysSupport for FileSystem {
type Error = FileSystemError;
fn sb_valid(sb: &SuperBlock) -> bool {
return sb_valid(sb);
}
fn mkfs<P: AsRef<Path>>(path: P, sb: &SuperBlock) -> Result<Self, Self::Error> {
if !FSName::sb_valid(sb) {
Err(FileSystemError::InvalidSuperBlock())
} else {
let device_result = Device::new(path, sb.block_size, sb.nblocks);
match device_result {
Ok(mut device) => {
//place superblock at index 0
write_sb(sb, &mut device)?;
allocate_inoderegionblocks(&sb, &mut device)?;
allocate_bitmapregion(&sb, &mut device)?;
allocate_dataregion(&sb, &mut device)?;
let fs = FileSystem::mountfs(device)?;
//allocate_inodes(&mut fs);
Ok(fs)
}
Err(e) => Err(FileSystemError::DeviceAPIError(e)),
}
}
}
fn mountfs(dev: Device) -> Result<Self, Self::Error> {
match dev.read_block(0) {
Ok(block) => {
let sb = &block.deserialize_from::<SuperBlock>(0)?;
if FSName::sb_valid(sb)
&& dev.block_size == sb.block_size
&& dev.nblocks == sb.nblocks
{
let fs = FileSystem::create_filesystem(*sb, Some(dev));
Ok(fs)
} else {
Err(FileSystemError::InvalidSuperBlock())
}
}
Err(e) => Err(FileSystemError::DeviceAPIError(e)),
}
}
fn unmountfs(mut self) -> Device {
let deviceoption = self.device.take();
let device = deviceoption.unwrap();
return device;
}
}
impl BlockSupport for FileSystem {
fn b_get(&self, i: u64) -> Result<Block, Self::Error> {
let dev = self
.device
.as_ref()
.ok_or_else(|| FileSystemError::DeviceNotSet())?;
return Ok(read_block(dev, i)?);
}
fn b_put(&mut self, b: &Block) -> Result<(), Self::Error> {
let dev = self
.device
.as_mut()
.ok_or_else(|| FileSystemError::DeviceNotSet())?;
return Ok(write_block(dev, b)?);
}
fn b_free(&mut self, i: u64) -> Result<(), Self::Error> {
let dev = self
.device
.as_mut()
.ok_or_else(|| FileSystemError::DeviceNotSet())?;
set_bitmapbit(&self.superblock, dev, i, false)?;
Ok(())
}
fn b_zero(&mut self, i: u64) -> Result<(), Self::Error> {
let datablock_index = i + self.superblock.datastart;
let newzeroblock = Block::new(
datablock_index,
vec![0; self.superblock.block_size as usize].into_boxed_slice(),
);
self.b_put(&newzeroblock)?;
Ok(())
}
fn b_alloc(&mut self) -> Result<u64, Self::Error> {
let nbitmapblocks = get_nbitmapblocks(&self.superblock);
let mut bmstart_index = self.superblock.bmapstart; // get the index
let mut block; // get the first block
let mut byte_array; // create an empty data buffer
let mut byteindex; //block index
for blockindex in 0..nbitmapblocks {
block = self.b_get(bmstart_index + blockindex)?; //next block
//byte_array = block.contents_as_ref(); //get the block's array
byte_array = block.contents_as_ref();
byteindex = get_bytesarray_free_index(byte_array);
if byteindex.is_err() {
// HERE WE ARE LOOKING FOR THE NEXT BLOCK
bmstart_index += 1; //next block index
} else {
// The current bm_block has a free spot
let byteindex = byteindex.unwrap(); //get the index of the byte that has a free spot
let byte = byte_array.get(usize::from(byteindex)).unwrap();
let bitindex = 8 - 1 - byte.trailing_ones(); //moves the 1 to the correct position
let mutator = 0b00000001u8 << byte.trailing_ones(); //moves the 1 to the correct position
let to_write_byte = &[(*byte | mutator)];
block.write_data(to_write_byte, byteindex as u64)?;
let byteindex: u64 = u64::from(byteindex);
let datablockindex = blockindex * self.superblock.block_size * 8
+ (byteindex) * 8
+ u64::from(7 - bitindex);
if datablockindex < self.superblock.ndatablocks {
self.b_zero(datablockindex)?;
self.b_put(&block)?;
return Ok(datablockindex);
}
}
}
Err(FileSystemError::AllocationError())
}
fn sup_get(&self) -> Result<SuperBlock, Self::Error> {
let block = self.b_get(0)?;
let sb = block.deserialize_from::<SuperBlock>(0)?;
Ok(sb)
}
fn sup_put(&mut self, sup: &SuperBlock) -> Result<(), Self::Error> {
let mut firstblock = self.b_get(0)?;
firstblock.serialize_into(&sup, 0)?;
self.b_put(&firstblock)?;
Ok(())
}
}
// Here we define a submodule, called `my_tests`, that will contain your unit
// tests for this module.
// You can define more tests in different modules, and change the name of this module
//
// The `test` in the `#[cfg(test)]` annotation ensures that this code is only compiled when we're testing the code.
// To run these tests, run the command `cargo test` in the `solution` directory
//
// To learn more about testing, check the Testing chapter of the Rust
// Book: https://doc.rust-lang.org/book/testing.html
#[cfg(test)]
mod superblock_tests {
use super::FSName;
use cplfs_api::fs::FileSysSupport;
use cplfs_api::types::SuperBlock;
//#[path = "utils.rs"]
#[test]
fn trivial_unit_test() {
assert_eq!(FSName::sb_valid(&SUPERBLOCK_OVERSIZED), false);
assert_eq!(FSName::sb_valid(&SUPERBLOCK_GOOD), true);
assert_eq!(FSName::sb_valid(&SUPERBLOCK_BAD_1), true);
assert_eq!(FSName::sb_valid(&SUPERBLOCK_BAD_2), true);
assert_eq!(FSName::sb_valid(&SUPERBLOCK_BAD_3), true);
}
static BLOCK_SIZE: u64 = 1000;
static NBLOCKS: u64 = 10;
static SUPERBLOCK_OVERSIZED: SuperBlock = SuperBlock {
block_size: BLOCK_SIZE,
nblocks: NBLOCKS,
ninodes: 1000,
inodestart: 1,
ndatablocks: 5,
bmapstart: 5,
datastart: 6,
};
static SUPERBLOCK_GOOD: SuperBlock = SuperBlock {
block_size: BLOCK_SIZE,
nblocks: NBLOCKS,
ninodes: 6,
inodestart: 1,
ndatablocks: 4,
bmapstart: 5,
datastart: 6,
};
static SUPERBLOCK_BAD_1: SuperBlock = SuperBlock {
block_size: BLOCK_SIZE,
nblocks: NBLOCKS,
ninodes: 6,
inodestart: 1,
ndatablocks: 2,
bmapstart: 5,
datastart: 6,
};
static SUPERBLOCK_BAD_2: SuperBlock = SuperBlock {
block_size: BLOCK_SIZE,
nblocks: NBLOCKS,
ninodes: 1,
inodestart: 1,
ndatablocks: 5,
bmapstart: 5,
datastart: 6,
};
static SUPERBLOCK_BAD_3: SuperBlock = SuperBlock {
block_size: BLOCK_SIZE,
nblocks: NBLOCKS,
ninodes: 1,
inodestart: 1,
ndatablocks: 5,
bmapstart: 4,
datastart: 5,
};
}
// If you want to write more complicated tests that create actual files on your system, take a look at `utils.rs` in the assignment, and how it is used in the `fs_tests` folder to perform the tests. I have imported it below to show you how it can be used.
// The `utils` folder has a few other useful methods too (nothing too crazy though, you might want to write your own utility functions, or use a testing framework in rust, if you want more advanced features)
#[cfg(test)]
#[path = "../../api/fs-tests"]
mod test_with_utils {
use crate::a_block_support::FSName;
use cplfs_api::fs::{BlockSupport, FileSysSupport};
use cplfs_api::types::SuperBlock;
use std::path::PathBuf;
#[path = "utils.rs"]
mod utils;
static BLOCK_SIZE: u64 = 1000;
static NBLOCKS: u64 = 10;
static SUPERBLOCK_GOOD: SuperBlock = SuperBlock {
block_size: BLOCK_SIZE,
nblocks: NBLOCKS,
ninodes: 6,
inodestart: 1,
ndatablocks: 4,
bmapstart: 5,
datastart: 6,
};
fn disk_prep_path(name: &str) -> PathBuf {
utils::disk_prep_path(&("fs-images-a-".to_string() + name), "img")
}
#[test]
fn complex_test() {
let path = disk_prep_path("test");
let mut my_fs = FSName::mkfs(&path, &SUPERBLOCK_GOOD).unwrap();
let zb = |i| utils::zero_block(i, BLOCK_SIZE);
for i in 1..NBLOCKS {
//Will fail if you sneak in inodesupport
assert_eq!(my_fs.b_get(i).unwrap(), zb(i));
}
let nb = utils::n_block(5, BLOCK_SIZE, 6);
my_fs.b_put(&nb).unwrap();
let b = my_fs.b_get(5).unwrap();
assert_eq!(b, nb);
let nb_bis = utils::n_block(6, BLOCK_SIZE, 6);
my_fs.b_put(&nb_bis).unwrap();
my_fs.b_zero(1).unwrap(); //zero this block again
let b = my_fs.b_get(6).unwrap();
let dev = my_fs.unmountfs();
utils::disk_destruct(dev);
}
}
// Here we define a submodule, called `tests`, that will contain our unit tests
// Take a look at the specified path to figure out which tests your code has to pass.
// As with all other files in the assignment, the testing module for this file is stored in the API crate (this is the reason for the 'path' attribute in the code below)
// The reason I set it up like this is that it allows me to easily add additional tests when grading your projects, without changing any of your files, but you can still run my tests together with yours by specifying the right features (see below) :)
// directory.
//
// To run these tests, run the command `cargo test --features="X"` in the `solution` directory, with "X" a space-separated string of the features you are interested in testing.
//
// WARNING: DO NOT TOUCH THE BELOW CODE -- IT IS REQUIRED FOR TESTING -- YOU WILL LOSE POINTS IF I MANUALLY HAVE TO FIX YOUR TESTS
//The below configuration tag specifies the following things:
// 'cfg' ensures this module is only included in the source if all conditions are met
// 'all' is true iff ALL conditions in the tuple hold
// 'test' is only true when running 'cargo test', not 'cargo build'
// 'any' is true iff SOME condition in the tuple holds
// 'feature = X' ensures that the code is only compiled when the cargo command includes the flag '--features "<some-features>"' and some features includes X.
// I declared the necessary features in Cargo.toml
// (Hint: this hacking using features is not idiomatic behavior, but it allows you to run your own tests without getting errors on mine, for parts that have not been implemented yet)
// The reason for this setup is that you can opt-in to tests, rather than getting errors at compilation time if you have not implemented something.
// The "a" feature will run these tests specifically, and the "all" feature will run all tests.
#[cfg(all(test, any(feature = "a", feature = "all")))]
#[path = "../../api/fs-tests/a_test.rs"]
mod tests;
|
use core::marker;
use {Async, Poll};
use stream::Stream;
/// A stream which is just a shim over an underlying instance of `Iterator`.
///
/// This stream will never block and is always ready.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct IterOk<I, E> {
iter: I,
_marker: marker::PhantomData<fn() -> E>,
}
/// Converts an `Iterator` into a `Stream` which is always ready
/// to yield the next value.
///
/// Iterators in Rust don't express the ability to block, so this adapter
/// simply always calls `iter.next()` and returns that.
///
/// ```rust
/// use futures::*;
///
/// let mut stream = stream::iter_ok::<_, ()>(vec![17, 19]);
/// assert_eq!(Ok(Async::Ready(Some(17))), stream.poll());
/// assert_eq!(Ok(Async::Ready(Some(19))), stream.poll());
/// assert_eq!(Ok(Async::Ready(None)), stream.poll());
/// ```
pub fn iter_ok<I, E>(i: I) -> IterOk<I::IntoIter, E>
where I: IntoIterator,
{
IterOk {
iter: i.into_iter(),
_marker: marker::PhantomData,
}
}
impl<I, E> Stream for IterOk<I, E>
where I: Iterator,
{
type Item = I::Item;
type Error = E;
fn poll(&mut self) -> Poll<Option<I::Item>, E> {
Ok(Async::Ready(self.iter.next()))
}
}
|
#[doc = "Reader of register FIFOCTL"]
pub type R = crate::R<u32, super::FIFOCTL>;
#[doc = "Writer for register FIFOCTL"]
pub type W = crate::W<u32, super::FIFOCTL>;
#[doc = "Register FIFOCTL `reset()`'s with value 0"]
impl crate::ResetValue for super::FIFOCTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TXTRIG`"]
pub type TXTRIG_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TXTRIG`"]
pub struct TXTRIG_W<'a> {
w: &'a mut W,
}
impl<'a> TXTRIG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "Reader of field `DMATXENA`"]
pub type DMATXENA_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMATXENA`"]
pub struct DMATXENA_W<'a> {
w: &'a mut W,
}
impl<'a> DMATXENA_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `TXFLUSH`"]
pub type TXFLUSH_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TXFLUSH`"]
pub struct TXFLUSH_W<'a> {
w: &'a mut W,
}
impl<'a> TXFLUSH_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `TXASGNMT`"]
pub type TXASGNMT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TXASGNMT`"]
pub struct TXASGNMT_W<'a> {
w: &'a mut W,
}
impl<'a> TXASGNMT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `RXTRIG`"]
pub type RXTRIG_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RXTRIG`"]
pub struct RXTRIG_W<'a> {
w: &'a mut W,
}
impl<'a> RXTRIG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 16)) | (((value as u32) & 0x07) << 16);
self.w
}
}
#[doc = "Reader of field `DMARXENA`"]
pub type DMARXENA_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMARXENA`"]
pub struct DMARXENA_W<'a> {
w: &'a mut W,
}
impl<'a> DMARXENA_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 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Reader of field `RXFLUSH`"]
pub type RXFLUSH_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RXFLUSH`"]
pub struct RXFLUSH_W<'a> {
w: &'a mut W,
}
impl<'a> RXFLUSH_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Reader of field `RXASGNMT`"]
pub type RXASGNMT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RXASGNMT`"]
pub struct RXASGNMT_W<'a> {
w: &'a mut W,
}
impl<'a> RXASGNMT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:2 - TX FIFO Trigger"]
#[inline(always)]
pub fn txtrig(&self) -> TXTRIG_R {
TXTRIG_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bit 13 - DMA TX Channel Enable"]
#[inline(always)]
pub fn dmatxena(&self) -> DMATXENA_R {
DMATXENA_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - TX FIFO Flush"]
#[inline(always)]
pub fn txflush(&self) -> TXFLUSH_R {
TXFLUSH_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - TX Control Assignment"]
#[inline(always)]
pub fn txasgnmt(&self) -> TXASGNMT_R {
TXASGNMT_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bits 16:18 - RX FIFO Trigger"]
#[inline(always)]
pub fn rxtrig(&self) -> RXTRIG_R {
RXTRIG_R::new(((self.bits >> 16) & 0x07) as u8)
}
#[doc = "Bit 29 - DMA RX Channel Enable"]
#[inline(always)]
pub fn dmarxena(&self) -> DMARXENA_R {
DMARXENA_R::new(((self.bits >> 29) & 0x01) != 0)
}
#[doc = "Bit 30 - RX FIFO Flush"]
#[inline(always)]
pub fn rxflush(&self) -> RXFLUSH_R {
RXFLUSH_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - RX Control Assignment"]
#[inline(always)]
pub fn rxasgnmt(&self) -> RXASGNMT_R {
RXASGNMT_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - TX FIFO Trigger"]
#[inline(always)]
pub fn txtrig(&mut self) -> TXTRIG_W {
TXTRIG_W { w: self }
}
#[doc = "Bit 13 - DMA TX Channel Enable"]
#[inline(always)]
pub fn dmatxena(&mut self) -> DMATXENA_W {
DMATXENA_W { w: self }
}
#[doc = "Bit 14 - TX FIFO Flush"]
#[inline(always)]
pub fn txflush(&mut self) -> TXFLUSH_W {
TXFLUSH_W { w: self }
}
#[doc = "Bit 15 - TX Control Assignment"]
#[inline(always)]
pub fn txasgnmt(&mut self) -> TXASGNMT_W {
TXASGNMT_W { w: self }
}
#[doc = "Bits 16:18 - RX FIFO Trigger"]
#[inline(always)]
pub fn rxtrig(&mut self) -> RXTRIG_W {
RXTRIG_W { w: self }
}
#[doc = "Bit 29 - DMA RX Channel Enable"]
#[inline(always)]
pub fn dmarxena(&mut self) -> DMARXENA_W {
DMARXENA_W { w: self }
}
#[doc = "Bit 30 - RX FIFO Flush"]
#[inline(always)]
pub fn rxflush(&mut self) -> RXFLUSH_W {
RXFLUSH_W { w: self }
}
#[doc = "Bit 31 - RX Control Assignment"]
#[inline(always)]
pub fn rxasgnmt(&mut self) -> RXASGNMT_W {
RXASGNMT_W { w: self }
}
}
|
use std::str;
fn main() {
let x: &[u8] = &[b'c', b'l', b'i', b'f', b'f'];
let stack_str: &str = str::from_utf8(x).unwrap();
println!("{}", stack_str);
}
|
use openxr::{
vulkan::SessionCreateInfo, ApplicationInfo, EnvironmentBlendMode, ExtensionSet, FormFactor,
FrameStream, FrameWaiter, Instance as OpenXRInstance, Session, SystemId, SystemProperties,
ViewConfigurationProperties, ViewConfigurationType, ViewConfigurationView, Vulkan,
};
use utilities::prelude::*;
use vulkan_rs::prelude::*;
use crate::p_try;
use std::mem;
use std::sync::Arc;
pub struct OpenXRIntegration {
instance: Arc<OpenXRInstance>,
system_id: SystemId,
}
impl OpenXRIntegration {
pub fn new<'a>(app_info: ApplicationInfo<'a>) -> VerboseResult<OpenXRIntegration> {
let entry = openxr::Entry::linked();
let supported_extensions = p_try!(entry.enumerate_extensions());
println!("supported extensions: {:#?}", supported_extensions);
let mut extensions = ExtensionSet::default();
if !supported_extensions.khr_vulkan_enable {
create_error!("vulkan not available for OpenXR implementation");
}
extensions.khr_vulkan_enable = true;
if supported_extensions.ext_debug_utils {
// extensions.ext_debug_utils = true;
}
let instance = p_try!(entry.create_instance(&app_info, &extensions));
let system_id = p_try!(instance.system(FormFactor::HEAD_MOUNTED_DISPLAY));
Ok(OpenXRIntegration {
instance: Arc::new(instance),
system_id,
})
}
pub fn activate_vulkan_instance_extensions(
&self,
extensions: &mut InstanceExtensions,
) -> VerboseResult<()> {
let extension_names: Vec<String> =
p_try!(self.instance.vulkan_instance_extensions(self.system_id))
.split(" ")
.map(|extension_name| extension_name.to_string())
.collect();
for extension_name in extension_names {
if let Err(err) = extensions.activate(&extension_name) {
println!("{}", err);
unsafe {
extensions.add_raw_name(&extension_name);
}
}
}
Ok(())
}
pub fn activate_vulkan_device_extensions(
&self,
extensions: &mut DeviceExtensions,
) -> VerboseResult<()> {
let extension_names: Vec<String> =
p_try!(self.instance.vulkan_device_extensions(self.system_id))
.split(" ")
.map(|s| s.to_string())
.collect();
for extension_name in extension_names {
if let Err(err) = extensions.activate(&extension_name) {
println!("{}", err);
unsafe {
extensions.add_raw_name(&extension_name);
}
}
}
Ok(())
}
pub fn physical_device(&self, instance: &Arc<Instance>) -> VerboseResult<VkPhysicalDevice> {
unsafe {
let phys_dev = p_try!(self
.instance
.vulkan_graphics_device(self.system_id, mem::transmute(instance.vk_handle())));
Ok(mem::transmute(phys_dev))
}
}
pub(crate) fn instance(&self) -> &Arc<OpenXRInstance> {
&self.instance
}
pub(crate) fn create_session(
&self,
device: &Arc<Device>,
queue_family_index: u32,
queue_index: u32,
) -> VerboseResult<(Session<Vulkan>, FrameWaiter, FrameStream<Vulkan>)> {
let session_ci = unsafe {
SessionCreateInfo {
instance: mem::transmute(device.physical_device().instance().vk_handle()),
device: mem::transmute(device.vk_handle()),
physical_device: mem::transmute(device.physical_device().vk_handle()),
queue_family_index,
queue_index,
}
};
Ok(p_try!(unsafe {
self.instance
.create_session::<Vulkan>(self.system_id, &session_ci)
}))
}
pub(crate) fn view_configs(&self) -> VerboseResult<Vec<ViewConfigurationType>> {
Ok(p_try!(self
.instance
.enumerate_view_configurations(self.system_id)))
}
pub(crate) fn view_config_properties(
&self,
view_config_type: ViewConfigurationType,
) -> VerboseResult<ViewConfigurationProperties> {
Ok(p_try!(self.instance.view_configuration_properties(
self.system_id,
view_config_type
)))
}
pub(crate) fn view_config_views(
&self,
view_config_type: ViewConfigurationType,
) -> VerboseResult<Vec<ViewConfigurationView>> {
Ok(p_try!(self.instance.enumerate_view_configuration_views(
self.system_id,
view_config_type
)))
}
pub(crate) fn enumerate_environment_blend_modes(
&self,
view_config_type: ViewConfigurationType,
) -> VerboseResult<Vec<EnvironmentBlendMode>> {
Ok(p_try!(self.instance.enumerate_environment_blend_modes(
self.system_id,
view_config_type
)))
}
pub(crate) fn system_properties(&self) -> VerboseResult<SystemProperties> {
Ok(p_try!(self.instance.system_properties(self.system_id)))
}
pub(crate) fn print_system_properties(system_properties: &SystemProperties) {
println!("OpenXR System Properties:");
println!("vendor_id: {}", system_properties.vendor_id);
println!("system_name: {}", system_properties.system_name);
println!("graphics_properties: {{");
println!(
"\tmax_swapchain_image_width: {}",
system_properties
.graphics_properties
.max_swapchain_image_width
);
println!(
"\tmax_swapchain_image_height: {}",
system_properties
.graphics_properties
.max_swapchain_image_height
);
println!(
"\tmax_layer_count: {}",
system_properties.graphics_properties.max_layer_count,
);
println!("}}");
println!("{:#?}", system_properties.tracking_properties);
}
}
impl std::fmt::Debug for OpenXRIntegration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "OpenXRIntegration {{ }}")
}
}
|
// 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.
/* automatically generated by rust-bindgen */
use core::libc::*;
type stbi_uc = c_uchar;
struct stbi_io_callbacks {
read: *u8,
skip: *u8,
eof: *u8,
}
type enum_unnamed1 = c_uint;
static STBI_default: u32 = 0_u32;
static STBI_grey: u32 = 1_u32;
static STBI_grey_alpha: u32 = 2_u32;
static STBI_rgb: u32 = 3_u32;
static STBI_rgb_alpha: u32 = 4_u32;
#[link_args="-L. -lstb-image"]
#[nolink]
extern mod m {
}
#[nolink]
pub extern mod bindgen {
fn stbi_load_from_memory(++buffer: *stbi_uc, ++len: c_int, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *stbi_uc;
fn stbi_load(++filename: *c_char, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *stbi_uc;
fn stbi_load_from_file(++f: *FILE, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *stbi_uc;
fn stbi_load_from_callbacks(++clbk: *stbi_io_callbacks, ++user: *c_void, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *stbi_uc;
fn stbi_loadf_from_memory(++buffer: *stbi_uc, ++len: c_int, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *c_float;
fn stbi_loadf(++filename: *c_char, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *c_float;
fn stbi_loadf_from_file(++f: *FILE, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *c_float;
fn stbi_loadf_from_callbacks(++clbk: *stbi_io_callbacks, ++user: *c_void, ++x: *c_int, ++y: *c_int, ++comp: *c_int, ++req_comp: c_int) -> *c_float;
fn stbi_hdr_to_ldr_gamma(++gamma: c_float);
fn stbi_hdr_to_ldr_scale(++scale: c_float);
fn stbi_ldr_to_hdr_gamma(++gamma: c_float);
fn stbi_ldr_to_hdr_scale(++scale: c_float);
fn stbi_is_hdr_from_callbacks(++clbk: *stbi_io_callbacks, ++user: *c_void) -> c_int;
fn stbi_is_hdr_from_memory(++buffer: *stbi_uc, ++len: c_int) -> c_int;
fn stbi_is_hdr(++filename: *c_char) -> c_int;
fn stbi_is_hdr_from_file(++f: *FILE) -> c_int;
fn stbi_failure_reason() -> *c_char;
fn stbi_image_free(++retval_from_stbi_load: *c_void);
fn stbi_info_from_memory(++buffer: *stbi_uc, ++len: c_int, ++x: *c_int, ++y: *c_int, ++comp: *c_int) -> c_int;
fn stbi_info_from_callbacks(++clbk: *stbi_io_callbacks, ++user: *c_void, ++x: *c_int, ++y: *c_int, ++comp: *c_int) -> c_int;
fn stbi_info(++filename: *c_char, ++x: *c_int, ++y: *c_int, ++comp: *c_int) -> c_int;
fn stbi_info_from_file(++f: *FILE, ++x: *c_int, ++y: *c_int, ++comp: *c_int) -> c_int;
fn stbi_set_unpremultiply_on_load(++flag_true_if_should_unpremultiply: c_int);
fn stbi_convert_iphone_png_to_rgb(++flag_true_if_should_convert: c_int);
fn stbi_zlib_decode_malloc_guesssize(++buffer: *c_char, ++len: c_int, ++initial_size: c_int, ++outlen: *c_int) -> *c_char;
fn stbi_zlib_decode_malloc(++buffer: *c_char, ++len: c_int, ++outlen: *c_int) -> *c_char;
fn stbi_zlib_decode_buffer(++obuffer: *c_char, ++olen: c_int, ++ibuffer: *c_char, ++ilen: c_int) -> c_int;
fn stbi_zlib_decode_noheader_malloc(++buffer: *c_char, ++len: c_int, ++outlen: *c_int) -> *c_char;
fn stbi_zlib_decode_noheader_buffer(++obuffer: *c_char, ++olen: c_int, ++ibuffer: *c_char, ++ilen: c_int) -> c_int;
}
|
#![allow(warnings)]
#![feature(link_args)]
#![feature(link_args)]
#[link_args = "-s EXPORTED_FUNCTIONS=['_exec']"]
#[macro_use]
extern crate dump;
#[macro_use]
extern crate stdweb;
extern crate euclid;
extern crate cgmath;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
mod sim;
use sim::*;
use stdweb::web::{document, IEventTarget, Element, NodeList, Node, INode, IElement};
use stdweb::web::event::{IEvent, ClickEvent};
use stdweb::web::html_element::InputElement;
use stdweb::event_loop;
use stdweb::unstable::TryInto;
use std::ops::DerefMut;
// mod balls;
// use balls::*;
extern "C" {}
macro_rules! enclose {
( ($( $x:ident ),*) $y:expr ) => {
{
$(let $x = $x.clone();)*
$y
}
};
}
fn console(outstr: String) {
println!("{}", outstr);
}
fn get_links() -> NodeList {
document().query_selector_all("a")
}
fn buttonClickHandler() {
let button: Element = document().query_selector("#button").unwrap();
dump!(button);
// button.try_into().unwrap();
button.add_event_listener(enclose!( (button) move|_:ClickEvent|{
button.class_list().add("clicked")
}));
}
#[no_mangle]
pub fn exec() {
stdweb::initialize();
let mut ps = points();
js!{
cool(@{ps});
}
// run(&mut ps);
// stdweb::event_loop();
}
fn main() {}
// let links = get_links();
// links
// .iter()
// .map(|link| {
// let elem: Element = link.try_into().unwrap();
// elem.class_list().add("sweet");
// })
// .count();
// buttonClickHandler(); |
mod camera;
mod hitable_list;
mod material;
mod ray;
mod sphere;
mod vec3;
use crate::camera::Camera;
use crate::hitable_list::HitableList;
use crate::material::{Lambertian, Metal};
use crate::ray::Ray;
use crate::sphere::Sphere;
use crate::vec3::Vec3;
use rand::random;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
use std::rc::Rc;
fn main() {
let path = Path::new("out.ppm");
let file = File::create(path).unwrap();
let mut writer = BufWriter::new(file);
let nx = 200;
let ny = 100;
let ns = 100;
let mut world = HitableList::new();
world.push(Box::new(Sphere::new(
Vec3(0.0, 0.0, -1.0),
0.5,
Rc::new(Lambertian {
albedo: Vec3(0.8, 0.3, 0.3),
}),
)));
world.push(Box::new(Sphere::new(
Vec3(0.0, -100.5, -1.0),
100.0,
Rc::new(Lambertian {
albedo: Vec3(0.8, 0.8, 0.0),
}),
)));
world.push(Box::new(Sphere::new(
Vec3(1.0, 0.0, -1.0),
0.5,
Rc::new(Metal {
albedo: Vec3(0.8, 0.6, 0.2),
fuzz: 0.0,
}),
)));
world.push(Box::new(Sphere::new(
Vec3(-1.0, 0.0, -1.0),
0.5,
Rc::new(Metal {
albedo: Vec3(0.8, 0.8, 0.8),
fuzz: 1.0,
}),
)));
let camera = Camera::new();
writer
.write(format!("P3\n{} {}\n255\n", nx, ny).as_bytes())
.unwrap();
for y in (0..ny).rev() {
for x in 0..nx {
let mut color = Vec3::zero();
for _ in 0..ns {
let u = (x as f64 + random::<f64>()) / nx as f64;
let v = (y as f64 + random::<f64>()) / ny as f64;
let ray = camera.get_ray(u, v);
let _point = ray.point_at(2.0);
color += Ray::color(&ray, &world, 0);
}
color /= ns as f64;
color = Vec3(color.r().sqrt(), color.g().sqrt(), color.b().sqrt());
let ir = (255.99 * color.r()) as i64;
let ig = (255.99 * color.g()) as i64;
let ib = (255.99 * color.b()) as i64;
writer
.write(format!("{} {} {}\n", ir, ig, ib).as_bytes())
.unwrap();
}
}
}
|
use crate::OutputChannel;
use crate::error::*;
use super::{RUNTIME};
use log::{error};
use nitox::{commands::*, NatsClient};
use futures::{prelude::*, future};
use prometheus::{IntCounter, Histogram};
pub struct NatsOutput {
subject: String,
nats_client: NatsClient,
msg_send_histogram: Histogram,
send_err_counter: IntCounter,
}
impl NatsOutput {
pub fn new(cluster_uri: &str, a_subject: String) -> Result<NatsOutput, DashPipeError> {
let msg_send_histogram = register_histogram!(histogram_opts!(
"dashpipe_sent_messages",
"Histogram for messages sent",
vec![1.0, 2.0],
labels! {"channel".to_string() => "nats".to_string(), "subject".to_string() => a_subject.clone(), }))
.unwrap();
let send_err_counter = register_int_counter!(opts!(
"dashpipe_sent_messages_error",
"Total number of errors while sending messages",
labels! {"channel" => "nats", "subject" => &a_subject, }))
.unwrap();
let nats_client_builder = super::connect_to_nats(cluster_uri);
let ret: Result<NatsOutput, DashPipeError> = match RUNTIME.lock().unwrap().block_on(nats_client_builder){
Ok(nats_client) => {
let output = NatsOutput{
subject: a_subject.to_owned(),
nats_client: nats_client,
msg_send_histogram: msg_send_histogram,
send_err_counter: send_err_counter,
};
Ok(output)
},
Err(nats_error) => {
let disp = format!("Unable to initialize NATs {}", nats_error);
error!("Unable to initialize NATs {}", nats_error);
Err(DashPipeError::InitializeError(disp))
}
};
ret
}
}
impl OutputChannel for NatsOutput{
fn send(&self, msg: String){
let pub_cmd = PubCommand::builder()
.subject(self.subject.to_string()).payload(msg).build().unwrap();
//try to avoid the clone
let ctr = self.send_err_counter.clone();
let timer = self.msg_send_histogram.start_timer();
let send = self.nats_client.publish(pub_cmd)
.then(move |f| {
timer.observe_duration();
match f {
Ok(_) => {},
Err(e) =>{
error!("Unable to send message {}", e);
ctr.inc();
},
}
future::ok(())
});
RUNTIME.lock().unwrap().spawn(send);
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qsizepolicy.h
// dst-file: /src/widgets/qsizepolicy.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QSizePolicy_Class_Size() -> c_int;
// proto: bool QSizePolicy::hasHeightForWidth();
fn C_ZNK11QSizePolicy17hasHeightForWidthEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QSizePolicy::retainSizeWhenHidden();
fn C_ZNK11QSizePolicy20retainSizeWhenHiddenEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QSizePolicy::hasWidthForHeight();
fn C_ZNK11QSizePolicy17hasWidthForHeightEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QSizePolicy::transpose();
fn C_ZN11QSizePolicy9transposeEv(qthis: u64 /* *mut c_void*/);
// proto: void QSizePolicy::setWidthForHeight(bool b);
fn C_ZN11QSizePolicy17setWidthForHeightEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QSizePolicy::setVerticalStretch(int stretchFactor);
fn C_ZN11QSizePolicy18setVerticalStretchEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QSizePolicy::setHeightForWidth(bool b);
fn C_ZN11QSizePolicy17setHeightForWidthEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: void QSizePolicy::setRetainSizeWhenHidden(bool retainSize);
fn C_ZN11QSizePolicy23setRetainSizeWhenHiddenEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: int QSizePolicy::horizontalStretch();
fn C_ZNK11QSizePolicy17horizontalStretchEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QSizePolicy::setHorizontalStretch(int stretchFactor);
fn C_ZN11QSizePolicy20setHorizontalStretchEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QSizePolicy::QSizePolicy();
fn C_ZN11QSizePolicyC2Ev() -> u64;
// proto: int QSizePolicy::verticalStretch();
fn C_ZNK11QSizePolicy15verticalStretchEv(qthis: u64 /* *mut c_void*/) -> c_int;
} // <= ext block end
// body block begin =>
// class sizeof(QSizePolicy)=4
#[derive(Default)]
pub struct QSizePolicy {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QSizePolicy {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSizePolicy {
return QSizePolicy{qclsinst: qthis, ..Default::default()};
}
}
// proto: bool QSizePolicy::hasHeightForWidth();
impl /*struct*/ QSizePolicy {
pub fn hasHeightForWidth<RetType, T: QSizePolicy_hasHeightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasHeightForWidth(self);
// return 1;
}
}
pub trait QSizePolicy_hasHeightForWidth<RetType> {
fn hasHeightForWidth(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: bool QSizePolicy::hasHeightForWidth();
impl<'a> /*trait*/ QSizePolicy_hasHeightForWidth<i8> for () {
fn hasHeightForWidth(self , rsthis: & QSizePolicy) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSizePolicy17hasHeightForWidthEv()};
let mut ret = unsafe {C_ZNK11QSizePolicy17hasHeightForWidthEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QSizePolicy::retainSizeWhenHidden();
impl /*struct*/ QSizePolicy {
pub fn retainSizeWhenHidden<RetType, T: QSizePolicy_retainSizeWhenHidden<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.retainSizeWhenHidden(self);
// return 1;
}
}
pub trait QSizePolicy_retainSizeWhenHidden<RetType> {
fn retainSizeWhenHidden(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: bool QSizePolicy::retainSizeWhenHidden();
impl<'a> /*trait*/ QSizePolicy_retainSizeWhenHidden<i8> for () {
fn retainSizeWhenHidden(self , rsthis: & QSizePolicy) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSizePolicy20retainSizeWhenHiddenEv()};
let mut ret = unsafe {C_ZNK11QSizePolicy20retainSizeWhenHiddenEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QSizePolicy::hasWidthForHeight();
impl /*struct*/ QSizePolicy {
pub fn hasWidthForHeight<RetType, T: QSizePolicy_hasWidthForHeight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasWidthForHeight(self);
// return 1;
}
}
pub trait QSizePolicy_hasWidthForHeight<RetType> {
fn hasWidthForHeight(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: bool QSizePolicy::hasWidthForHeight();
impl<'a> /*trait*/ QSizePolicy_hasWidthForHeight<i8> for () {
fn hasWidthForHeight(self , rsthis: & QSizePolicy) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSizePolicy17hasWidthForHeightEv()};
let mut ret = unsafe {C_ZNK11QSizePolicy17hasWidthForHeightEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QSizePolicy::transpose();
impl /*struct*/ QSizePolicy {
pub fn transpose<RetType, T: QSizePolicy_transpose<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.transpose(self);
// return 1;
}
}
pub trait QSizePolicy_transpose<RetType> {
fn transpose(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: void QSizePolicy::transpose();
impl<'a> /*trait*/ QSizePolicy_transpose<()> for () {
fn transpose(self , rsthis: & QSizePolicy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSizePolicy9transposeEv()};
unsafe {C_ZN11QSizePolicy9transposeEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QSizePolicy::setWidthForHeight(bool b);
impl /*struct*/ QSizePolicy {
pub fn setWidthForHeight<RetType, T: QSizePolicy_setWidthForHeight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWidthForHeight(self);
// return 1;
}
}
pub trait QSizePolicy_setWidthForHeight<RetType> {
fn setWidthForHeight(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: void QSizePolicy::setWidthForHeight(bool b);
impl<'a> /*trait*/ QSizePolicy_setWidthForHeight<()> for (i8) {
fn setWidthForHeight(self , rsthis: & QSizePolicy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSizePolicy17setWidthForHeightEb()};
let arg0 = self as c_char;
unsafe {C_ZN11QSizePolicy17setWidthForHeightEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QSizePolicy::setVerticalStretch(int stretchFactor);
impl /*struct*/ QSizePolicy {
pub fn setVerticalStretch<RetType, T: QSizePolicy_setVerticalStretch<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setVerticalStretch(self);
// return 1;
}
}
pub trait QSizePolicy_setVerticalStretch<RetType> {
fn setVerticalStretch(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: void QSizePolicy::setVerticalStretch(int stretchFactor);
impl<'a> /*trait*/ QSizePolicy_setVerticalStretch<()> for (i32) {
fn setVerticalStretch(self , rsthis: & QSizePolicy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSizePolicy18setVerticalStretchEi()};
let arg0 = self as c_int;
unsafe {C_ZN11QSizePolicy18setVerticalStretchEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QSizePolicy::setHeightForWidth(bool b);
impl /*struct*/ QSizePolicy {
pub fn setHeightForWidth<RetType, T: QSizePolicy_setHeightForWidth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setHeightForWidth(self);
// return 1;
}
}
pub trait QSizePolicy_setHeightForWidth<RetType> {
fn setHeightForWidth(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: void QSizePolicy::setHeightForWidth(bool b);
impl<'a> /*trait*/ QSizePolicy_setHeightForWidth<()> for (i8) {
fn setHeightForWidth(self , rsthis: & QSizePolicy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSizePolicy17setHeightForWidthEb()};
let arg0 = self as c_char;
unsafe {C_ZN11QSizePolicy17setHeightForWidthEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QSizePolicy::setRetainSizeWhenHidden(bool retainSize);
impl /*struct*/ QSizePolicy {
pub fn setRetainSizeWhenHidden<RetType, T: QSizePolicy_setRetainSizeWhenHidden<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRetainSizeWhenHidden(self);
// return 1;
}
}
pub trait QSizePolicy_setRetainSizeWhenHidden<RetType> {
fn setRetainSizeWhenHidden(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: void QSizePolicy::setRetainSizeWhenHidden(bool retainSize);
impl<'a> /*trait*/ QSizePolicy_setRetainSizeWhenHidden<()> for (i8) {
fn setRetainSizeWhenHidden(self , rsthis: & QSizePolicy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSizePolicy23setRetainSizeWhenHiddenEb()};
let arg0 = self as c_char;
unsafe {C_ZN11QSizePolicy23setRetainSizeWhenHiddenEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QSizePolicy::horizontalStretch();
impl /*struct*/ QSizePolicy {
pub fn horizontalStretch<RetType, T: QSizePolicy_horizontalStretch<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.horizontalStretch(self);
// return 1;
}
}
pub trait QSizePolicy_horizontalStretch<RetType> {
fn horizontalStretch(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: int QSizePolicy::horizontalStretch();
impl<'a> /*trait*/ QSizePolicy_horizontalStretch<i32> for () {
fn horizontalStretch(self , rsthis: & QSizePolicy) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSizePolicy17horizontalStretchEv()};
let mut ret = unsafe {C_ZNK11QSizePolicy17horizontalStretchEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QSizePolicy::setHorizontalStretch(int stretchFactor);
impl /*struct*/ QSizePolicy {
pub fn setHorizontalStretch<RetType, T: QSizePolicy_setHorizontalStretch<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setHorizontalStretch(self);
// return 1;
}
}
pub trait QSizePolicy_setHorizontalStretch<RetType> {
fn setHorizontalStretch(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: void QSizePolicy::setHorizontalStretch(int stretchFactor);
impl<'a> /*trait*/ QSizePolicy_setHorizontalStretch<()> for (i32) {
fn setHorizontalStretch(self , rsthis: & QSizePolicy) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSizePolicy20setHorizontalStretchEi()};
let arg0 = self as c_int;
unsafe {C_ZN11QSizePolicy20setHorizontalStretchEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QSizePolicy::QSizePolicy();
impl /*struct*/ QSizePolicy {
pub fn new<T: QSizePolicy_new>(value: T) -> QSizePolicy {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QSizePolicy_new {
fn new(self) -> QSizePolicy;
}
// proto: void QSizePolicy::QSizePolicy();
impl<'a> /*trait*/ QSizePolicy_new for () {
fn new(self) -> QSizePolicy {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QSizePolicyC2Ev()};
let ctysz: c_int = unsafe{QSizePolicy_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN11QSizePolicyC2Ev()};
let rsthis = QSizePolicy{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: int QSizePolicy::verticalStretch();
impl /*struct*/ QSizePolicy {
pub fn verticalStretch<RetType, T: QSizePolicy_verticalStretch<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.verticalStretch(self);
// return 1;
}
}
pub trait QSizePolicy_verticalStretch<RetType> {
fn verticalStretch(self , rsthis: & QSizePolicy) -> RetType;
}
// proto: int QSizePolicy::verticalStretch();
impl<'a> /*trait*/ QSizePolicy_verticalStretch<i32> for () {
fn verticalStretch(self , rsthis: & QSizePolicy) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK11QSizePolicy15verticalStretchEv()};
let mut ret = unsafe {C_ZNK11QSizePolicy15verticalStretchEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// <= body block end
|
use lettre::smtp::authentication::{Credentials, Mechanism};
use lettre::{SendableEmail, SmtpClient, SmtpTransport, Transport};
use lettre_email::EmailBuilder;
pub fn send_email(
email: &String,
name: &String,
subject: &String,
body: &String,
email_address: &String,
email_password: &String,
email_provider: &String,
) {
let email = EmailBuilder::new()
// Addresses can be specified by the tuple (email, alias)
.to((email, name))
.from(email_address.clone())
.subject(subject)
.html(body)
.build()
.unwrap();
let email: SendableEmail = email.into();
let credentials = Credentials::new(email_address.into(), email_password.into());
let client = SmtpClient::new_simple(email_provider)
.unwrap()
.credentials(credentials)
.authentication_mechanism(Mechanism::Plain);
// build the Transport
let mut mailer = SmtpTransport::new(client);
// Send the email
match mailer.send(email) {
Ok(_) => println!("Email sent successfully!"),
Err(e) => eprintln!("Could not send email: {:?}", e),
}
mailer.close();
}
|
use std::fmt;
/// http://paulbourke.net/dataformats/ply/
pub mod standard_formats {
use super::{PlyFormat, PlyFormatVersion};
pub const ASCII_10: PlyFormat = PlyFormat::Ascii(PlyFormatVersion::get(1, 0));
}
pub struct PlyFileHeader {
pub format: PlyFormat,
pub elements: Vec<PlyElementDescriptor>,
}
#[derive(Copy, Clone)]
pub enum PlyFormat {
Ascii(PlyFormatVersion),
BinaryLE(PlyFormatVersion),
BinaryBE(PlyFormatVersion),
}
#[derive(Copy, Clone)]
pub struct PlyFormatVersion {
pub major: u16,
pub minor: u16
}
impl PlyFormatVersion {
pub const fn get(major: u16, minor: u16) -> PlyFormatVersion {
PlyFormatVersion {
major,
minor,
}
}
}
pub struct PlyElementDescriptor {
pub element_index: u32,
pub name: String,
pub num_entries: u32,
pub properties: Vec<PlyPropertyDescriptor>
}
impl PlyElementDescriptor {
// pub fn recalc_full_element_size(&mut self) {
// let mut full_size = 0u32;
// for p in &self.properties {
// full_size += p.datatype.byte_size();
// }
// self.full_element_size = full_size;
// }
pub fn properties(&self) -> &[PlyPropertyDescriptor] {
self.properties.as_slice()
}
pub fn new(element_index: u32, name: String, num_entries: u32) -> PlyElementDescriptor {
PlyElementDescriptor {
element_index,
name,
num_entries,
properties: Vec::new(),
// full_element_size: 0,
}
}
}
pub struct PlyPropertyDescriptor {
pub name: String,
pub datatype: PlyDatatype,
}
#[derive(Copy, Clone)]
pub enum PlyDatatype {
Scalar(PlyScalar),
List {
index: PlyScalar,
element: PlyScalar,
}
}
//impl PlyDatatype {
// pub fn scalar_byte_size(&self) -> Option<u32> {
// if let PlyDatatype::Scalar(s) = self {
// Some(s.byte_size())
// } else {
// None
// }
// }
//}
impl fmt::Debug for PlyDatatype {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
use PlyDatatype as D;
match self {
D::Scalar(s) => <PlyScalar as fmt::Debug>::fmt(s, f),
D::List {index, element} => {
write!(f, "list ")?;
<PlyScalar as fmt::Debug>::fmt(index, f)?;
write!(f, " ")?;
<PlyScalar as fmt::Debug>::fmt(element, f)
}
}
}
}
#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
pub enum PlyScalar {
char,
uchar,
short,
ushort,
int,
float,
uint,
double,
}
impl PlyScalar {
pub fn byte_size(&self) -> u32 {
use PlyScalar as S;
match self {
S::char => 1,
S::uchar => 1,
S::short => 2,
S::ushort => 2,
S::int => 4,
S::uint => 4,
S::float => 4,
S::double => 8,
}
}
pub fn from_str(string: &str) -> Option<PlyScalar> {
use super::PlyScalar as S;
match string {
"char" => Some(S::char),
"uchar" => Some(S::uchar),
"short" => Some(S::short),
"ushort" => Some(S::ushort),
"int" => Some(S::int),
"uint" => Some(S::uint),
"float" => Some(S::float),
"double" => Some(S::double),
_ => None,
}
}
}
impl fmt::Debug for PlyScalar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
use PlyScalar as S;
let name = match self {
S::char => "char",
S::uchar => "uchar",
S::short => "short",
S::ushort => "ushort",
S::int => "int",
S::uint => "uint",
S::float => "float",
S::double => "double",
};
write!(f, "{}", name)
}
}
|
use nalgebra_glm as glm;
pub enum CameraDirection {
Forward,
Backward,
Left,
Right,
}
pub struct Camera {
pub position: glm::Vec3,
right: glm::Vec3,
pub front: glm::Vec3,
up: glm::Vec3,
world_up: glm::Vec3,
speed: f32,
sensitivity: f32,
yaw_degrees: f32,
pitch_degrees: f32,
}
impl Default for Camera {
fn default() -> Self {
Self::new()
}
}
impl Camera {
pub fn new() -> Self {
let mut camera = Camera {
position: glm::vec3(0.0, 0.0, 10.0),
right: glm::vec3(0.0, 0.0, 0.0),
front: glm::vec3(0.0, 0.0, -1.0),
up: glm::vec3(0.0, 0.0, 0.0),
world_up: glm::vec3(0.0, 1.0, 0.0),
speed: 50.0,
sensitivity: 0.05,
yaw_degrees: -90.0,
pitch_degrees: 0.0,
};
camera.calculate_vectors();
camera
}
// TODO: This needs testing
pub fn position_at(&mut self, position: &glm::Vec3) {
self.position = *position;
self.calculate_vectors();
}
// TODO: This also needs testing
pub fn look_at(&mut self, target: &glm::Vec3) {
self.front = (target - self.position).normalize();
self.pitch_degrees = self.front.y.asin().to_degrees();
self.yaw_degrees = (self.front.x / self.front.y.asin().cos())
.acos()
.to_degrees();
self.calculate_vectors();
}
pub fn view_matrix(&self) -> glm::Mat4 {
let target = self.position + self.front;
glm::look_at(&self.position, &target, &self.up)
}
pub fn translate(&mut self, direction: CameraDirection, delta_time: f32) {
let velocity = self.speed * delta_time;
match direction {
CameraDirection::Forward => self.position += self.front * velocity,
CameraDirection::Backward => self.position -= self.front * velocity,
CameraDirection::Left => self.position -= self.right * velocity,
CameraDirection::Right => self.position += self.right * velocity,
};
}
pub fn process_mouse_movement(&mut self, x_offset: f32, y_offset: f32) {
let (x_offset, y_offset) = (x_offset * self.sensitivity, y_offset * self.sensitivity);
self.yaw_degrees -= x_offset;
self.pitch_degrees += y_offset;
let pitch_threshold = 89.0;
if self.pitch_degrees > pitch_threshold {
self.pitch_degrees = pitch_threshold
} else if self.pitch_degrees < -pitch_threshold {
self.pitch_degrees = -pitch_threshold
}
self.calculate_vectors();
}
fn calculate_vectors(&mut self) {
let pitch_radians = self.pitch_degrees.to_radians();
let yaw_radians = self.yaw_degrees.to_radians();
self.front = glm::vec3(
pitch_radians.cos() * yaw_radians.cos(),
pitch_radians.sin(),
yaw_radians.sin() * pitch_radians.cos(),
)
.normalize();
self.right = self.front.cross(&self.world_up).normalize();
self.up = self.right.cross(&self.front).normalize();
}
}
|
//! dbase is rust library meant to read and write
//!
//! # Reading
//!
//! To Read the whole file at once you should use the [read](fn.read.html) function.
//!
//! Once you have access to the records, you will have to `match` against the real
//! [FieldValue](enum.FieldValue.html)
//!
//! # Examples
//!
//! ```
//! use dbase::FieldValue;
//! let records = dbase::read("tests/data/line.dbf").unwrap();
//! for record in records {
//! for (name, value) in record {
//! println!("{} -> {:?}", name, value);
//! match value {
//! FieldValue::Character(Some(string)) => println!("Got string: {}", string),
//! FieldValue::Numeric(value) => println!("Got numeric value of {:?}", value),
//! _ => {}
//! }
//! }
//!}
//! ```
//!
//! You can also create a [Reader](reading/Reader.struct.html) and iterate over the records.
//!
//! ```
//! let reader = dbase::Reader::from_path("tests/data/line.dbf").unwrap();
//! for record_result in reader {
//! let record = record_result.unwrap();
//! for (name, value) in record {
//! println!("name: {}, value: {:?}", name, value);
//! }
//! }
//!
//! ```
//!
//https://dbfviewer.com/dbf-file-structure/
extern crate byteorder;
pub use reading::{read, Reader, Record};
pub use record::field::FieldValue;
pub use record::FieldFlags;
pub use writing::{write_to, write_to_path, Writer};
mod header;
mod reading;
mod record;
mod writing;
/// Errors that may happen when reading a .dbf
#[derive(Debug)]
pub enum Error {
/// Wrapper of `std::io::Error` to forward any reading/writing error
IoError(std::io::Error),
/// Wrapper to forward errors whe trying to parse a float from the file
ParseFloatError(std::num::ParseFloatError),
/// Wrapper to forward errors whe trying to parse an integer value from the file
ParseIntError(std::num::ParseIntError),
/// The Field as an invalid FieldType
InvalidFieldType(char),
InvalidDate,
FieldLengthTooLong,
FieldNameTooLong,
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::IoError(e)
}
}
impl From<std::num::ParseFloatError> for Error {
fn from(p: std::num::ParseFloatError) -> Self {
Error::ParseFloatError(p)
}
}
impl From<std::num::ParseIntError> for Error {
fn from(p: std::num::ParseIntError) -> Self {
Error::ParseIntError(p)
}
}
|
use std::env::args;
use std::fs::File;
use std::io::{BufWriter, Result, Write};
use grass::algorithm::AssumeSorted;
use grass::algorithm::SortedIntersect;
use grass::properties::Serializable;
use grass::records::{Bed3, Bed4};
use grass::{chromset::LexicalChromRef, LexicalChromSet, LineRecordStreamExt};
fn main() -> Result<()> {
let args: Vec<_> = args().skip(1).take(3).collect();
let chroms = LexicalChromSet::new();
let bed3_file = File::open(&args[0])?
.into_record_iter::<Bed3<LexicalChromRef>, _>(&chroms)
.assume_sorted();
let bed4_file = File::open(&args[1])?
.into_record_iter::<Bed4<LexicalChromRef>, _>(&chroms)
.assume_sorted();
let mut out_file = BufWriter::new(File::create(&args[2])?);
for pair in bed3_file.sorted_intersect(bed4_file) {
let result = Bed3::new(&pair);
result.dump(&mut out_file)?;
out_file.write_all(b"\n")?;
}
Ok(())
}
|
mod logfile;
mod iter;
pub use self::logfile::*;
|
use super::*;
#[derive(Clone)]
pub struct Assignment {
var: Variable,
constant: Constant
}
impl Assignment {
pub fn new(var: Variable, c: Constant) -> Assignment {
Assignment {
var: var,
constant: c,
}
}
pub fn variable(&self) -> &Variable {
&self.var
}
pub fn constant(&self) -> &Constant {
&self.constant
}
} |
use crate::game_data::locale;
use chrono::Duration;
use itertools::Itertools;
use serde::Deserialize;
use serde_with::{serde_as, CommaSeparator, DisplayFromStr, DurationSeconds, StringWithSeparator};
#[serde_as]
#[derive(Debug, Deserialize)]
pub struct ItemSpecifier {
pub name: String,
#[serde_as(as = "DisplayFromStr")]
pub count: u32,
}
impl ItemSpecifier {
pub fn display_name(&self) -> &str {
locale::DISPLAY_NAMES
.get(&self.name)
.map(|s| s.as_str())
.unwrap_or(&"DISPLAY_NAME_NOT_FOUND")
}
}
// <recipe name="drinkCanEmpty" count="1" material_based="true" craft_area="forge" tags="perkAdvancedEngineering">
// <ingredient name="unit_iron" count="5"/>
// <ingredient name="unit_clay" count="1"/>
// <effect_group>
// <passive_effect name="CraftingIngredientCount" operation="perc_add" level="0,1,2,3,4" value=".25,.25,.25,.177,.12" tags="unit_iron"/>
// </effect_group>
// </recipe>
// All tags:
// [
// "boiledWater",
// "cementMixerCrafting",
// "chemStationCrafting",
// "learnable",
// "perkAdvancedEngineering",
// "perkArchery",
// "perkBoomstick",
// "perkBrawler",
// "perkChefBoiledWater",
// "perkDeadEye",
// "perkDeepCuts",
// "perkDemolitionsExpert",
// "perkElectrocutioner",
// "perkGreaseMonkey",
// "perkGunslinger",
// "perkHeavyArmor",
// "perkJavelinMaster",
// "perkLightArmor",
// "perkLivingOffTheLandCrafting",
// "perkMachineGunner",
// "perkMasterChef",
// "perkMiner69r",
// "perkPummelPete",
// "perkSalvageOperations",
// "perkSkullCrusher",
// "perkTurrets",
// "salvageScrap",
// "workbenchCrafting",
// ]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CraftArea {
Campfire,
CementMixer,
ChemistryStation,
Forge,
Workbench,
}
#[derive(Debug, Deserialize)]
pub enum CraftTool {
#[serde(rename = "toolBeaker")]
Beaker,
#[serde(rename = "toolCookingGrill")]
CookingGrill,
#[serde(rename = "toolCookingPot")]
CookingPot,
#[serde(rename = "toolForgeCrucible")]
Crucible,
}
fn zero_duration() -> Duration {
Duration::seconds(0)
}
// TODO: "material_based" recipes supposedly mean it can be smelted down in the forge... Does that mean the recipe works the other way around for that? Check if "material_based" recipes exist with craft_area other than forge. Update: probably not, see resourceRockSmall
#[serde_as]
#[derive(Debug, Deserialize)]
pub struct Recipe {
#[serde(flatten)]
pub result: ItemSpecifier,
#[serde(rename = "ingredient", default)]
pub ingredients: Vec<ItemSpecifier>,
pub craft_area: Option<CraftArea>,
#[serde_as(as = "StringWithSeparator::<CommaSeparator, String>")]
#[serde(default)]
pub tags: Vec<String>,
// wildcard_forge_category has to do with forge_category in materials.xml
// wildcard_forge_category is an empty tag if present, so this is deserialized a bit strangely and we have to use the is_wildcard_forge_category function to expose the actual value
wildcard_forge_category: Option<String>,
pub craft_tool: Option<CraftTool>,
#[serde_as(as = "DurationSeconds<String>")]
#[serde(default = "zero_duration")]
pub craft_time: Duration,
}
impl Recipe {
pub fn is_wildcard_forge_category(&self) -> bool {
self.wildcard_forge_category.is_some()
}
}
#[derive(Debug, Deserialize)]
pub struct RecipesFile {
#[serde(rename = "$value")]
pub recipes: Vec<Recipe>,
}
impl RecipesFile {
/// Returns a list of all recipe tags present in the recipe file
pub fn get_unique_recipe_tags(&self) -> Vec<&String> {
self.recipes
.iter()
.flat_map(|r| &r.tags)
.sorted()
.dedup()
.collect()
}
}
|
#[doc = "Reader of register CR"]
pub type R = crate::R<u32, super::CR>;
#[doc = "Writer for register CR"]
pub type W = crate::W<u32, super::CR>;
#[doc = "Register CR `reset()`'s with value 0"]
impl crate::ResetValue for super::CR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `DEN`"]
pub type DEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DEN`"]
pub struct DEN_W<'a> {
w: &'a mut W,
}
impl<'a> DEN_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 `SEN`"]
pub type SEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SEN`"]
pub struct SEN_W<'a> {
w: &'a mut W,
}
impl<'a> SEN_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
}
}
impl R {
#[doc = "Bit 0 - Delay block enable bit"]
#[inline(always)]
pub fn den(&self) -> DEN_R {
DEN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Sampler length enable bit"]
#[inline(always)]
pub fn sen(&self) -> SEN_R {
SEN_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Delay block enable bit"]
#[inline(always)]
pub fn den(&mut self) -> DEN_W {
DEN_W { w: self }
}
#[doc = "Bit 1 - Sampler length enable bit"]
#[inline(always)]
pub fn sen(&mut self) -> SEN_W {
SEN_W { w: self }
}
}
|
//! Defines functionality for the property tag interface of the BCM2837 mailbox system.
//!
//! There is some documentation on the various tags that are supported by this interface on the
//! [Raspberry Pi Wiki], along with information which defines most of the implementation used in
//! this module.
//!
//! Currently only sending a single tag at a time is supported.
//!
//! [Raspberry Pi Wiki]: https://github.com/raspberrypi/firmware/wiki/Mailbox-property-interface
pub mod set_gpio_state;
pub use self::set_gpio_state::*;
use board::mem;
use core::intrinsics;
use mmio;
use super::Channel;
pub trait PropertyTag {
fn id(&self) -> u32;
fn buffer(&self) -> &[u8];
}
const PT_PROCESS_REQUEST: u32 = 0;
const PT_END_TAG: u32 = 0;
extern "C" {
/// A 16-byte aligned buffer, defined in assembly (`property_tags.s`)
static __property_tags: *mut u8;
}
/// Sends a property tag request to the VideoCore via the mailbox.
pub fn send<T>(tag: &T)
where T: PropertyTag
{
// Currently we use a single static buffer, defined in assembly, as Rust doesn't have a nice
// way to align stack-allocated buffers. This means that you can only send property tags
// synchronously at the moment, whereas the actual interface allows asynchronous requests.
unsafe {
let addr = __property_tags as usize;
// Buffer size in bytes (including the header values, the end tag and padding)
mmio::write(addr + 0, 24 + tag.buffer().len());
// Buffer request code
mmio::write(addr + 4, PT_PROCESS_REQUEST);
// Tag identifier
mmio::write(addr + 8, tag.id());
// Tag buffer size in bytes
mmio::write(addr + 12, tag.buffer().len());
// Tag request code
mmio::write(addr + 16, PT_PROCESS_REQUEST);
// End tag
mmio::write(addr + 16 + tag.buffer().len(), PT_END_TAG);
// Copy the tag data into the buffer
intrinsics::volatile_copy_nonoverlapping_memory(__property_tags.offset(20),
tag.buffer().as_ptr(),
tag.buffer().len());
// Send the buffer address to the mailbox
super::write(addr as u32, Channel::PropertyTags);
mem::write_barrier();
// Read the value received from the mailbox. Without this read, the mailbox would
// eventually become full and no more messages could be send. Currently the data returned
// by the mailbox is ignored.
let _ = super::read(Channel::PropertyTags);
mem::read_barrier();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.