text stringlengths 8 4.13M |
|---|
#[allow(unused_imports)]
#[macro_use] extern crate serde_derive;
extern crate reqwest;
extern crate serde;
extern crate serde_json;
extern crate url;
use std::io;
use std::io::Read;
use serde_json::Value;
use url::Url;
#[allow(unused_must_use)]
fn get_json(zip: &str) -> Value {
let key = "1aa84f76ad87af18";
let url_str = format!("http://api.wunderground.com/api/{}/conditions/q/{}.json", key, zip);
let url = Url::parse(url_str.as_str()).unwrap();
let mut resp = reqwest::get(url).unwrap();
assert!(resp.status().is_success());
let mut content = String::new();
resp.read_to_string(&mut content);
serde_json::from_str(content.as_str()).unwrap()
}
fn main() {
println!("What area would you like a forecast for? ");
let mut zip = String::new();
io::stdin()
.read_line(&mut zip)
.expect("Failed to read line");
let zip = zip.trim();
let json = get_json(zip);
let chars_to_trim: &[char] = &['"'];
let ref feels_like = json["current_observation"]["feelslike_string"].to_string();
let feels_like = feels_like.trim_matches(chars_to_trim);
let ref weather = json["current_observation"]["weather"].to_string();
let weather = weather.trim_matches(chars_to_trim);
println!("Weather for {} is currently {}, and temp feels like {}", zip, weather, feels_like);
}
|
use std::env;
use std::string::String;
use std::num;
use std::num::strconv;
use std::ffi::OsStr;
use std::path::PathBuf;
pub fn get_prompt(status: isize) -> String {
let cwd = match env::current_dir() {
Ok(d) => {d},
Err(f) => {panic!(f.to_string())},
};
let home = match env::home_dir() {
Some(p) => {p},
None => {PathBuf::from("/")},
};
let dir = match cwd.file_name() {
Some(d) => {d},
None => {OsStr::from_str("/")},
};
let dispdir = match cwd == home {
true => "~",
false => dir.to_str().unwrap_or("dir not found"),
};
let mut pro = String::new();
let fstat: f64 = num::cast(status).unwrap();
//this function is really complicated
let (dispstat, flag) = strconv::float_to_str_common(
fstat,
10,
true,
strconv::SignFormat::SignNeg,
strconv::SignificantDigits::DigAll, //this could go poorly, but i hope not
strconv::ExponentFormat::ExpNone,
false);
if status != 0 && !flag {
pro.push('(');
pro.push_str(dispstat.as_slice());
pro.push(')');
pro.push(' ');
}
pro.push_str(dispdir);
pro.push_str(" $ ");
pro
}
#[cfg(test)]
mod tests {
use prompt::get_prompt;
use std::env;
use std::string::String;
use std::path;
//make constant directory
use std::path::Path;
#[test]
fn status_is_zero() {
let root = Path::new("/tmp");
assert!(env::set_current_dir(&root).is_ok());
let dir = env::current_dir().unwrap();
let file = dir.file_name().unwrap();
let dir_st = file.to_str().unwrap();
let mut out = String::new();
out.push_str(dir_st);
out.push_str(" $ ");
assert_eq!(out, get_prompt(0));
}
#[test]
fn status_non_zero() {
let root = Path::new("/tmp");
assert!(env::set_current_dir(&root).is_ok());
let dir = env::current_dir().unwrap();
let file = dir.file_name().unwrap();
let dir_st = file.to_str().unwrap();
let mut out = String::new();
out.push_str("(101) ");
out.push_str(dir_st);
out.push_str(" $ ");
assert_eq!(out, get_prompt(101));
}
}
|
/*
Copyright 2020 Timo Saarinen
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use super::*;
// -------------------------------------------------------------------------------------------------
/// Type 21: Aid-to-Navigation Report
#[derive(Default, Clone, Debug, PartialEq)]
pub struct AidToNavigationReport {
/// True if the data is about own vessel, false if about other.
pub own_vessel: bool,
/// AIS station type.
pub station: Station,
/// User ID (30 bits)
pub mmsi: u32,
/// Aid type (5 bits)
pub aid_type: NavAidType,
/// Name (120 bits)
pub name: String,
/// Position accuracy.
high_position_accuracy: bool,
/// Latitude
pub latitude: Option<f64>,
/// Longitude
pub longitude: Option<f64>,
/// Overall dimension / reference for position A (9 bits)
pub dimension_to_bow: Option<u16>,
/// Overall dimension / reference for position B (9 bits)
pub dimension_to_stern: Option<u16>,
/// Overall dimension / reference for position C (6 bits)
pub dimension_to_port: Option<u16>,
/// Overall dimension / reference for position C (6 bits)
pub dimension_to_starboard: Option<u16>,
// Type of electronic position fixing device.
pub position_fix_type: Option<PositionFixType>,
/// Derived from UTC second (6 bits)
pub timestamp_seconds: u8,
/// Off-position indicator (1 bit):
/// true = off position, false = on position
pub off_position_indicator: bool,
/// Regional reserved, uninterpreted.
pub regional: u8,
/// Riverine And Inland Navigation systems blue sign:
/// RAIM (Receiver autonomous integrity monitoring) flag of electronic position
/// fixing device; false = RAIM not in use = default; true = RAIM in use
pub raim_flag: bool,
/// Virtual aid flag:
/// true = virtual aid to navigation simulated by nearby AIS station
/// false = real aid to navigation at indicated position
pub virtual_aid_flag: bool,
/// Assigned-mode flag
pub assigned_mode_flag: bool,
}
impl LatLon for AidToNavigationReport {
fn latitude(&self) -> Option<f64> {
self.latitude
}
fn longitude(&self) -> Option<f64> {
self.longitude
}
}
/// Type of navigation aid
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum NavAidType {
/// Default, type not specified
NotSpecified, // 0
/// Reference point
ReferencePoint, // 1
/// RACON (radar transponder marking a navigation hazard)
Racon, // 2
/// Fixed structure off shore
FixedStructure, // 3
/// Reserved for future use.
Reserved4, // 4
/// Light without sectors
LightWithoutSectors, // 5
/// Light with sectors
LightWithSectors, // 6
/// Leading light front
LeadingLightFront, // 7
/// Leading light rear
LeadingLightRear, // 8
/// Beacon, Cardinal North
BeaconCardinalNorth, // 9
/// Beacon, Cardinal East
BeaconCardinalEast, // 10
/// Beacon, Cardinal South
BeaconCardinalSouth, // 11
/// Beacon, Cardinal West
BeaconCardinalWest, // 12
/// Beacon, Port
BeaconLateralPort, // 13
/// Beacon, Starboard
BeaconLateralStarboard, // 14
/// Beacon, preferred channel port
BeaconLateralPreferredChannelPort, // 15
/// Beacon, preferred channel starboard
BeaconLateralPreferredChannelStarboard, // 16
/// Beacon, isolated danger
BeaconIsolatedDanger, // 17
/// Beacon, safe water
BeaconSafeWater, // 18
/// Beacon, special mark
BeaconSpecialMark, // 19
/// Cardinal Mark, north
CardinalMarkNorth, // 20
/// Cardinal Mark, east
CardinalMarkEast, // 21
/// Cardinal Mark, south
CardinalMarkSouth, // 22
/// Cardinal Mark, west
CardinalMarkWest, // 23
/// Port hand mark
PortHandMark, // 24
/// Starboard hand mark
StarboardHandMark, // 25
/// Preferred channel, port
PreferredChannelPort, // 26
/// Preferred channel, starboard
PreferredChannelStarboard, // 27
/// Isolated danger
IsolatedDanger, // 28
/// Safe Water
SafeWater, // 29
/// Special mark
SpecialMark, // 30
/// Light vessel / LANBY / rigs
LightVessel, // 31
}
impl NavAidType {
fn new(raw: u8) -> Result<NavAidType, ParseError> {
match raw {
0 => Ok(NavAidType::NotSpecified),
1 => Ok(NavAidType::ReferencePoint),
2 => Ok(NavAidType::Racon),
3 => Ok(NavAidType::FixedStructure),
4 => Ok(NavAidType::Reserved4),
5 => Ok(NavAidType::LightWithoutSectors),
6 => Ok(NavAidType::LightWithSectors),
7 => Ok(NavAidType::LeadingLightFront),
8 => Ok(NavAidType::LeadingLightRear),
9 => Ok(NavAidType::BeaconCardinalNorth),
10 => Ok(NavAidType::BeaconCardinalEast),
11 => Ok(NavAidType::BeaconCardinalSouth),
12 => Ok(NavAidType::BeaconCardinalWest),
13 => Ok(NavAidType::BeaconLateralPort),
14 => Ok(NavAidType::BeaconLateralStarboard),
15 => Ok(NavAidType::BeaconLateralPreferredChannelPort),
16 => Ok(NavAidType::BeaconLateralPreferredChannelStarboard),
17 => Ok(NavAidType::BeaconIsolatedDanger),
18 => Ok(NavAidType::BeaconSafeWater),
19 => Ok(NavAidType::BeaconSpecialMark),
20 => Ok(NavAidType::CardinalMarkNorth),
21 => Ok(NavAidType::CardinalMarkEast),
22 => Ok(NavAidType::CardinalMarkSouth),
23 => Ok(NavAidType::CardinalMarkWest),
24 => Ok(NavAidType::PortHandMark),
25 => Ok(NavAidType::StarboardHandMark),
26 => Ok(NavAidType::PreferredChannelPort),
27 => Ok(NavAidType::PreferredChannelStarboard),
28 => Ok(NavAidType::IsolatedDanger),
29 => Ok(NavAidType::SafeWater),
30 => Ok(NavAidType::SpecialMark),
31 => Ok(NavAidType::LightVessel),
_ => Err(format!("Unrecognized Nav aid type code: {}", raw).into()),
}
}
}
impl Default for NavAidType {
fn default() -> NavAidType {
NavAidType::NotSpecified
}
}
impl std::fmt::Display for NavAidType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NavAidType::NotSpecified => write!(f, "not specified"),
NavAidType::ReferencePoint => write!(f, "reference point"),
NavAidType::Racon => write!(f, "RACON"),
NavAidType::FixedStructure => write!(f, "FixedStructure"),
NavAidType::Reserved4 => write!(f, "(reserved)"),
NavAidType::LightWithoutSectors => write!(f, "light without sectors"),
NavAidType::LightWithSectors => write!(f, "light with sectors"),
NavAidType::LeadingLightFront => write!(f, "leading light front"),
NavAidType::LeadingLightRear => write!(f, "leading light rear"),
NavAidType::BeaconCardinalNorth => write!(f, "cardinal beacon, north"),
NavAidType::BeaconCardinalEast => write!(f, "cardinal beacon, east"),
NavAidType::BeaconCardinalSouth => write!(f, "cardinal beacon, south"),
NavAidType::BeaconCardinalWest => write!(f, "cardinal beacon, west"),
NavAidType::BeaconLateralPort => write!(f, "lateral beacon, port side"),
NavAidType::BeaconLateralStarboard => write!(f, "lateral beacon, starboard side"),
NavAidType::BeaconLateralPreferredChannelPort => {
write!(f, "lateral beacon, preferred channel, port side")
}
NavAidType::BeaconLateralPreferredChannelStarboard => {
write!(f, "lateral beacon, preferred channel, starboard side")
}
NavAidType::BeaconIsolatedDanger => write!(f, "isolated danger beacon"),
NavAidType::BeaconSafeWater => write!(f, "safe water"),
NavAidType::BeaconSpecialMark => write!(f, "special mark"),
NavAidType::CardinalMarkNorth => write!(f, "cardinal mark, north"),
NavAidType::CardinalMarkEast => write!(f, "cardinal mark, east"),
NavAidType::CardinalMarkSouth => write!(f, "cardinal mark, south"),
NavAidType::CardinalMarkWest => write!(f, "cardinal mark, west"),
NavAidType::PortHandMark => write!(f, "port hand mark"),
NavAidType::StarboardHandMark => write!(f, "starboard hand mark"),
NavAidType::PreferredChannelPort => write!(f, "preferred channel, port side"),
NavAidType::PreferredChannelStarboard => write!(f, "preferred channel, starboard side"),
NavAidType::IsolatedDanger => write!(f, "isolated danger"),
NavAidType::SafeWater => write!(f, "safe water"),
NavAidType::SpecialMark => write!(f, "special mark"),
NavAidType::LightVessel => write!(f, "light vessel"),
}
}
}
// -------------------------------------------------------------------------------------------------
/// AIS VDM/VDO type 21: Aid-to-Navigation Report
pub(crate) fn handle(
bv: &BitVec,
station: Station,
own_vessel: bool,
) -> Result<ParsedMessage, ParseError> {
Ok(ParsedMessage::AidToNavigationReport(
AidToNavigationReport {
own_vessel: { own_vessel },
station: { station },
mmsi: { pick_u64(&bv, 8, 30) as u32 },
aid_type: {
NavAidType::new(pick_u64(&bv, 38, 5) as u8)
.ok()
.unwrap_or(NavAidType::NotSpecified)
},
name: {
let mut s = pick_string(&bv, 43, 20);
s.push_str(&pick_string(&bv, 272, 14));
s
},
high_position_accuracy: { pick_u64(&bv, 163, 1) != 0 },
latitude: {
let lat_raw = pick_i64(&bv, 192, 27) as i32;
if lat_raw != 0x3412140 {
Some((lat_raw as f64) / 600000.0)
} else {
None
}
},
longitude: {
let lon_raw = pick_i64(&bv, 164, 28) as i32;
if lon_raw != 0x6791AC0 {
Some((lon_raw as f64) / 600000.0)
} else {
None
}
},
dimension_to_bow: { Some(pick_u64(&bv, 219, 9) as u16) },
dimension_to_stern: { Some(pick_u64(&bv, 228, 9) as u16) },
dimension_to_port: { Some(pick_u64(&bv, 237, 6) as u16) },
dimension_to_starboard: { Some(pick_u64(&bv, 243, 6) as u16) },
position_fix_type: { Some(PositionFixType::new(pick_u64(&bv, 249, 4) as u8)) },
timestamp_seconds: { pick_u64(&bv, 253, 6) as u8 },
off_position_indicator: { pick_u64(&bv, 243, 1) != 0 },
regional: { pick_u64(&bv, 260, 8) as u8 },
raim_flag: { pick_u64(&bv, 268, 1) != 0 },
virtual_aid_flag: { pick_u64(&bv, 269, 1) != 0 },
assigned_mode_flag: { pick_u64(&bv, 270, 1) != 0 },
},
))
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_vdm_type21() {
let mut p = NmeaParser::new();
match p.parse_sentence("!AIVDM,2,1,5,B,E1mg=5J1T4W0h97aRh6ba84<h2d;W:Te=eLvH50```q,0*46") {
Ok(ps) => match ps {
ParsedMessage::Incomplete => {
assert!(true);
}
_ => {
assert!(false);
}
},
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
match p.parse_sentence("!AIVDM,2,2,5,B,:D44QDlp0C1DU00,2*36") {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::AidToNavigationReport(atnr) => {
assert_eq!(atnr.mmsi, 123456789);
assert_eq!(atnr.aid_type, NavAidType::CardinalMarkNorth);
assert_eq!(atnr.name, "CHINA ROSE MURPHY EXPRESS ALERT");
assert_eq!(atnr.high_position_accuracy, false);
assert::close(atnr.latitude.unwrap_or(0.0), 47.9206183333, 0.00000001);
assert::close(atnr.longitude.unwrap_or(0.0), -122.698591667, 0.00000001);
assert_eq!(atnr.dimension_to_bow, Some(5));
assert_eq!(atnr.dimension_to_stern, Some(5));
assert_eq!(atnr.dimension_to_port, Some(5));
assert_eq!(atnr.dimension_to_starboard, Some(5));
assert_eq!(atnr.position_fix_type, Some(PositionFixType::GPS));
assert_eq!(atnr.timestamp_seconds, 50);
assert_eq!(atnr.off_position_indicator, false);
assert_eq!(atnr.regional, 165);
assert_eq!(atnr.raim_flag, false);
assert_eq!(atnr.virtual_aid_flag, false);
assert_eq!(atnr.assigned_mode_flag, false);
}
ParsedMessage::Incomplete => {
assert!(false);
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
}
}
|
use crate::archives::packages::patches::{block::MAX_BLOCK_LENGTH, Id, Patch, Entry, Block, decrypt::decrypt};
use std::collections::HashMap;
use std::io::{Write, SeekFrom, Seek, Read};
use crate::archives::Oodle;
use std::alloc::Layout;
#[derive(Debug)]
pub struct Package {
pub id: Id,
pub patches: HashMap<Id, Patch>,
pub description: String,
}
impl Package {
pub fn new(id: Id, description: String) -> Package {
Package {
id,
patches: HashMap::new(),
description,
}
}
pub fn get_master_patch(&self) -> &Patch {
self.patches.get(self.patches.keys().max().unwrap()).unwrap()
}
pub fn get_entries(&self) -> &Vec<Entry> {
self.get_master_patch().get_entries()
}
pub fn get_blocks(&self) -> &Vec<Block> {
self.get_master_patch().get_blocks()
}
pub fn get_block_bytes(&self, block: Block) -> Vec<u8> {
let patch = self.patches.get(&block.patch_id).unwrap();
let size = block.size as usize;
let mut file = patch.file_info.get_file();
file.seek(SeekFrom::Start(block.offset as u64)).expect("Seek failed!");
let layout = Layout::array::<u8>(
size
).expect("Could not create layout!");
let raw_bytes = unsafe {
let pointer = std::alloc::alloc(layout) as *mut u8;
let target = std::slice::from_raw_parts_mut(pointer, size);
file.read_exact(target).expect("Slice read failed!");
target.to_vec()
};
let decrypted_bytes: Vec<u8>;
if block.is_encrypted() {
decrypted_bytes = decrypt(
self.id,
patch.file_info.header.version,
block.is_using_alternate_key(),
raw_bytes
);
} else {
decrypted_bytes = raw_bytes;
}
let mut decompressed_bytes: Vec<u8>;
if block.is_compressed() {
decompressed_bytes = Oodle::lz_decompress(decrypted_bytes);
} else {
decompressed_bytes = decrypted_bytes;
}
decompressed_bytes.truncate(block.size as usize);
decompressed_bytes
}
pub fn extract_entry(&self, entry: Entry) -> Vec<u8> {
self.get_entry_blocks(entry).1
}
pub fn get_entry_blocks(&self, entry: Entry) -> (Vec<Block>, Vec<u8>) {
let size = entry.get_size() as usize;
let index = entry.get_start_block_index() as usize;
let offset = entry.get_precise_start_block_offset() as usize;
let count = (offset + size + MAX_BLOCK_LENGTH - 1) / MAX_BLOCK_LENGTH;
let entry_blocks = &self.get_blocks()[index..(index + count)];
let mut entry_bytes: Vec<u8> = Vec::<u8>::with_capacity(size + offset);
for block in entry_blocks {
entry_bytes.write_all(self.get_block_bytes(*block).as_slice()).unwrap();
}
(entry_blocks.to_vec(), entry_bytes[offset..].to_vec())
}
} |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DDP_FILE_EXTENT {
pub Length: i64,
pub Offset: i64,
}
impl DDP_FILE_EXTENT {}
impl ::core::default::Default for DDP_FILE_EXTENT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DDP_FILE_EXTENT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DDP_FILE_EXTENT").field("Length", &self.Length).field("Offset", &self.Offset).finish()
}
}
impl ::core::cmp::PartialEq for DDP_FILE_EXTENT {
fn eq(&self, other: &Self) -> bool {
self.Length == other.Length && self.Offset == other.Offset
}
}
impl ::core::cmp::Eq for DDP_FILE_EXTENT {}
unsafe impl ::windows::core::Abi for DDP_FILE_EXTENT {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DEDUP_BACKUP_SUPPORT_PARAM_TYPE(pub i32);
pub const DEDUP_RECONSTRUCT_UNOPTIMIZED: DEDUP_BACKUP_SUPPORT_PARAM_TYPE = DEDUP_BACKUP_SUPPORT_PARAM_TYPE(1i32);
pub const DEDUP_RECONSTRUCT_OPTIMIZED: DEDUP_BACKUP_SUPPORT_PARAM_TYPE = DEDUP_BACKUP_SUPPORT_PARAM_TYPE(2i32);
impl ::core::convert::From<i32> for DEDUP_BACKUP_SUPPORT_PARAM_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DEDUP_BACKUP_SUPPORT_PARAM_TYPE {
type Abi = Self;
}
pub const DEDUP_CHUNKLIB_MAX_CHUNKS_ENUM: u32 = 1024u32;
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DEDUP_CHUNK_INFO_HASH32 {
pub ChunkFlags: u32,
pub ChunkOffsetInStream: u64,
pub ChunkSize: u64,
pub HashVal: [u8; 32],
}
impl DEDUP_CHUNK_INFO_HASH32 {}
impl ::core::default::Default for DEDUP_CHUNK_INFO_HASH32 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DEDUP_CHUNK_INFO_HASH32 {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DEDUP_CHUNK_INFO_HASH32").field("ChunkFlags", &self.ChunkFlags).field("ChunkOffsetInStream", &self.ChunkOffsetInStream).field("ChunkSize", &self.ChunkSize).field("HashVal", &self.HashVal).finish()
}
}
impl ::core::cmp::PartialEq for DEDUP_CHUNK_INFO_HASH32 {
fn eq(&self, other: &Self) -> bool {
self.ChunkFlags == other.ChunkFlags && self.ChunkOffsetInStream == other.ChunkOffsetInStream && self.ChunkSize == other.ChunkSize && self.HashVal == other.HashVal
}
}
impl ::core::cmp::Eq for DEDUP_CHUNK_INFO_HASH32 {}
unsafe impl ::windows::core::Abi for DEDUP_CHUNK_INFO_HASH32 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DEDUP_CONTAINER_EXTENT {
pub ContainerIndex: u32,
pub StartOffset: i64,
pub Length: i64,
}
impl DEDUP_CONTAINER_EXTENT {}
impl ::core::default::Default for DEDUP_CONTAINER_EXTENT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DEDUP_CONTAINER_EXTENT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DEDUP_CONTAINER_EXTENT").field("ContainerIndex", &self.ContainerIndex).field("StartOffset", &self.StartOffset).field("Length", &self.Length).finish()
}
}
impl ::core::cmp::PartialEq for DEDUP_CONTAINER_EXTENT {
fn eq(&self, other: &Self) -> bool {
self.ContainerIndex == other.ContainerIndex && self.StartOffset == other.StartOffset && self.Length == other.Length
}
}
impl ::core::cmp::Eq for DEDUP_CONTAINER_EXTENT {}
unsafe impl ::windows::core::Abi for DEDUP_CONTAINER_EXTENT {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DEDUP_SET_PARAM_TYPE(pub i32);
pub const DEDUP_PT_MinChunkSizeBytes: DEDUP_SET_PARAM_TYPE = DEDUP_SET_PARAM_TYPE(1i32);
pub const DEDUP_PT_MaxChunkSizeBytes: DEDUP_SET_PARAM_TYPE = DEDUP_SET_PARAM_TYPE(2i32);
pub const DEDUP_PT_AvgChunkSizeBytes: DEDUP_SET_PARAM_TYPE = DEDUP_SET_PARAM_TYPE(3i32);
pub const DEDUP_PT_InvariantChunking: DEDUP_SET_PARAM_TYPE = DEDUP_SET_PARAM_TYPE(4i32);
pub const DEDUP_PT_DisableStrongHashComputation: DEDUP_SET_PARAM_TYPE = DEDUP_SET_PARAM_TYPE(5i32);
impl ::core::convert::From<i32> for DEDUP_SET_PARAM_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DEDUP_SET_PARAM_TYPE {
type Abi = Self;
}
pub const DedupBackupSupport: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x73d6b2ad_2984_4715_b2e3_924c149744dd);
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DedupChunk {
pub Hash: DedupHash,
pub Flags: DedupChunkFlags,
pub LogicalSize: u32,
pub DataSize: u32,
}
impl DedupChunk {}
impl ::core::default::Default for DedupChunk {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DedupChunk {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DedupChunk").field("Hash", &self.Hash).field("Flags", &self.Flags).field("LogicalSize", &self.LogicalSize).field("DataSize", &self.DataSize).finish()
}
}
impl ::core::cmp::PartialEq for DedupChunk {
fn eq(&self, other: &Self) -> bool {
self.Hash == other.Hash && self.Flags == other.Flags && self.LogicalSize == other.LogicalSize && self.DataSize == other.DataSize
}
}
impl ::core::cmp::Eq for DedupChunk {}
unsafe impl ::windows::core::Abi for DedupChunk {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DedupChunkFlags(pub i32);
pub const DedupChunkFlags_None: DedupChunkFlags = DedupChunkFlags(0i32);
pub const DedupChunkFlags_Compressed: DedupChunkFlags = DedupChunkFlags(1i32);
impl ::core::convert::From<i32> for DedupChunkFlags {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DedupChunkFlags {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DedupChunkingAlgorithm(pub i32);
pub const DedupChunkingAlgorithm_Unknonwn: DedupChunkingAlgorithm = DedupChunkingAlgorithm(0i32);
pub const DedupChunkingAlgorithm_V1: DedupChunkingAlgorithm = DedupChunkingAlgorithm(1i32);
impl ::core::convert::From<i32> for DedupChunkingAlgorithm {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DedupChunkingAlgorithm {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DedupCompressionAlgorithm(pub i32);
pub const DedupCompressionAlgorithm_Unknonwn: DedupCompressionAlgorithm = DedupCompressionAlgorithm(0i32);
pub const DedupCompressionAlgorithm_Xpress: DedupCompressionAlgorithm = DedupCompressionAlgorithm(1i32);
impl ::core::convert::From<i32> for DedupCompressionAlgorithm {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DedupCompressionAlgorithm {
type Abi = Self;
}
pub const DedupDataPort: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8f107207_1829_48b2_a64b_e61f8e0d9acb);
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DedupDataPortManagerOption(pub i32);
pub const DedupDataPortManagerOption_None: DedupDataPortManagerOption = DedupDataPortManagerOption(0i32);
pub const DedupDataPortManagerOption_AutoStart: DedupDataPortManagerOption = DedupDataPortManagerOption(1i32);
pub const DedupDataPortManagerOption_SkipReconciliation: DedupDataPortManagerOption = DedupDataPortManagerOption(2i32);
impl ::core::convert::From<i32> for DedupDataPortManagerOption {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DedupDataPortManagerOption {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DedupDataPortRequestStatus(pub i32);
pub const DedupDataPortRequestStatus_Unknown: DedupDataPortRequestStatus = DedupDataPortRequestStatus(0i32);
pub const DedupDataPortRequestStatus_Queued: DedupDataPortRequestStatus = DedupDataPortRequestStatus(1i32);
pub const DedupDataPortRequestStatus_Processing: DedupDataPortRequestStatus = DedupDataPortRequestStatus(2i32);
pub const DedupDataPortRequestStatus_Partial: DedupDataPortRequestStatus = DedupDataPortRequestStatus(3i32);
pub const DedupDataPortRequestStatus_Complete: DedupDataPortRequestStatus = DedupDataPortRequestStatus(4i32);
pub const DedupDataPortRequestStatus_Failed: DedupDataPortRequestStatus = DedupDataPortRequestStatus(5i32);
impl ::core::convert::From<i32> for DedupDataPortRequestStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DedupDataPortRequestStatus {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DedupDataPortVolumeStatus(pub i32);
pub const DedupDataPortVolumeStatus_Unknown: DedupDataPortVolumeStatus = DedupDataPortVolumeStatus(0i32);
pub const DedupDataPortVolumeStatus_NotEnabled: DedupDataPortVolumeStatus = DedupDataPortVolumeStatus(1i32);
pub const DedupDataPortVolumeStatus_NotAvailable: DedupDataPortVolumeStatus = DedupDataPortVolumeStatus(2i32);
pub const DedupDataPortVolumeStatus_Initializing: DedupDataPortVolumeStatus = DedupDataPortVolumeStatus(3i32);
pub const DedupDataPortVolumeStatus_Ready: DedupDataPortVolumeStatus = DedupDataPortVolumeStatus(4i32);
pub const DedupDataPortVolumeStatus_Maintenance: DedupDataPortVolumeStatus = DedupDataPortVolumeStatus(5i32);
pub const DedupDataPortVolumeStatus_Shutdown: DedupDataPortVolumeStatus = DedupDataPortVolumeStatus(6i32);
impl ::core::convert::From<i32> for DedupDataPortVolumeStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DedupDataPortVolumeStatus {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DedupHash {
pub Hash: [u8; 32],
}
impl DedupHash {}
impl ::core::default::Default for DedupHash {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DedupHash {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DedupHash").field("Hash", &self.Hash).finish()
}
}
impl ::core::cmp::PartialEq for DedupHash {
fn eq(&self, other: &Self) -> bool {
self.Hash == other.Hash
}
}
impl ::core::cmp::Eq for DedupHash {}
unsafe impl ::windows::core::Abi for DedupHash {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DedupHashingAlgorithm(pub i32);
pub const DedupHashingAlgorithm_Unknonwn: DedupHashingAlgorithm = DedupHashingAlgorithm(0i32);
pub const DedupHashingAlgorithm_V1: DedupHashingAlgorithm = DedupHashingAlgorithm(1i32);
impl ::core::convert::From<i32> for DedupHashingAlgorithm {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DedupHashingAlgorithm {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct DedupStream {
pub Path: super::super::Foundation::BSTR,
pub Offset: u64,
pub Length: u64,
pub ChunkCount: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl DedupStream {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for DedupStream {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for DedupStream {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DedupStream").field("Path", &self.Path).field("Offset", &self.Offset).field("Length", &self.Length).field("ChunkCount", &self.ChunkCount).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for DedupStream {
fn eq(&self, other: &Self) -> bool {
self.Path == other.Path && self.Offset == other.Offset && self.Length == other.Length && self.ChunkCount == other.ChunkCount
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for DedupStream {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for DedupStream {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct DedupStreamEntry {
pub Hash: DedupHash,
pub LogicalSize: u32,
pub Offset: u64,
}
impl DedupStreamEntry {}
impl ::core::default::Default for DedupStreamEntry {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for DedupStreamEntry {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("DedupStreamEntry").field("Hash", &self.Hash).field("LogicalSize", &self.LogicalSize).field("Offset", &self.Offset).finish()
}
}
impl ::core::cmp::PartialEq for DedupStreamEntry {
fn eq(&self, other: &Self) -> bool {
self.Hash == other.Hash && self.LogicalSize == other.LogicalSize && self.Offset == other.Offset
}
}
impl ::core::cmp::Eq for DedupStreamEntry {}
unsafe impl ::windows::core::Abi for DedupStreamEntry {
type Abi = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDedupBackupSupport(pub ::windows::core::IUnknown);
impl IDedupBackupSupport {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn RestoreFiles<'a, Param2: ::windows::core::IntoParam<'a, IDedupReadFileCallback>>(&self, numberoffiles: u32, filefullpaths: *const super::super::Foundation::BSTR, store: Param2, flags: u32, fileresults: *mut ::windows::core::HRESULT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(numberoffiles), ::core::mem::transmute(filefullpaths), store.into_param().abi(), ::core::mem::transmute(flags), ::core::mem::transmute(fileresults)).ok()
}
}
unsafe impl ::windows::core::Interface for IDedupBackupSupport {
type Vtable = IDedupBackupSupport_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc719d963_2b2d_415e_acf7_7eb7ca596ff4);
}
impl ::core::convert::From<IDedupBackupSupport> for ::windows::core::IUnknown {
fn from(value: IDedupBackupSupport) -> Self {
value.0
}
}
impl ::core::convert::From<&IDedupBackupSupport> for ::windows::core::IUnknown {
fn from(value: &IDedupBackupSupport) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDedupBackupSupport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDedupBackupSupport {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDedupBackupSupport_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, numberoffiles: u32, filefullpaths: *const ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, store: ::windows::core::RawPtr, flags: u32, fileresults: *mut ::windows::core::HRESULT) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDedupChunkLibrary(pub ::windows::core::IUnknown);
impl IDedupChunkLibrary {
pub unsafe fn InitializeForPushBuffers(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Uninitialize(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn SetParameter<'a, Param1: ::windows::core::IntoParam<'a, super::super::System::Com::VARIANT>>(&self, dwparamtype: u32, vparamvalue: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwparamtype), vparamvalue.into_param().abi()).ok()
}
pub unsafe fn StartChunking<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, iiditeratorinterfaceid: Param0) -> ::windows::core::Result<::windows::core::IUnknown> {
let mut result__: <::windows::core::IUnknown as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), iiditeratorinterfaceid.into_param().abi(), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
}
unsafe impl ::windows::core::Interface for IDedupChunkLibrary {
type Vtable = IDedupChunkLibrary_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbb5144d7_2720_4dcc_8777_78597416ec23);
}
impl ::core::convert::From<IDedupChunkLibrary> for ::windows::core::IUnknown {
fn from(value: IDedupChunkLibrary) -> Self {
value.0
}
}
impl ::core::convert::From<&IDedupChunkLibrary> for ::windows::core::IUnknown {
fn from(value: &IDedupChunkLibrary) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDedupChunkLibrary {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDedupChunkLibrary {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDedupChunkLibrary_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) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwparamtype: u32, vparamvalue: ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iiditeratorinterfaceid: ::windows::core::GUID, ppchunksenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDedupDataPort(pub ::windows::core::IUnknown);
impl IDedupDataPort {
pub unsafe fn GetStatus(&self, pstatus: *mut DedupDataPortVolumeStatus, pdataheadroommb: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pstatus), ::core::mem::transmute(pdataheadroommb)).ok()
}
pub unsafe fn LookupChunks(&self, count: u32, phashes: *const DedupHash) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(count), ::core::mem::transmute(phashes), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
pub unsafe fn InsertChunks(&self, chunkcount: u32, pchunkmetadata: *const DedupChunk, databytecount: u32, pchunkdata: *const u8) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(chunkcount), ::core::mem::transmute(pchunkmetadata), ::core::mem::transmute(databytecount), ::core::mem::transmute(pchunkdata), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
#[cfg(feature = "Win32_System_Com")]
pub unsafe fn InsertChunksWithStream<'a, Param3: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>>(&self, chunkcount: u32, pchunkmetadata: *const DedupChunk, databytecount: u32, pchunkdatastream: Param3) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(chunkcount), ::core::mem::transmute(pchunkmetadata), ::core::mem::transmute(databytecount), pchunkdatastream.into_param().abi(), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn CommitStreams(&self, streamcount: u32, pstreams: *const DedupStream, entrycount: u32, pentries: *const DedupStreamEntry) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(streamcount), ::core::mem::transmute(pstreams), ::core::mem::transmute(entrycount), ::core::mem::transmute(pentries), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
pub unsafe fn CommitStreamsWithStream<'a, Param3: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>>(&self, streamcount: u32, pstreams: *const DedupStream, entrycount: u32, pentriesstream: Param3) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(streamcount), ::core::mem::transmute(pstreams), ::core::mem::transmute(entrycount), pentriesstream.into_param().abi(), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetStreams(&self, streamcount: u32, pstreampaths: *const super::super::Foundation::BSTR) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(streamcount), ::core::mem::transmute(pstreampaths), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetStreamsResults<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, requestid: Param0, maxwaitms: u32, streamentryindex: u32, pstreamcount: *mut u32, ppstreams: *mut *mut DedupStream, pentrycount: *mut u32, ppentries: *mut *mut DedupStreamEntry, pstatus: *mut DedupDataPortRequestStatus, ppitemresults: *mut *mut ::windows::core::HRESULT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(
::core::mem::transmute_copy(self),
requestid.into_param().abi(),
::core::mem::transmute(maxwaitms),
::core::mem::transmute(streamentryindex),
::core::mem::transmute(pstreamcount),
::core::mem::transmute(ppstreams),
::core::mem::transmute(pentrycount),
::core::mem::transmute(ppentries),
::core::mem::transmute(pstatus),
::core::mem::transmute(ppitemresults),
)
.ok()
}
pub unsafe fn GetChunks(&self, count: u32, phashes: *const DedupHash) -> ::windows::core::Result<::windows::core::GUID> {
let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(count), ::core::mem::transmute(phashes), &mut result__).from_abi::<::windows::core::GUID>(result__)
}
pub unsafe fn GetChunksResults<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, requestid: Param0, maxwaitms: u32, chunkindex: u32, pchunkcount: *mut u32, ppchunkmetadata: *mut *mut DedupChunk, pdatabytecount: *mut u32, ppchunkdata: *mut *mut u8, pstatus: *mut DedupDataPortRequestStatus, ppitemresults: *mut *mut ::windows::core::HRESULT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(
::core::mem::transmute_copy(self),
requestid.into_param().abi(),
::core::mem::transmute(maxwaitms),
::core::mem::transmute(chunkindex),
::core::mem::transmute(pchunkcount),
::core::mem::transmute(ppchunkmetadata),
::core::mem::transmute(pdatabytecount),
::core::mem::transmute(ppchunkdata),
::core::mem::transmute(pstatus),
::core::mem::transmute(ppitemresults),
)
.ok()
}
pub unsafe fn GetRequestStatus<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, requestid: Param0) -> ::windows::core::Result<DedupDataPortRequestStatus> {
let mut result__: <DedupDataPortRequestStatus as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), requestid.into_param().abi(), &mut result__).from_abi::<DedupDataPortRequestStatus>(result__)
}
pub unsafe fn GetRequestResults<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, requestid: Param0, maxwaitms: u32, pbatchresult: *mut ::windows::core::HRESULT, pbatchcount: *mut u32, pstatus: *mut DedupDataPortRequestStatus, ppitemresults: *mut *mut ::windows::core::HRESULT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), requestid.into_param().abi(), ::core::mem::transmute(maxwaitms), ::core::mem::transmute(pbatchresult), ::core::mem::transmute(pbatchcount), ::core::mem::transmute(pstatus), ::core::mem::transmute(ppitemresults)).ok()
}
}
unsafe impl ::windows::core::Interface for IDedupDataPort {
type Vtable = IDedupDataPort_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7963d734_40a9_4ea3_bbf6_5a89d26f7ae8);
}
impl ::core::convert::From<IDedupDataPort> for ::windows::core::IUnknown {
fn from(value: IDedupDataPort) -> Self {
value.0
}
}
impl ::core::convert::From<&IDedupDataPort> for ::windows::core::IUnknown {
fn from(value: &IDedupDataPort) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDedupDataPort {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDedupDataPort {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDedupDataPort_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, pstatus: *mut DedupDataPortVolumeStatus, pdataheadroommb: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: u32, phashes: *const DedupHash, prequestid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, chunkcount: u32, pchunkmetadata: *const DedupChunk, databytecount: u32, pchunkdata: *const u8, prequestid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, chunkcount: u32, pchunkmetadata: *const DedupChunk, databytecount: u32, pchunkdatastream: ::windows::core::RawPtr, prequestid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, streamcount: u32, pstreams: *const ::core::mem::ManuallyDrop<DedupStream>, entrycount: u32, pentries: *const DedupStreamEntry, prequestid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, streamcount: u32, pstreams: *const ::core::mem::ManuallyDrop<DedupStream>, entrycount: u32, pentriesstream: ::windows::core::RawPtr, prequestid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, streamcount: u32, pstreampaths: *const ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, prequestid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestid: ::windows::core::GUID, maxwaitms: u32, streamentryindex: u32, pstreamcount: *mut u32, ppstreams: *mut *mut DedupStream, pentrycount: *mut u32, ppentries: *mut *mut DedupStreamEntry, pstatus: *mut DedupDataPortRequestStatus, ppitemresults: *mut *mut ::windows::core::HRESULT) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: u32, phashes: *const DedupHash, prequestid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestid: ::windows::core::GUID, maxwaitms: u32, chunkindex: u32, pchunkcount: *mut u32, ppchunkmetadata: *mut *mut DedupChunk, pdatabytecount: *mut u32, ppchunkdata: *mut *mut u8, pstatus: *mut DedupDataPortRequestStatus, ppitemresults: *mut *mut ::windows::core::HRESULT) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestid: ::windows::core::GUID, pstatus: *mut DedupDataPortRequestStatus) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, requestid: ::windows::core::GUID, maxwaitms: u32, pbatchresult: *mut ::windows::core::HRESULT, pbatchcount: *mut u32, pstatus: *mut DedupDataPortRequestStatus, ppitemresults: *mut *mut ::windows::core::HRESULT) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDedupDataPortManager(pub ::windows::core::IUnknown);
impl IDedupDataPortManager {
pub unsafe fn GetConfiguration(&self, pminchunksize: *mut u32, pmaxchunksize: *mut u32, pchunkingalgorithm: *mut DedupChunkingAlgorithm, phashingalgorithm: *mut DedupHashingAlgorithm, pcompressionalgorithm: *mut DedupCompressionAlgorithm) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pminchunksize), ::core::mem::transmute(pmaxchunksize), ::core::mem::transmute(pchunkingalgorithm), ::core::mem::transmute(phashingalgorithm), ::core::mem::transmute(pcompressionalgorithm)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetVolumeStatus<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, options: u32, path: Param1) -> ::windows::core::Result<DedupDataPortVolumeStatus> {
let mut result__: <DedupDataPortVolumeStatus as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(options), path.into_param().abi(), &mut result__).from_abi::<DedupDataPortVolumeStatus>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetVolumeDataPort<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, options: u32, path: Param1) -> ::windows::core::Result<IDedupDataPort> {
let mut result__: <IDedupDataPort as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(options), path.into_param().abi(), &mut result__).from_abi::<IDedupDataPort>(result__)
}
}
unsafe impl ::windows::core::Interface for IDedupDataPortManager {
type Vtable = IDedupDataPortManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x44677452_b90a_445e_8192_cdcfe81511fb);
}
impl ::core::convert::From<IDedupDataPortManager> for ::windows::core::IUnknown {
fn from(value: IDedupDataPortManager) -> Self {
value.0
}
}
impl ::core::convert::From<&IDedupDataPortManager> for ::windows::core::IUnknown {
fn from(value: &IDedupDataPortManager) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDedupDataPortManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDedupDataPortManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDedupDataPortManager_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, pminchunksize: *mut u32, pmaxchunksize: *mut u32, pchunkingalgorithm: *mut DedupChunkingAlgorithm, phashingalgorithm: *mut DedupHashingAlgorithm, pcompressionalgorithm: *mut DedupCompressionAlgorithm) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, options: u32, path: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pstatus: *mut DedupDataPortVolumeStatus) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, options: u32, path: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppdataport: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDedupIterateChunksHash32(pub ::windows::core::IUnknown);
impl IDedupIterateChunksHash32 {
pub unsafe fn PushBuffer(&self, pbuffer: *const u8, ulbufferlength: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbuffer), ::core::mem::transmute(ulbufferlength)).ok()
}
pub unsafe fn Next(&self, ulmaxchunks: u32, parrchunks: *mut DEDUP_CHUNK_INFO_HASH32, pulfetched: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(ulmaxchunks), ::core::mem::transmute(parrchunks), ::core::mem::transmute(pulfetched)).ok()
}
pub unsafe fn Drain(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Reset(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for IDedupIterateChunksHash32 {
type Vtable = IDedupIterateChunksHash32_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x90b584d3_72aa_400f_9767_cad866a5a2d8);
}
impl ::core::convert::From<IDedupIterateChunksHash32> for ::windows::core::IUnknown {
fn from(value: IDedupIterateChunksHash32) -> Self {
value.0
}
}
impl ::core::convert::From<&IDedupIterateChunksHash32> for ::windows::core::IUnknown {
fn from(value: &IDedupIterateChunksHash32) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDedupIterateChunksHash32 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDedupIterateChunksHash32 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDedupIterateChunksHash32_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, pbuffer: *const u8, ulbufferlength: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ulmaxchunks: u32, parrchunks: *mut DEDUP_CHUNK_INFO_HASH32, pulfetched: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDedupReadFileCallback(pub ::windows::core::IUnknown);
impl IDedupReadFileCallback {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ReadBackupFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, filefullpath: Param0, fileoffset: i64, sizetoread: u32, filebuffer: *mut u8, returnedsize: *mut u32, flags: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), filefullpath.into_param().abi(), ::core::mem::transmute(fileoffset), ::core::mem::transmute(sizetoread), ::core::mem::transmute(filebuffer), ::core::mem::transmute(returnedsize), ::core::mem::transmute(flags)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn OrderContainersRestore(&self, numberofcontainers: u32, containerpaths: *const super::super::Foundation::BSTR, readplanentries: *mut u32, readplan: *mut *mut DEDUP_CONTAINER_EXTENT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(numberofcontainers), ::core::mem::transmute(containerpaths), ::core::mem::transmute(readplanentries), ::core::mem::transmute(readplan)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PreviewContainerRead<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, filefullpath: Param0, numberofreads: u32, readoffsets: *const DDP_FILE_EXTENT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), filefullpath.into_param().abi(), ::core::mem::transmute(numberofreads), ::core::mem::transmute(readoffsets)).ok()
}
}
unsafe impl ::windows::core::Interface for IDedupReadFileCallback {
type Vtable = IDedupReadFileCallback_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7bacc67a_2f1d_42d0_897e_6ff62dd533bb);
}
impl ::core::convert::From<IDedupReadFileCallback> for ::windows::core::IUnknown {
fn from(value: IDedupReadFileCallback) -> Self {
value.0
}
}
impl ::core::convert::From<&IDedupReadFileCallback> for ::windows::core::IUnknown {
fn from(value: &IDedupReadFileCallback) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDedupReadFileCallback {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDedupReadFileCallback {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDedupReadFileCallback_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, filefullpath: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, fileoffset: i64, sizetoread: u32, filebuffer: *mut u8, returnedsize: *mut u32, flags: u32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, numberofcontainers: u32, containerpaths: *const ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, readplanentries: *mut u32, readplan: *mut *mut DEDUP_CONTAINER_EXTENT) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, filefullpath: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, numberofreads: u32, readoffsets: *const DDP_FILE_EXTENT) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
|
use crate::vm::{builtins::PyModule, PyRef, VirtualMachine};
#[cfg(feature = "ssl")]
pub(super) use _socket::{sock_select, timeout_error_msg, PySocket, SelectKind};
pub fn make_module(vm: &VirtualMachine) -> PyRef<PyModule> {
#[cfg(windows)]
crate::vm::stdlib::nt::init_winsock();
_socket::make_module(vm)
}
#[pymodule]
mod _socket {
use crate::common::lock::{PyMappedRwLockReadGuard, PyRwLock, PyRwLockReadGuard};
use crate::vm::{
builtins::{PyBaseExceptionRef, PyListRef, PyStrRef, PyTupleRef, PyTypeRef},
convert::{IntoPyException, ToPyObject, TryFromBorrowedObject, TryFromObject},
function::{ArgBytesLike, ArgMemoryBuffer, Either, FsPath, OptionalArg, OptionalOption},
types::{DefaultConstructor, Initializer, Representable},
utils::ToCString,
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
};
use crossbeam_utils::atomic::AtomicCell;
use num_traits::ToPrimitive;
use socket2::{Domain, Protocol, Socket, Type as SocketType};
use std::{
ffi,
io::{self, Read, Write},
mem::MaybeUninit,
net::{self, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs},
time::{Duration, Instant},
};
#[cfg(unix)]
use libc as c;
#[cfg(windows)]
mod c {
pub use winapi::shared::ifdef::IF_MAX_STRING_SIZE as IF_NAMESIZE;
pub use winapi::shared::mstcpip::*;
pub use winapi::shared::netioapi::{if_indextoname, if_nametoindex};
pub use winapi::shared::ws2def::*;
pub use winapi::shared::ws2ipdef::*;
pub use winapi::um::winsock2::{
IPPORT_RESERVED, SD_BOTH as SHUT_RDWR, SD_RECEIVE as SHUT_RD, SD_SEND as SHUT_WR,
SOCK_DGRAM, SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET, SOCK_STREAM, SOL_SOCKET, SO_BROADCAST,
SO_ERROR, SO_EXCLUSIVEADDRUSE, SO_LINGER, SO_OOBINLINE, SO_REUSEADDR, SO_TYPE,
SO_USELOOPBACK, *,
};
pub use winapi::um::ws2tcpip::*;
}
// constants
#[pyattr(name = "has_ipv6")]
const HAS_IPV6: bool = true;
#[pyattr]
// put IPPROTO_MAX later
use c::{
AF_INET, AF_INET6, AF_UNSPEC, INADDR_ANY, INADDR_LOOPBACK, INADDR_NONE, IPPROTO_ICMP,
IPPROTO_ICMPV6, IPPROTO_IP, IPPROTO_IP as IPPROTO_IPIP, IPPROTO_IPV6, IPPROTO_TCP,
IPPROTO_TCP as SOL_TCP, IPPROTO_UDP, MSG_CTRUNC, MSG_DONTROUTE, MSG_OOB, MSG_PEEK,
MSG_TRUNC, MSG_WAITALL, NI_DGRAM, NI_MAXHOST, NI_NAMEREQD, NI_NOFQDN, NI_NUMERICHOST,
NI_NUMERICSERV, SHUT_RD, SHUT_RDWR, SHUT_WR, SOCK_DGRAM, SOCK_STREAM, SOL_SOCKET,
SO_BROADCAST, SO_ERROR, SO_LINGER, SO_OOBINLINE, SO_REUSEADDR, SO_TYPE, TCP_NODELAY,
};
#[cfg(not(target_os = "redox"))]
#[pyattr]
use c::{
AF_DECnet, AF_APPLETALK, AF_IPX, IPPROTO_AH, IPPROTO_DSTOPTS, IPPROTO_EGP, IPPROTO_ESP,
IPPROTO_FRAGMENT, IPPROTO_HOPOPTS, IPPROTO_IDP, IPPROTO_IGMP, IPPROTO_NONE, IPPROTO_PIM,
IPPROTO_PUP, IPPROTO_RAW, IPPROTO_ROUTING,
};
#[cfg(unix)]
#[pyattr]
use c::{AF_UNIX, SO_REUSEPORT};
#[pyattr]
use c::{AI_ADDRCONFIG, AI_NUMERICHOST, AI_NUMERICSERV, AI_PASSIVE};
#[cfg(not(target_os = "redox"))]
#[pyattr]
use c::{SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET};
#[cfg(target_os = "android")]
#[pyattr]
use c::{SOL_ATALK, SOL_AX25, SOL_IPX, SOL_NETROM, SOL_ROSE};
#[cfg(target_os = "freebsd")]
#[pyattr]
use c::SO_SETFIB;
#[cfg(target_os = "linux")]
#[pyattr]
use c::{
CAN_BCM, CAN_EFF_FLAG, CAN_EFF_MASK, CAN_ERR_FLAG, CAN_ERR_MASK, CAN_ISOTP, CAN_J1939,
CAN_RAW, CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES, CAN_RAW_FILTER, CAN_RAW_JOIN_FILTERS,
CAN_RAW_LOOPBACK, CAN_RAW_RECV_OWN_MSGS, CAN_RTR_FLAG, CAN_SFF_MASK, IPPROTO_MPTCP,
J1939_IDLE_ADDR, J1939_MAX_UNICAST_ADDR, J1939_NLA_BYTES_ACKED, J1939_NLA_PAD,
J1939_NO_ADDR, J1939_NO_NAME, J1939_NO_PGN, J1939_PGN_ADDRESS_CLAIMED,
J1939_PGN_ADDRESS_COMMANDED, J1939_PGN_MAX, J1939_PGN_PDU1_MAX, J1939_PGN_REQUEST,
SCM_J1939_DEST_ADDR, SCM_J1939_DEST_NAME, SCM_J1939_ERRQUEUE, SCM_J1939_PRIO, SOL_CAN_BASE,
SOL_CAN_RAW, SO_J1939_ERRQUEUE, SO_J1939_FILTER, SO_J1939_PROMISC, SO_J1939_SEND_PRIO,
};
#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[pyattr]
use c::SOL_RDS;
#[cfg(target_os = "netbsd")]
#[pyattr]
use c::IPPROTO_VRRP;
#[cfg(target_vendor = "apple")]
#[pyattr]
use c::{AF_SYSTEM, PF_SYSTEM, SYSPROTO_CONTROL, TCP_KEEPALIVE};
#[cfg(windows)]
#[pyattr]
use c::{
IPPORT_RESERVED, IPPROTO_IPV4, RCVALL_IPLEVEL, RCVALL_OFF, RCVALL_ON,
RCVALL_SOCKETLEVELONLY, SIO_KEEPALIVE_VALS, SIO_LOOPBACK_FAST_PATH, SIO_RCVALL,
SO_EXCLUSIVEADDRUSE,
};
#[cfg(not(windows))]
#[pyattr]
const IPPORT_RESERVED: i32 = 1024;
#[pyattr]
const IPPORT_USERRESERVED: i32 = 5000;
#[cfg(any(unix, target_os = "android"))]
#[pyattr]
use c::{
EAI_SYSTEM, MSG_EOR, SO_ACCEPTCONN, SO_DEBUG, SO_DONTROUTE, SO_KEEPALIVE, SO_RCVBUF,
SO_RCVLOWAT, SO_RCVTIMEO, SO_SNDBUF, SO_SNDLOWAT, SO_SNDTIMEO,
};
#[cfg(any(target_os = "android", target_os = "linux"))]
#[pyattr]
use c::{
ALG_OP_DECRYPT, ALG_OP_ENCRYPT, ALG_SET_AEAD_ASSOCLEN, ALG_SET_AEAD_AUTHSIZE, ALG_SET_IV,
ALG_SET_KEY, ALG_SET_OP, IPV6_DSTOPTS, IPV6_NEXTHOP, IPV6_PATHMTU, IPV6_RECVDSTOPTS,
IPV6_RECVHOPLIMIT, IPV6_RECVHOPOPTS, IPV6_RECVPATHMTU, IPV6_RTHDRDSTOPTS,
IP_DEFAULT_MULTICAST_LOOP, IP_RECVOPTS, IP_RETOPTS, NETLINK_CRYPTO, NETLINK_DNRTMSG,
NETLINK_FIREWALL, NETLINK_IP6_FW, NETLINK_NFLOG, NETLINK_ROUTE, NETLINK_USERSOCK,
NETLINK_XFRM, SOL_ALG, SO_PASSSEC, SO_PEERSEC,
};
#[cfg(any(target_os = "android", target_vendor = "apple"))]
#[pyattr]
use c::{AI_DEFAULT, AI_MASK, AI_V4MAPPED_CFG};
#[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
#[pyattr]
use c::MSG_NOTIFICATION;
#[cfg(any(target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
use c::TCP_USER_TIMEOUT;
#[cfg(any(unix, target_os = "android", windows))]
#[pyattr]
use c::{
INADDR_BROADCAST, IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF, IPV6_MULTICAST_LOOP,
IPV6_UNICAST_HOPS, IPV6_V6ONLY, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_MULTICAST_IF,
IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL,
};
#[cfg(any(unix, target_os = "android", windows))]
#[pyattr]
const INADDR_UNSPEC_GROUP: u32 = 0xe0000000;
#[cfg(any(unix, target_os = "android", windows))]
#[pyattr]
const INADDR_ALLHOSTS_GROUP: u32 = 0xe0000001;
#[cfg(any(unix, target_os = "android", windows))]
#[pyattr]
const INADDR_MAX_LOCAL_GROUP: u32 = 0xe00000ff;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
use c::{
AF_ALG, AF_ASH, AF_ATMPVC, AF_ATMSVC, AF_AX25, AF_BRIDGE, AF_CAN, AF_ECONET, AF_IRDA,
AF_LLC, AF_NETBEUI, AF_NETLINK, AF_NETROM, AF_PACKET, AF_PPPOX, AF_RDS, AF_SECURITY,
AF_TIPC, AF_VSOCK, AF_WANPIPE, AF_X25, IP_TRANSPARENT, MSG_CONFIRM, MSG_ERRQUEUE,
MSG_FASTOPEN, MSG_MORE, PF_CAN, PF_PACKET, PF_RDS, SCM_CREDENTIALS, SOL_IP, SOL_TIPC,
SOL_UDP, SO_BINDTODEVICE, SO_MARK, TCP_CORK, TCP_DEFER_ACCEPT, TCP_LINGER2, TCP_QUICKACK,
TCP_SYNCNT, TCP_WINDOW_CLAMP,
};
// gated on presence of AF_VSOCK:
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
const SO_VM_SOCKETS_BUFFER_SIZE: u32 = 0;
// gated on presence of AF_VSOCK:
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
const SO_VM_SOCKETS_BUFFER_MIN_SIZE: u32 = 1;
// gated on presence of AF_VSOCK:
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
const SO_VM_SOCKETS_BUFFER_MAX_SIZE: u32 = 2;
// gated on presence of AF_VSOCK:
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
const VMADDR_CID_ANY: u32 = 0xffffffff; // 0xffffffff
// gated on presence of AF_VSOCK:
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
const VMADDR_PORT_ANY: u32 = 0xffffffff; // 0xffffffff
// gated on presence of AF_VSOCK:
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
const VMADDR_CID_HOST: u32 = 2;
// gated on presence of AF_VSOCK:
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
#[pyattr]
const VM_SOCKETS_INVALID_VERSION: u32 = 0xffffffff; // 0xffffffff
// TODO: gated on https://github.com/rust-lang/libc/pull/1662
// // gated on presence of AF_VSOCK:
// #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
// #[pyattr(name = "IOCTL_VM_SOCKETS_GET_LOCAL_CID", once)]
// fn ioctl_vm_sockets_get_local_cid(_vm: &VirtualMachine) -> i32 {
// c::_IO(7, 0xb9)
// }
#[cfg(not(any(target_os = "android", target_os = "fuchsia", target_os = "linux")))]
#[pyattr]
const SOL_IP: i32 = 0;
#[cfg(not(any(target_os = "android", target_os = "fuchsia", target_os = "linux")))]
#[pyattr]
const SOL_UDP: i32 = 17;
#[cfg(any(target_os = "android", target_os = "linux", windows))]
#[pyattr]
use c::{IPV6_HOPOPTS, IPV6_RECVRTHDR, IPV6_RTHDR, IP_OPTIONS};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_vendor = "apple"
))]
#[pyattr]
use c::{IPPROTO_HELLO, IPPROTO_XTP, LOCAL_PEERCRED, MSG_EOF};
#[cfg(any(target_os = "netbsd", target_os = "openbsd", windows))]
#[pyattr]
use c::{MSG_BCAST, MSG_MCAST};
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "freebsd",
target_os = "linux"
))]
#[pyattr]
use c::{IPPROTO_UDPLITE, TCP_CONGESTION};
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "freebsd",
target_os = "linux"
))]
#[pyattr]
const UDPLITE_SEND_CSCOV: i32 = 10;
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "freebsd",
target_os = "linux"
))]
#[pyattr]
const UDPLITE_RECV_CSCOV: i32 = 11;
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
#[pyattr]
use c::AF_KEY;
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux",
target_os = "redox"
))]
#[pyattr]
use c::SO_DOMAIN;
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
all(
target_os = "linux",
any(
target_arch = "aarch64",
target_arch = "i686",
target_arch = "loongarch64",
target_arch = "mips",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "powerpc64le",
target_arch = "riscv64gc",
target_arch = "s390x",
target_arch = "x86_64"
)
),
target_os = "redox"
))]
#[pyattr]
use c::SO_PRIORITY;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
#[pyattr]
use c::IPPROTO_MOBILE;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_vendor = "apple"
))]
#[pyattr]
use c::SCM_CREDS;
#[cfg(any(
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_vendor = "apple"
))]
#[pyattr]
use c::TCP_FASTOPEN;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
all(
target_os = "linux",
any(
target_arch = "aarch64",
target_arch = "i686",
target_arch = "loongarch64",
target_arch = "mips",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "powerpc64le",
target_arch = "riscv64gc",
target_arch = "s390x",
target_arch = "x86_64"
)
),
target_os = "redox"
))]
#[pyattr]
use c::SO_PROTOCOL;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
windows
))]
#[pyattr]
use c::IPV6_DONTFRAG;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "fuchsia",
target_os = "linux",
target_os = "redox"
))]
#[pyattr]
use c::{SO_PASSCRED, SO_PEERCRED};
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd"
))]
#[pyattr]
use c::TCP_INFO;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_vendor = "apple"
))]
#[pyattr]
use c::IP_RECVTOS;
#[cfg(any(
target_os = "android",
target_os = "netbsd",
target_os = "redox",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::NI_MAXSERV;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple"
))]
#[pyattr]
use c::{IPPROTO_EON, IPPROTO_IPCOMP};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::IPPROTO_ND;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::{IPV6_CHECKSUM, IPV6_HOPLIMIT};
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd"
))]
#[pyattr]
use c::IPPROTO_SCTP; // also in windows
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::{AI_ALL, AI_V4MAPPED};
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::EAI_NODATA;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::{
AF_LINK, IPPROTO_GGP, IPV6_JOIN_GROUP, IPV6_LEAVE_GROUP, IP_RECVDSTADDR, SO_USELOOPBACK,
};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd"
))]
#[pyattr]
use c::{MSG_CMSG_CLOEXEC, MSG_NOSIGNAL};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "redox"
))]
#[pyattr]
use c::TCP_KEEPIDLE;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_vendor = "apple"
))]
#[pyattr]
use c::{TCP_KEEPCNT, TCP_KEEPINTVL};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox"
))]
#[pyattr]
use c::{SOCK_CLOEXEC, SOCK_NONBLOCK};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple"
))]
#[pyattr]
use c::{
AF_ROUTE, AF_SNA, EAI_OVERFLOW, IPPROTO_GRE, IPPROTO_RSVP, IPPROTO_TP, IPV6_RECVPKTINFO,
MSG_DONTWAIT, SCM_RIGHTS, TCP_MAXSEG,
};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::IPV6_PKTINFO;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::AI_CANONNAME;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
windows
))]
#[pyattr]
use c::{
EAI_AGAIN, EAI_BADFLAGS, EAI_FAIL, EAI_FAMILY, EAI_MEMORY, EAI_NONAME, EAI_SERVICE,
EAI_SOCKTYPE, IPV6_RECVTCLASS, IPV6_TCLASS, IP_HDRINCL, IP_TOS, SOMAXCONN,
};
#[cfg(not(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
windows
)))]
#[pyattr]
const SOMAXCONN: i32 = 5; // Common value
// HERE IS WHERE THE BLUETOOTH CONSTANTS START
// TODO: there should be a more intelligent way of detecting bluetooth on a platform.
// CPython uses header-detection, but blocks NetBSD and DragonFly BSD
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
#[pyattr]
use c::AF_BLUETOOTH;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
#[pyattr]
const BDADDR_ANY: &str = "00:00:00:00:00:00";
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
#[pyattr]
const BDADDR_LOCAL: &str = "00:00:00:FF:FF:FF";
// HERE IS WHERE THE BLUETOOTH CONSTANTS END
#[cfg(windows)]
#[pyattr]
use winapi::shared::ws2def::{
IPPROTO_CBT, IPPROTO_ICLFXBM, IPPROTO_IGP, IPPROTO_L2TP, IPPROTO_PGM, IPPROTO_RDP,
IPPROTO_SCTP, IPPROTO_ST,
};
#[pyattr]
fn error(vm: &VirtualMachine) -> PyTypeRef {
vm.ctx.exceptions.os_error.to_owned()
}
#[pyattr]
fn timeout(vm: &VirtualMachine) -> PyTypeRef {
vm.ctx.exceptions.timeout_error.to_owned()
}
#[pyattr(once)]
fn herror(vm: &VirtualMachine) -> PyTypeRef {
vm.ctx.new_exception_type(
"socket",
"herror",
Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
)
}
#[pyattr(once)]
fn gaierror(vm: &VirtualMachine) -> PyTypeRef {
vm.ctx.new_exception_type(
"socket",
"gaierror",
Some(vec![vm.ctx.exceptions.os_error.to_owned()]),
)
}
#[pyfunction]
fn htonl(x: u32) -> u32 {
u32::to_be(x)
}
#[pyfunction]
fn htons(x: u16) -> u16 {
u16::to_be(x)
}
#[pyfunction]
fn ntohl(x: u32) -> u32 {
u32::from_be(x)
}
#[pyfunction]
fn ntohs(x: u16) -> u16 {
u16::from_be(x)
}
#[cfg(unix)]
type RawSocket = std::os::unix::io::RawFd;
#[cfg(windows)]
type RawSocket = std::os::windows::raw::SOCKET;
#[cfg(unix)]
macro_rules! errcode {
($e:ident) => {
c::$e
};
}
#[cfg(windows)]
macro_rules! errcode {
($e:ident) => {
paste::paste!(c::[<WSA $e>])
};
}
#[cfg(windows)]
use winapi::shared::netioapi;
fn get_raw_sock(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<RawSocket> {
#[cfg(unix)]
type CastFrom = libc::c_long;
#[cfg(windows)]
type CastFrom = libc::c_longlong;
// should really just be to_index() but test_socket tests the error messages explicitly
if obj.fast_isinstance(vm.ctx.types.float_type) {
return Err(vm.new_type_error("integer argument expected, got float".to_owned()));
}
let int = obj
.try_index_opt(vm)
.unwrap_or_else(|| Err(vm.new_type_error("an integer is required".to_owned())))?;
int.try_to_primitive::<CastFrom>(vm)
.map(|sock| sock as RawSocket)
}
#[pyattr(name = "socket")]
#[pyattr(name = "SocketType")]
#[pyclass(name = "socket")]
#[derive(Debug, PyPayload)]
pub struct PySocket {
kind: AtomicCell<i32>,
family: AtomicCell<i32>,
proto: AtomicCell<i32>,
pub(crate) timeout: AtomicCell<f64>,
sock: PyRwLock<Option<Socket>>,
}
const _: () = assert!(std::mem::size_of::<Option<Socket>>() == std::mem::size_of::<Socket>());
impl Default for PySocket {
fn default() -> Self {
PySocket {
kind: AtomicCell::default(),
family: AtomicCell::default(),
proto: AtomicCell::default(),
timeout: AtomicCell::new(-1.0),
sock: PyRwLock::new(None),
}
}
}
#[cfg(windows)]
const CLOSED_ERR: i32 = c::WSAENOTSOCK;
#[cfg(unix)]
const CLOSED_ERR: i32 = c::EBADF;
impl Read for &PySocket {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
(&mut &*self.sock()?).read(buf)
}
}
impl Write for &PySocket {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
(&mut &*self.sock()?).write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
(&mut &*self.sock()?).flush()
}
}
impl PySocket {
pub fn sock_opt(&self) -> Option<PyMappedRwLockReadGuard<'_, Socket>> {
PyRwLockReadGuard::try_map(self.sock.read(), |sock| sock.as_ref()).ok()
}
pub fn sock(&self) -> io::Result<PyMappedRwLockReadGuard<'_, Socket>> {
self.sock_opt()
.ok_or_else(|| io::Error::from_raw_os_error(CLOSED_ERR))
}
fn init_inner(
&self,
family: i32,
socket_kind: i32,
proto: i32,
sock: Socket,
) -> io::Result<()> {
self.family.store(family);
self.kind.store(socket_kind);
self.proto.store(proto);
let mut s = self.sock.write();
let sock = s.insert(sock);
let timeout = DEFAULT_TIMEOUT.load();
self.timeout.store(timeout);
if timeout >= 0.0 {
sock.set_nonblocking(true)?;
}
Ok(())
}
/// returns Err(blocking)
pub fn get_timeout(&self) -> Result<Duration, bool> {
let timeout = self.timeout.load();
if timeout > 0.0 {
Ok(Duration::from_secs_f64(timeout))
} else {
Err(timeout != 0.0)
}
}
fn sock_op<F, R>(
&self,
vm: &VirtualMachine,
select: SelectKind,
f: F,
) -> Result<R, IoOrPyException>
where
F: FnMut() -> io::Result<R>,
{
self.sock_op_timeout_err(vm, select, self.get_timeout().ok(), f)
}
fn sock_op_timeout_err<F, R>(
&self,
vm: &VirtualMachine,
select: SelectKind,
timeout: Option<Duration>,
mut f: F,
) -> Result<R, IoOrPyException>
where
F: FnMut() -> io::Result<R>,
{
let deadline = timeout.map(Deadline::new);
loop {
if deadline.is_some() || matches!(select, SelectKind::Connect) {
let interval = deadline.as_ref().map(|d| d.time_until()).transpose()?;
let res = sock_select(&*self.sock()?, select, interval);
match res {
Ok(true) => return Err(IoOrPyException::Timeout),
Err(e) if e.kind() == io::ErrorKind::Interrupted => {
vm.check_signals()?;
continue;
}
Err(e) => return Err(e.into()),
Ok(false) => {} // no timeout, continue as normal
}
}
let err = loop {
// loop on interrupt
match f() {
Ok(x) => return Ok(x),
Err(e) if e.kind() == io::ErrorKind::Interrupted => vm.check_signals()?,
Err(e) => break e,
}
};
if timeout.is_some() && err.kind() == io::ErrorKind::WouldBlock {
continue;
}
return Err(err.into());
}
}
fn extract_address(
&self,
addr: PyObjectRef,
caller: &str,
vm: &VirtualMachine,
) -> Result<socket2::SockAddr, IoOrPyException> {
let family = self.family.load();
match family {
#[cfg(unix)]
c::AF_UNIX => {
use std::os::unix::ffi::OsStrExt;
let buf = crate::vm::function::ArgStrOrBytesLike::try_from_object(vm, addr)?;
let path = &*buf.borrow_bytes();
socket2::SockAddr::unix(ffi::OsStr::from_bytes(path))
.map_err(|_| vm.new_os_error("AF_UNIX path too long".to_owned()).into())
}
c::AF_INET => {
let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
vm.new_type_error(format!(
"{}(): AF_INET address must be tuple, not {}",
caller,
obj.class().name()
))
})?;
if tuple.len() != 2 {
return Err(vm
.new_type_error(
"AF_INET address must be a pair (host, post)".to_owned(),
)
.into());
}
let addr = Address::from_tuple(&tuple, vm)?;
let mut addr4 = get_addr(vm, addr.host, c::AF_INET)?;
match &mut addr4 {
SocketAddr::V4(addr4) => {
addr4.set_port(addr.port);
}
SocketAddr::V6(_) => unreachable!(),
}
Ok(addr4.into())
}
c::AF_INET6 => {
let tuple: PyTupleRef = addr.downcast().map_err(|obj| {
vm.new_type_error(format!(
"{}(): AF_INET6 address must be tuple, not {}",
caller,
obj.class().name()
))
})?;
match tuple.len() {
2..=4 => {}
_ => return Err(vm.new_type_error(
"AF_INET6 address must be a tuple (host, port[, flowinfo[, scopeid]])"
.to_owned(),
).into()),
}
let (addr, flowinfo, scopeid) = Address::from_tuple_ipv6(&tuple, vm)?;
let mut addr6 = get_addr(vm, addr.host, c::AF_INET6)?;
match &mut addr6 {
SocketAddr::V6(addr6) => {
addr6.set_port(addr.port);
addr6.set_flowinfo(flowinfo);
addr6.set_scope_id(scopeid);
}
SocketAddr::V4(_) => unreachable!(),
}
Ok(addr6.into())
}
_ => Err(vm.new_os_error(format!("{caller}(): bad family")).into()),
}
}
fn connect_inner(
&self,
address: PyObjectRef,
caller: &str,
vm: &VirtualMachine,
) -> Result<(), IoOrPyException> {
let sock_addr = self.extract_address(address, caller, vm)?;
let err = match self.sock()?.connect(&sock_addr) {
Ok(()) => return Ok(()),
Err(e) => e,
};
let wait_connect = if err.kind() == io::ErrorKind::Interrupted {
vm.check_signals()?;
self.timeout.load() != 0.0
} else {
#[cfg(unix)]
use c::EINPROGRESS;
#[cfg(windows)]
use c::WSAEWOULDBLOCK as EINPROGRESS;
self.timeout.load() > 0.0 && err.raw_os_error() == Some(EINPROGRESS)
};
if wait_connect {
// basically, connect() is async, and it registers an "error" on the socket when it's
// done connecting. SelectKind::Connect fills the errorfds fd_set, so if we wake up
// from poll and the error is EISCONN then we know that the connect is done
self.sock_op(vm, SelectKind::Connect, || {
let sock = self.sock()?;
let err = sock.take_error()?;
match err {
Some(e) if e.raw_os_error() == Some(libc::EISCONN) => Ok(()),
Some(e) => Err(e),
// TODO: is this accurate?
None => Ok(()),
}
})
} else {
Err(err.into())
}
}
}
impl DefaultConstructor for PySocket {}
impl Initializer for PySocket {
type Args = (
OptionalArg<i32>,
OptionalArg<i32>,
OptionalArg<i32>,
OptionalOption<PyObjectRef>,
);
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
Self::_init(zelf, args, vm).map_err(|e| e.into_pyexception(vm))
}
}
impl Representable for PySocket {
#[inline]
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!(
"<socket object, fd={}, family={}, type={}, proto={}>",
// cast because INVALID_SOCKET is unsigned, so would show usize::MAX instead of -1
zelf.fileno() as i64,
zelf.family.load(),
zelf.kind.load(),
zelf.proto.load(),
))
}
}
#[pyclass(with(DefaultConstructor, Initializer, Representable), flags(BASETYPE))]
impl PySocket {
fn _init(
zelf: PyRef<Self>,
(family, socket_kind, proto, fileno): <Self as Initializer>::Args,
vm: &VirtualMachine,
) -> Result<(), IoOrPyException> {
let mut family = family.unwrap_or(-1);
let mut socket_kind = socket_kind.unwrap_or(-1);
let mut proto = proto.unwrap_or(-1);
let fileno = fileno
.flatten()
.map(|obj| get_raw_sock(obj, vm))
.transpose()?;
let sock;
if let Some(fileno) = fileno {
sock = sock_from_raw(fileno, vm)?;
match sock.local_addr() {
Ok(addr) if family == -1 => family = addr.family() as i32,
Err(e)
if family == -1
|| matches!(
e.raw_os_error(),
Some(errcode!(ENOTSOCK)) | Some(errcode!(EBADF))
) =>
{
std::mem::forget(sock);
return Err(e.into());
}
_ => {}
}
if socket_kind == -1 {
socket_kind = sock.r#type().map_err(|e| e.into_pyexception(vm))?.into();
}
cfg_if::cfg_if! {
if #[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
))] {
if proto == -1 {
proto = sock.protocol()?.map_or(0, Into::into);
}
} else {
proto = 0;
}
}
} else {
if family == -1 {
family = c::AF_INET as _
}
if socket_kind == -1 {
socket_kind = c::SOCK_STREAM
}
if proto == -1 {
proto = 0
}
sock = Socket::new(
Domain::from(family),
SocketType::from(socket_kind),
Some(Protocol::from(proto)),
)?;
};
Ok(zelf.init_inner(family, socket_kind, proto, sock)?)
}
#[pymethod]
fn connect(
&self,
address: PyObjectRef,
vm: &VirtualMachine,
) -> Result<(), IoOrPyException> {
self.connect_inner(address, "connect", vm)
}
#[pymethod]
fn connect_ex(&self, address: PyObjectRef, vm: &VirtualMachine) -> PyResult<i32> {
match self.connect_inner(address, "connect_ex", vm) {
Ok(()) => Ok(0),
Err(err) => err.errno(),
}
}
#[pymethod]
fn bind(&self, address: PyObjectRef, vm: &VirtualMachine) -> Result<(), IoOrPyException> {
let sock_addr = self.extract_address(address, "bind", vm)?;
Ok(self.sock()?.bind(&sock_addr)?)
}
#[pymethod]
fn listen(&self, backlog: OptionalArg<i32>) -> io::Result<()> {
let backlog = backlog.unwrap_or(128);
let backlog = if backlog < 0 { 0 } else { backlog };
self.sock()?.listen(backlog)
}
#[pymethod]
fn _accept(
&self,
vm: &VirtualMachine,
) -> Result<(RawSocket, PyObjectRef), IoOrPyException> {
let (sock, addr) = self.sock_op(vm, SelectKind::Read, || self.sock()?.accept())?;
let fd = into_sock_fileno(sock);
Ok((fd, get_addr_tuple(&addr, vm)))
}
#[pymethod]
fn recv(
&self,
bufsize: usize,
flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> Result<Vec<u8>, IoOrPyException> {
let flags = flags.unwrap_or(0);
let mut buffer = Vec::with_capacity(bufsize);
let sock = self.sock()?;
let n = self.sock_op(vm, SelectKind::Read, || {
sock.recv_with_flags(buffer.spare_capacity_mut(), flags)
})?;
unsafe { buffer.set_len(n) };
Ok(buffer)
}
#[pymethod]
fn recv_into(
&self,
buf: ArgMemoryBuffer,
flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> Result<usize, IoOrPyException> {
let flags = flags.unwrap_or(0);
let sock = self.sock()?;
let mut buf = buf.borrow_buf_mut();
let buf = &mut *buf;
self.sock_op(vm, SelectKind::Read, || {
sock.recv_with_flags(slice_as_uninit(buf), flags)
})
}
#[pymethod]
fn recvfrom(
&self,
bufsize: isize,
flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> Result<(Vec<u8>, PyObjectRef), IoOrPyException> {
let flags = flags.unwrap_or(0);
let bufsize = bufsize
.to_usize()
.ok_or_else(|| vm.new_value_error("negative buffersize in recvfrom".to_owned()))?;
let mut buffer = Vec::with_capacity(bufsize);
let (n, addr) = self.sock_op(vm, SelectKind::Read, || {
self.sock()?
.recv_from_with_flags(buffer.spare_capacity_mut(), flags)
})?;
unsafe { buffer.set_len(n) };
Ok((buffer, get_addr_tuple(&addr, vm)))
}
#[pymethod]
fn recvfrom_into(
&self,
buf: ArgMemoryBuffer,
nbytes: OptionalArg<isize>,
flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> Result<(usize, PyObjectRef), IoOrPyException> {
let mut buf = buf.borrow_buf_mut();
let buf = &mut *buf;
let buf = match nbytes {
OptionalArg::Present(i) => {
let i = i.to_usize().ok_or_else(|| {
vm.new_value_error("negative buffersize in recvfrom_into".to_owned())
})?;
buf.get_mut(..i).ok_or_else(|| {
vm.new_value_error(
"nbytes is greater than the length of the buffer".to_owned(),
)
})?
}
OptionalArg::Missing => buf,
};
let flags = flags.unwrap_or(0);
let sock = self.sock()?;
let (n, addr) = self.sock_op(vm, SelectKind::Read, || {
sock.recv_from_with_flags(slice_as_uninit(buf), flags)
})?;
Ok((n, get_addr_tuple(&addr, vm)))
}
#[pymethod]
fn send(
&self,
bytes: ArgBytesLike,
flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> Result<usize, IoOrPyException> {
let flags = flags.unwrap_or(0);
let buf = bytes.borrow_buf();
let buf = &*buf;
self.sock_op(vm, SelectKind::Write, || {
self.sock()?.send_with_flags(buf, flags)
})
}
#[pymethod]
fn sendall(
&self,
bytes: ArgBytesLike,
flags: OptionalArg<i32>,
vm: &VirtualMachine,
) -> Result<(), IoOrPyException> {
let flags = flags.unwrap_or(0);
let timeout = self.get_timeout().ok();
let deadline = timeout.map(Deadline::new);
let buf = bytes.borrow_buf();
let buf = &*buf;
let mut buf_offset = 0;
// now we have like 3 layers of interrupt loop :)
while buf_offset < buf.len() {
let interval = deadline.as_ref().map(|d| d.time_until()).transpose()?;
self.sock_op_timeout_err(vm, SelectKind::Write, interval, || {
let subbuf = &buf[buf_offset..];
buf_offset += self.sock()?.send_with_flags(subbuf, flags)?;
Ok(())
})?;
vm.check_signals()?;
}
Ok(())
}
#[pymethod]
fn sendto(
&self,
bytes: ArgBytesLike,
arg2: PyObjectRef,
arg3: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> Result<usize, IoOrPyException> {
// signature is bytes[, flags], address
let (flags, address) = match arg3 {
OptionalArg::Present(arg3) => {
// should just be i32::try_from_obj but tests check for error message
let int = arg2.try_index_opt(vm).unwrap_or_else(|| {
Err(vm.new_type_error("an integer is required".to_owned()))
})?;
let flags = int.try_to_primitive::<i32>(vm)?;
(flags, arg3)
}
OptionalArg::Missing => (0, arg2),
};
let addr = self.extract_address(address, "sendto", vm)?;
let buf = bytes.borrow_buf();
let buf = &*buf;
self.sock_op(vm, SelectKind::Write, || {
self.sock()?.send_to_with_flags(buf, &addr, flags)
})
}
#[pymethod]
fn close(&self) -> io::Result<()> {
let sock = self.detach();
if sock != INVALID_SOCKET {
close_inner(sock)?;
}
Ok(())
}
#[pymethod]
#[inline]
fn detach(&self) -> RawSocket {
let sock = self.sock.write().take();
sock.map_or(INVALID_SOCKET, into_sock_fileno)
}
#[pymethod]
fn fileno(&self) -> RawSocket {
self.sock
.read()
.as_ref()
.map_or(INVALID_SOCKET, sock_fileno)
}
#[pymethod]
fn getsockname(&self, vm: &VirtualMachine) -> std::io::Result<PyObjectRef> {
let addr = self.sock()?.local_addr()?;
Ok(get_addr_tuple(&addr, vm))
}
#[pymethod]
fn getpeername(&self, vm: &VirtualMachine) -> std::io::Result<PyObjectRef> {
let addr = self.sock()?.peer_addr()?;
Ok(get_addr_tuple(&addr, vm))
}
#[pymethod]
fn gettimeout(&self) -> Option<f64> {
let timeout = self.timeout.load();
if timeout >= 0.0 {
Some(timeout)
} else {
None
}
}
#[pymethod]
fn setblocking(&self, block: bool) -> io::Result<()> {
self.timeout.store(if block { -1.0 } else { 0.0 });
self.sock()?.set_nonblocking(!block)
}
#[pymethod]
fn getblocking(&self) -> bool {
self.timeout.load() != 0.0
}
#[pymethod]
fn settimeout(&self, timeout: Option<Duration>) -> io::Result<()> {
self.timeout
.store(timeout.map_or(-1.0, |d| d.as_secs_f64()));
// even if timeout is > 0 the socket needs to be nonblocking in order for us to select() on
// it
self.sock()?.set_nonblocking(timeout.is_some())
}
#[pymethod]
fn getsockopt(
&self,
level: i32,
name: i32,
buflen: OptionalArg<i32>,
vm: &VirtualMachine,
) -> Result<PyObjectRef, IoOrPyException> {
let sock = self.sock()?;
let fd = sock_fileno(&sock);
let buflen = buflen.unwrap_or(0);
if buflen == 0 {
let mut flag: libc::c_int = 0;
let mut flagsize = std::mem::size_of::<libc::c_int>() as _;
let ret = unsafe {
c::getsockopt(
fd as _,
level,
name,
&mut flag as *mut libc::c_int as *mut _,
&mut flagsize,
)
};
if ret < 0 {
return Err(crate::common::os::errno().into());
}
Ok(vm.ctx.new_int(flag).into())
} else {
if buflen <= 0 || buflen > 1024 {
return Err(vm
.new_os_error("getsockopt buflen out of range".to_owned())
.into());
}
let mut buf = vec![0u8; buflen as usize];
let mut buflen = buflen as _;
let ret = unsafe {
c::getsockopt(
fd as _,
level,
name,
buf.as_mut_ptr() as *mut _,
&mut buflen,
)
};
if ret < 0 {
return Err(crate::common::os::errno().into());
}
buf.truncate(buflen as usize);
Ok(vm.ctx.new_bytes(buf).into())
}
}
#[pymethod]
fn setsockopt(
&self,
level: i32,
name: i32,
value: Option<Either<ArgBytesLike, i32>>,
optlen: OptionalArg<u32>,
vm: &VirtualMachine,
) -> Result<(), IoOrPyException> {
let sock = self.sock()?;
let fd = sock_fileno(&sock);
let ret = match (value, optlen) {
(Some(Either::A(b)), OptionalArg::Missing) => b.with_ref(|b| unsafe {
c::setsockopt(fd as _, level, name, b.as_ptr() as *const _, b.len() as _)
}),
(Some(Either::B(ref val)), OptionalArg::Missing) => unsafe {
c::setsockopt(
fd as _,
level,
name,
val as *const i32 as *const _,
std::mem::size_of::<i32>() as _,
)
},
(None, OptionalArg::Present(optlen)) => unsafe {
c::setsockopt(fd as _, level, name, std::ptr::null(), optlen as _)
},
_ => {
return Err(vm
.new_type_error("expected the value arg xor the optlen arg".to_owned())
.into());
}
};
if ret < 0 {
Err(crate::common::os::errno().into())
} else {
Ok(())
}
}
#[pymethod]
fn shutdown(&self, how: i32, vm: &VirtualMachine) -> Result<(), IoOrPyException> {
let how = match how {
c::SHUT_RD => Shutdown::Read,
c::SHUT_WR => Shutdown::Write,
c::SHUT_RDWR => Shutdown::Both,
_ => {
return Err(vm
.new_value_error("`how` must be SHUT_RD, SHUT_WR, or SHUT_RDWR".to_owned())
.into())
}
};
Ok(self.sock()?.shutdown(how)?)
}
#[pygetset(name = "type")]
fn kind(&self) -> i32 {
self.kind.load()
}
#[pygetset]
fn family(&self) -> i32 {
self.family.load()
}
#[pygetset]
fn proto(&self) -> i32 {
self.proto.load()
}
}
struct Address {
host: PyStrRef,
port: u16,
}
impl ToSocketAddrs for Address {
type Iter = std::vec::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
(self.host.as_str(), self.port).to_socket_addrs()
}
}
impl TryFromObject for Address {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
let tuple = PyTupleRef::try_from_object(vm, obj)?;
if tuple.len() != 2 {
Err(vm.new_type_error("Address tuple should have only 2 values".to_owned()))
} else {
Self::from_tuple(&tuple, vm)
}
}
}
impl Address {
fn from_tuple(tuple: &[PyObjectRef], vm: &VirtualMachine) -> PyResult<Self> {
let host = PyStrRef::try_from_object(vm, tuple[0].clone())?;
let port = i32::try_from_borrowed_object(vm, &tuple[1])?;
let port = port
.to_u16()
.ok_or_else(|| vm.new_overflow_error("port must be 0-65535.".to_owned()))?;
Ok(Address { host, port })
}
fn from_tuple_ipv6(
tuple: &[PyObjectRef],
vm: &VirtualMachine,
) -> PyResult<(Self, u32, u32)> {
let addr = Address::from_tuple(tuple, vm)?;
let flowinfo = tuple
.get(2)
.map(|obj| u32::try_from_borrowed_object(vm, obj))
.transpose()?
.unwrap_or(0);
let scopeid = tuple
.get(3)
.map(|obj| u32::try_from_borrowed_object(vm, obj))
.transpose()?
.unwrap_or(0);
if flowinfo > 0xfffff {
return Err(vm.new_overflow_error("flowinfo must be 0-1048575.".to_owned()));
}
Ok((addr, flowinfo, scopeid))
}
}
fn get_ip_addr_tuple(addr: &SocketAddr, vm: &VirtualMachine) -> PyObjectRef {
match addr {
SocketAddr::V4(addr) => (addr.ip().to_string(), addr.port()).to_pyobject(vm),
SocketAddr::V6(addr) => (
addr.ip().to_string(),
addr.port(),
addr.flowinfo(),
addr.scope_id(),
)
.to_pyobject(vm),
}
}
fn get_addr_tuple(addr: &socket2::SockAddr, vm: &VirtualMachine) -> PyObjectRef {
if let Some(addr) = addr.as_socket() {
return get_ip_addr_tuple(&addr, vm);
}
#[cfg(unix)]
use nix::sys::socket::{SockaddrLike, UnixAddr};
#[cfg(unix)]
if let Some(unix_addr) = unsafe { UnixAddr::from_raw(addr.as_ptr(), Some(addr.len())) } {
use std::os::unix::ffi::OsStrExt;
#[cfg(any(target_os = "android", target_os = "linux"))]
if let Some(abstractpath) = unix_addr.as_abstract() {
return vm.ctx.new_bytes([b"\0", abstractpath].concat()).into();
}
// necessary on macos
let path = ffi::OsStr::as_bytes(unix_addr.path().unwrap_or("".as_ref()).as_ref());
let nul_pos = memchr::memchr(b'\0', path).unwrap_or(path.len());
let path = ffi::OsStr::from_bytes(&path[..nul_pos]);
return vm.ctx.new_str(path.to_string_lossy()).into();
}
// TODO: support more address families
(String::new(), 0).to_pyobject(vm)
}
#[pyfunction]
fn gethostname(vm: &VirtualMachine) -> PyResult<PyStrRef> {
gethostname::gethostname()
.into_string()
.map(|hostname| vm.ctx.new_str(hostname))
.map_err(|err| vm.new_os_error(err.into_string().unwrap()))
}
#[cfg(all(unix, not(target_os = "redox")))]
#[pyfunction]
fn sethostname(hostname: PyStrRef) -> nix::Result<()> {
nix::unistd::sethostname(hostname.as_str())
}
#[pyfunction]
fn inet_aton(ip_string: PyStrRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
ip_string
.as_str()
.parse::<Ipv4Addr>()
.map(|ip_addr| Vec::<u8>::from(ip_addr.octets()))
.map_err(|_| {
vm.new_os_error("illegal IP address string passed to inet_aton".to_owned())
})
}
#[pyfunction]
fn inet_ntoa(packed_ip: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let packed_ip = packed_ip.borrow_buf();
let packed_ip = <&[u8; 4]>::try_from(&*packed_ip)
.map_err(|_| vm.new_os_error("packed IP wrong length for inet_ntoa".to_owned()))?;
Ok(vm.ctx.new_str(Ipv4Addr::from(*packed_ip).to_string()))
}
fn cstr_opt_as_ptr(x: &OptionalArg<ffi::CString>) -> *const libc::c_char {
x.as_ref().map_or_else(std::ptr::null, |s| s.as_ptr())
}
#[pyfunction]
fn getservbyname(
servicename: PyStrRef,
protocolname: OptionalArg<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<u16> {
let cstr_name = servicename.to_cstring(vm)?;
let cstr_proto = protocolname
.as_ref()
.map(|s| s.to_cstring(vm))
.transpose()?;
let cstr_proto = cstr_opt_as_ptr(&cstr_proto);
let serv = unsafe { c::getservbyname(cstr_name.as_ptr(), cstr_proto) };
if serv.is_null() {
return Err(vm.new_os_error("service/proto not found".to_owned()));
}
let port = unsafe { (*serv).s_port };
Ok(u16::from_be(port as u16))
}
#[pyfunction]
fn getservbyport(
port: i32,
protocolname: OptionalArg<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<String> {
let port = port.to_u16().ok_or_else(|| {
vm.new_overflow_error("getservbyport: port must be 0-65535.".to_owned())
})?;
let cstr_proto = protocolname
.as_ref()
.map(|s| s.to_cstring(vm))
.transpose()?;
let cstr_proto = cstr_opt_as_ptr(&cstr_proto);
let serv = unsafe { c::getservbyport(port.to_be() as _, cstr_proto) };
if serv.is_null() {
return Err(vm.new_os_error("port/proto not found".to_owned()));
}
let s = unsafe { ffi::CStr::from_ptr((*serv).s_name) };
Ok(s.to_string_lossy().into_owned())
}
fn slice_as_uninit<T>(v: &mut [T]) -> &mut [MaybeUninit<T>] {
unsafe { &mut *(v as *mut [T] as *mut [MaybeUninit<T>]) }
}
enum IoOrPyException {
Timeout,
Py(PyBaseExceptionRef),
Io(io::Error),
}
impl From<PyBaseExceptionRef> for IoOrPyException {
fn from(exc: PyBaseExceptionRef) -> Self {
Self::Py(exc)
}
}
impl From<io::Error> for IoOrPyException {
fn from(err: io::Error) -> Self {
Self::Io(err)
}
}
impl IoOrPyException {
fn errno(self) -> PyResult<i32> {
match self {
Self::Timeout => Ok(errcode!(EWOULDBLOCK)),
Self::Io(err) => {
// TODO: just unwrap()?
Ok(err.raw_os_error().unwrap_or(1))
}
Self::Py(exc) => Err(exc),
}
}
}
impl IntoPyException for IoOrPyException {
#[inline]
fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef {
match self {
Self::Timeout => timeout_error(vm),
Self::Py(exc) => exc,
Self::Io(err) => err.into_pyexception(vm),
}
}
}
#[derive(Copy, Clone)]
pub(crate) enum SelectKind {
Read,
Write,
Connect,
}
/// returns true if timed out
pub(crate) fn sock_select(
sock: &Socket,
kind: SelectKind,
interval: Option<Duration>,
) -> io::Result<bool> {
let fd = sock_fileno(sock);
#[cfg(unix)]
{
use nix::poll::*;
let events = match kind {
SelectKind::Read => PollFlags::POLLIN,
SelectKind::Write => PollFlags::POLLOUT,
SelectKind::Connect => PollFlags::POLLOUT | PollFlags::POLLERR,
};
let mut pollfd = [PollFd::new(fd, events)];
let timeout = match interval {
Some(d) => d.as_millis() as _,
None => -1,
};
let ret = poll(&mut pollfd, timeout)?;
Ok(ret == 0)
}
#[cfg(windows)]
{
use crate::select;
let mut reads = select::FdSet::new();
let mut writes = select::FdSet::new();
let mut errs = select::FdSet::new();
let fd = fd as usize;
match kind {
SelectKind::Read => reads.insert(fd),
SelectKind::Write => writes.insert(fd),
SelectKind::Connect => {
writes.insert(fd);
errs.insert(fd);
}
}
let mut interval = interval.map(|dur| select::timeval {
tv_sec: dur.as_secs() as _,
tv_usec: dur.subsec_micros() as _,
});
select::select(
fd as i32 + 1,
&mut reads,
&mut writes,
&mut errs,
interval.as_mut(),
)
.map(|ret| ret == 0)
}
}
#[derive(FromArgs)]
struct GAIOptions {
#[pyarg(positional)]
host: Option<PyStrRef>,
#[pyarg(positional)]
port: Option<Either<PyStrRef, i32>>,
#[pyarg(positional, default = "c::AF_UNSPEC")]
family: i32,
#[pyarg(positional, default = "0")]
ty: i32,
#[pyarg(positional, default = "0")]
proto: i32,
#[pyarg(positional, default = "0")]
flags: i32,
}
#[pyfunction]
fn getaddrinfo(
opts: GAIOptions,
vm: &VirtualMachine,
) -> Result<Vec<PyObjectRef>, IoOrPyException> {
let hints = dns_lookup::AddrInfoHints {
socktype: opts.ty,
protocol: opts.proto,
address: opts.family,
flags: opts.flags,
};
let host = opts.host.as_ref().map(|s| s.as_str());
let port = opts.port.as_ref().map(|p| -> std::borrow::Cow<str> {
match p {
Either::A(ref s) => s.as_str().into(),
Either::B(i) => i.to_string().into(),
}
});
let port = port.as_ref().map(|p| p.as_ref());
let addrs = dns_lookup::getaddrinfo(host, port, Some(hints))
.map_err(|err| convert_socket_error(vm, err, SocketError::GaiError))?;
let list = addrs
.map(|ai| {
ai.map(|ai| {
vm.new_tuple((
ai.address,
ai.socktype,
ai.protocol,
ai.canonname,
get_ip_addr_tuple(&ai.sockaddr, vm),
))
.into()
})
})
.collect::<io::Result<Vec<_>>>()?;
Ok(list)
}
#[pyfunction]
fn gethostbyaddr(
addr: PyStrRef,
vm: &VirtualMachine,
) -> Result<(String, PyListRef, PyListRef), IoOrPyException> {
let addr = get_addr(vm, addr, c::AF_UNSPEC)?;
let (hostname, _) = dns_lookup::getnameinfo(&addr, 0)
.map_err(|e| convert_socket_error(vm, e, SocketError::HError))?;
Ok((
hostname,
vm.ctx.new_list(vec![]),
vm.ctx
.new_list(vec![vm.ctx.new_str(addr.ip().to_string()).into()]),
))
}
#[pyfunction]
fn gethostbyname(name: PyStrRef, vm: &VirtualMachine) -> Result<String, IoOrPyException> {
let addr = get_addr(vm, name, c::AF_INET)?;
match addr {
SocketAddr::V4(ip) => Ok(ip.ip().to_string()),
_ => unreachable!(),
}
}
#[pyfunction]
fn gethostbyname_ex(
name: PyStrRef,
vm: &VirtualMachine,
) -> Result<(String, PyListRef, PyListRef), IoOrPyException> {
let addr = get_addr(vm, name, c::AF_INET)?;
let (hostname, _) = dns_lookup::getnameinfo(&addr, 0)
.map_err(|e| convert_socket_error(vm, e, SocketError::HError))?;
Ok((
hostname,
vm.ctx.new_list(vec![]),
vm.ctx
.new_list(vec![vm.ctx.new_str(addr.ip().to_string()).into()]),
))
}
#[pyfunction]
fn inet_pton(af_inet: i32, ip_string: PyStrRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
static ERROR_MSG: &str = "illegal IP address string passed to inet_pton";
let ip_addr = match af_inet {
c::AF_INET => ip_string
.as_str()
.parse::<Ipv4Addr>()
.map_err(|_| vm.new_os_error(ERROR_MSG.to_owned()))?
.octets()
.to_vec(),
c::AF_INET6 => ip_string
.as_str()
.parse::<Ipv6Addr>()
.map_err(|_| vm.new_os_error(ERROR_MSG.to_owned()))?
.octets()
.to_vec(),
_ => return Err(vm.new_os_error("Address family not supported by protocol".to_owned())),
};
Ok(ip_addr)
}
#[pyfunction]
fn inet_ntop(af_inet: i32, packed_ip: ArgBytesLike, vm: &VirtualMachine) -> PyResult<String> {
let packed_ip = packed_ip.borrow_buf();
match af_inet {
c::AF_INET => {
let packed_ip = <&[u8; 4]>::try_from(&*packed_ip).map_err(|_| {
vm.new_value_error("invalid length of packed IP address string".to_owned())
})?;
Ok(Ipv4Addr::from(*packed_ip).to_string())
}
c::AF_INET6 => {
let packed_ip = <&[u8; 16]>::try_from(&*packed_ip).map_err(|_| {
vm.new_value_error("invalid length of packed IP address string".to_owned())
})?;
Ok(get_ipv6_addr_str(Ipv6Addr::from(*packed_ip)))
}
_ => Err(vm.new_value_error(format!("unknown address family {af_inet}"))),
}
}
#[pyfunction]
fn getprotobyname(name: PyStrRef, vm: &VirtualMachine) -> PyResult {
let cstr = name.to_cstring(vm)?;
let proto = unsafe { c::getprotobyname(cstr.as_ptr()) };
if proto.is_null() {
return Err(vm.new_os_error("protocol not found".to_owned()));
}
let num = unsafe { (*proto).p_proto };
Ok(vm.ctx.new_int(num).into())
}
#[pyfunction]
fn getnameinfo(
address: PyTupleRef,
flags: i32,
vm: &VirtualMachine,
) -> Result<(String, String), IoOrPyException> {
match address.len() {
2..=4 => {}
_ => {
return Err(vm
.new_type_error("illegal sockaddr argument".to_owned())
.into())
}
}
let (addr, flowinfo, scopeid) = Address::from_tuple_ipv6(&address, vm)?;
let hints = dns_lookup::AddrInfoHints {
address: c::AF_UNSPEC,
socktype: c::SOCK_DGRAM,
flags: c::AI_NUMERICHOST,
protocol: 0,
};
let service = addr.port.to_string();
let mut res =
dns_lookup::getaddrinfo(Some(addr.host.as_str()), Some(&service), Some(hints))
.map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?
.filter_map(Result::ok);
let mut ainfo = res.next().unwrap();
if res.next().is_some() {
return Err(vm
.new_os_error("sockaddr resolved to multiple addresses".to_owned())
.into());
}
match &mut ainfo.sockaddr {
SocketAddr::V4(_) => {
if address.len() != 2 {
return Err(vm
.new_os_error("IPv4 sockaddr must be 2 tuple".to_owned())
.into());
}
}
SocketAddr::V6(addr) => {
addr.set_flowinfo(flowinfo);
addr.set_scope_id(scopeid);
}
}
dns_lookup::getnameinfo(&ainfo.sockaddr, flags)
.map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))
}
#[cfg(unix)]
#[pyfunction]
fn socketpair(
family: OptionalArg<i32>,
socket_kind: OptionalArg<i32>,
proto: OptionalArg<i32>,
) -> Result<(PySocket, PySocket), IoOrPyException> {
let family = family.unwrap_or(libc::AF_UNIX);
let socket_kind = socket_kind.unwrap_or(libc::SOCK_STREAM);
let proto = proto.unwrap_or(0);
let (a, b) = Socket::pair(family.into(), socket_kind.into(), Some(proto.into()))?;
let py_a = PySocket::default();
py_a.init_inner(family, socket_kind, proto, a)?;
let py_b = PySocket::default();
py_b.init_inner(family, socket_kind, proto, b)?;
Ok((py_a, py_b))
}
#[cfg(all(unix, not(target_os = "redox")))]
type IfIndex = c::c_uint;
#[cfg(windows)]
type IfIndex = winapi::shared::ifdef::NET_IFINDEX;
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn if_nametoindex(name: FsPath, vm: &VirtualMachine) -> PyResult<IfIndex> {
let name = name.to_cstring(vm)?;
let ret = unsafe { c::if_nametoindex(name.as_ptr()) };
if ret == 0 {
Err(vm.new_os_error("no interface with this name".to_owned()))
} else {
Ok(ret)
}
}
#[cfg(not(target_os = "redox"))]
#[pyfunction]
fn if_indextoname(index: IfIndex, vm: &VirtualMachine) -> PyResult<String> {
let mut buf = [0; c::IF_NAMESIZE + 1];
let ret = unsafe { c::if_indextoname(index, buf.as_mut_ptr()) };
if ret.is_null() {
Err(crate::vm::stdlib::os::errno_err(vm))
} else {
let buf = unsafe { ffi::CStr::from_ptr(buf.as_ptr()) };
Ok(buf.to_string_lossy().into_owned())
}
}
#[cfg(any(
windows,
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
))]
#[pyfunction]
fn if_nameindex(vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
#[cfg(not(windows))]
{
let list = nix::net::if_::if_nameindex()
.map_err(|err| err.into_pyexception(vm))?
.to_slice()
.iter()
.map(|iface| {
let tup: (u32, String) =
(iface.index(), iface.name().to_string_lossy().into_owned());
tup.to_pyobject(vm)
})
.collect();
Ok(list)
}
#[cfg(windows)]
{
use std::ptr;
let table = MibTable::get_raw().map_err(|err| err.into_pyexception(vm))?;
let list = table.as_slice().iter().map(|entry| {
let name =
get_name(&entry.InterfaceLuid).map_err(|err| err.into_pyexception(vm))?;
let tup = (entry.InterfaceIndex, name.to_string_lossy());
Ok(tup.to_pyobject(vm))
});
let list = list.collect::<PyResult<_>>()?;
return Ok(list);
fn get_name(
luid: &winapi::shared::ifdef::NET_LUID,
) -> io::Result<widestring::WideCString> {
let mut buf = [0; c::IF_NAMESIZE + 1];
let ret = unsafe {
netioapi::ConvertInterfaceLuidToNameW(luid, buf.as_mut_ptr(), buf.len())
};
if ret == 0 {
Ok(widestring::WideCString::from_ustr_truncate(
widestring::WideStr::from_slice(&buf[..]),
))
} else {
Err(io::Error::from_raw_os_error(ret as i32))
}
}
struct MibTable {
ptr: ptr::NonNull<netioapi::MIB_IF_TABLE2>,
}
impl MibTable {
fn get_raw() -> io::Result<Self> {
let mut ptr = ptr::null_mut();
let ret = unsafe { netioapi::GetIfTable2Ex(netioapi::MibIfTableRaw, &mut ptr) };
if ret == 0 {
let ptr = unsafe { ptr::NonNull::new_unchecked(ptr) };
Ok(Self { ptr })
} else {
Err(io::Error::from_raw_os_error(ret as i32))
}
}
}
impl MibTable {
fn as_slice(&self) -> &[netioapi::MIB_IF_ROW2] {
unsafe {
let p = self.ptr.as_ptr();
let ptr = ptr::addr_of!((*p).Table) as *const netioapi::MIB_IF_ROW2;
std::slice::from_raw_parts(ptr, (*p).NumEntries as usize)
}
}
}
impl Drop for MibTable {
fn drop(&mut self) {
unsafe { netioapi::FreeMibTable(self.ptr.as_ptr() as *mut _) }
}
}
}
}
fn get_addr(
vm: &VirtualMachine,
pyname: PyStrRef,
af: i32,
) -> Result<SocketAddr, IoOrPyException> {
let name = pyname.as_str();
if name.is_empty() {
let hints = dns_lookup::AddrInfoHints {
address: af,
socktype: c::SOCK_DGRAM,
flags: c::AI_PASSIVE,
protocol: 0,
};
let mut res = dns_lookup::getaddrinfo(None, Some("0"), Some(hints))
.map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?;
let ainfo = res.next().unwrap()?;
if res.next().is_some() {
return Err(vm
.new_os_error("wildcard resolved to multiple address".to_owned())
.into());
}
return Ok(ainfo.sockaddr);
}
if name == "255.255.255.255" || name == "<broadcast>" {
match af {
c::AF_INET | c::AF_UNSPEC => {}
_ => {
return Err(vm
.new_os_error("address family mismatched".to_owned())
.into())
}
}
return Ok(SocketAddr::V4(net::SocketAddrV4::new(
c::INADDR_BROADCAST.into(),
0,
)));
}
if let c::AF_INET | c::AF_UNSPEC = af {
if let Ok(addr) = name.parse::<Ipv4Addr>() {
return Ok(SocketAddr::V4(net::SocketAddrV4::new(addr, 0)));
}
}
if matches!(af, c::AF_INET | c::AF_UNSPEC) && !name.contains('%') {
if let Ok(addr) = name.parse::<Ipv6Addr>() {
return Ok(SocketAddr::V6(net::SocketAddrV6::new(addr, 0, 0, 0)));
}
}
let hints = dns_lookup::AddrInfoHints {
address: af,
..Default::default()
};
let name = vm
.state
.codec_registry
.encode_text(pyname, "idna", None, vm)?;
let name = std::str::from_utf8(name.as_bytes())
.map_err(|_| vm.new_runtime_error("idna output is not utf8".to_owned()))?;
let mut res = dns_lookup::getaddrinfo(Some(name), None, Some(hints))
.map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?;
Ok(res.next().unwrap().map(|ainfo| ainfo.sockaddr)?)
}
fn sock_from_raw(fileno: RawSocket, vm: &VirtualMachine) -> PyResult<Socket> {
let invalid = {
cfg_if::cfg_if! {
if #[cfg(windows)] {
fileno == INVALID_SOCKET
} else {
fileno < 0
}
}
};
if invalid {
return Err(vm.new_value_error("negative file descriptor".to_owned()));
}
Ok(unsafe { sock_from_raw_unchecked(fileno) })
}
/// SAFETY: fileno must not be equal to INVALID_SOCKET
unsafe fn sock_from_raw_unchecked(fileno: RawSocket) -> Socket {
#[cfg(unix)]
{
use std::os::unix::io::FromRawFd;
Socket::from_raw_fd(fileno)
}
#[cfg(windows)]
{
use std::os::windows::io::FromRawSocket;
Socket::from_raw_socket(fileno)
}
}
pub(super) fn sock_fileno(sock: &Socket) -> RawSocket {
#[cfg(unix)]
{
use std::os::unix::io::AsRawFd;
sock.as_raw_fd()
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawSocket;
sock.as_raw_socket()
}
}
fn into_sock_fileno(sock: Socket) -> RawSocket {
#[cfg(unix)]
{
use std::os::unix::io::IntoRawFd;
sock.into_raw_fd()
}
#[cfg(windows)]
{
use std::os::windows::io::IntoRawSocket;
sock.into_raw_socket()
}
}
pub(super) const INVALID_SOCKET: RawSocket = {
#[cfg(unix)]
{
-1
}
#[cfg(windows)]
{
winapi::um::winsock2::INVALID_SOCKET as RawSocket
}
};
fn convert_socket_error(
vm: &VirtualMachine,
err: dns_lookup::LookupError,
err_kind: SocketError,
) -> IoOrPyException {
if let dns_lookup::LookupErrorKind::System = err.kind() {
return io::Error::from(err).into();
}
let strerr = {
#[cfg(unix)]
{
let s = match err_kind {
SocketError::GaiError => unsafe {
ffi::CStr::from_ptr(libc::gai_strerror(err.error_num()))
},
SocketError::HError => unsafe {
ffi::CStr::from_ptr(libc::hstrerror(err.error_num()))
},
};
s.to_str().unwrap()
}
#[cfg(windows)]
{
"getaddrinfo failed"
}
};
let exception_cls = match err_kind {
SocketError::GaiError => gaierror(vm),
SocketError::HError => herror(vm),
};
vm.new_exception(
exception_cls,
vec![vm.new_pyobj(err.error_num()), vm.ctx.new_str(strerr).into()],
)
.into()
}
fn timeout_error(vm: &VirtualMachine) -> PyBaseExceptionRef {
timeout_error_msg(vm, "timed out".to_owned())
}
pub(crate) fn timeout_error_msg(vm: &VirtualMachine, msg: String) -> PyBaseExceptionRef {
vm.new_exception_msg(timeout(vm), msg)
}
fn get_ipv6_addr_str(ipv6: Ipv6Addr) -> String {
match ipv6.to_ipv4() {
// instead of "::0.0.ddd.ddd" it's "::xxxx"
Some(v4) if !ipv6.is_unspecified() && matches!(v4.octets(), [0, 0, _, _]) => {
format!("::{:x}", u32::from(v4))
}
_ => ipv6.to_string(),
}
}
pub(crate) struct Deadline {
deadline: Instant,
}
impl Deadline {
fn new(timeout: Duration) -> Self {
Self {
deadline: Instant::now() + timeout,
}
}
fn time_until(&self) -> Result<Duration, IoOrPyException> {
self.deadline
.checked_duration_since(Instant::now())
// past the deadline already
.ok_or(IoOrPyException::Timeout)
}
}
static DEFAULT_TIMEOUT: AtomicCell<f64> = AtomicCell::new(-1.0);
#[pyfunction]
fn getdefaulttimeout() -> Option<f64> {
let timeout = DEFAULT_TIMEOUT.load();
if timeout >= 0.0 {
Some(timeout)
} else {
None
}
}
#[pyfunction]
fn setdefaulttimeout(timeout: Option<Duration>) {
DEFAULT_TIMEOUT.store(timeout.map_or(-1.0, |d| d.as_secs_f64()));
}
#[pyfunction]
fn dup(x: PyObjectRef, vm: &VirtualMachine) -> Result<RawSocket, IoOrPyException> {
let sock = get_raw_sock(x, vm)?;
let sock = std::mem::ManuallyDrop::new(sock_from_raw(sock, vm)?);
let newsock = sock.try_clone()?;
let fd = into_sock_fileno(newsock);
#[cfg(windows)]
crate::vm::stdlib::nt::raw_set_handle_inheritable(fd as _, false)?;
Ok(fd)
}
#[pyfunction]
fn close(x: PyObjectRef, vm: &VirtualMachine) -> Result<(), IoOrPyException> {
Ok(close_inner(get_raw_sock(x, vm)?)?)
}
fn close_inner(x: RawSocket) -> io::Result<()> {
#[cfg(unix)]
use libc::close;
#[cfg(windows)]
use winapi::um::winsock2::closesocket as close;
let ret = unsafe { close(x as _) };
if ret < 0 {
let err = crate::common::os::errno();
if err.raw_os_error() != Some(errcode!(ECONNRESET)) {
return Err(err);
}
}
Ok(())
}
enum SocketError {
HError,
GaiError,
}
}
|
pub mod decimal;
mod hdb_decimal;
pub mod daydate;
pub mod longdate;
pub mod seconddate;
pub mod secondtime;
pub mod lob;
|
extern crate notify_rust;
fn main() {
let mut server = notify_rust::server::NotificationServer::new();
server.start(|n| {
if ! n.summary.is_empty() {
print!("{}", n.summary);
}
if ! n.body.is_empty() {
if ! n.summary.is_empty() {
// Maybe this is an impossible case?
// notify-send won't allow it, at least
print!(" ");
}
print!("{}", n.body);
}
print!("\n");
});
}
|
use proc_macro2::{Ident, Span};
use quote::{format_ident, quote};
fn main() {
let i1 = Ident::new("d1", Span::call_site());
println!("{}", i1);
let exp = quote! { let #i1 = 123; };
println!("{}", exp);
let i2 = format_ident!("{}_copy", i1);
println!("{}", i2);
} |
use anyhow::Result;
use qapi::qga;
use clap::Parser;
use futures::future::{FutureExt, Fuse};
use futures::stream::StreamExt;
use futures::{pin_mut, select};
use tokio::time::sleep;
use std::time::Duration;
use std::path::PathBuf;
use std::fs::File;
use std::io::{self, Read};
use super::{GlobalArgs, QgaStream};
#[derive(Parser, Debug)]
/// Executes a process inside the guest
pub(crate) struct Exec {
/// set environment variable(s)
#[clap(short = 'e', long = "env")]
environment: Option<Vec<String>>,
/// send contents as stdin
#[clap(short = 'i', long)]
stdin: Option<PathBuf>,
/// do not wait for process to terminate
#[clap(short = 'W', long)]
no_wait: bool,
path: String,
arguments: Vec<String>,
}
fn guest_kill(pid: i64, os: qga::GuestOSInfo, force: bool) -> qga::guest_exec {
let os_id = os.id.as_ref().map(String::as_str).unwrap_or("");
match os_id {
"mswindows" => qga::guest_exec {
path: "powershell.exe".into(),
arg: Some(if force {
vec!["-Command".into(), format!("Stop-Process -Id {pid} -Force")]
} else {
vec!["-Command".into(), format!("Stop-Process -Id {pid}")]
}),
env: Default::default(),
input_data: Default::default(),
capture_output: Some(false),
},
_ => qga::guest_exec {
path: "kill".into(),
arg: Some(if force {
vec!["-TERM".into(), format!("{pid}")]
} else {
vec![format!("{pid}")]
}),
env: Default::default(),
input_data: Default::default(),
capture_output: Some(false),
},
}
}
const SIGINT: i32 = 2;
impl Exec {
pub async fn run(self, qga: QgaStream, _args: GlobalArgs) -> Result<i32> {
let guest_exec = qga::guest_exec {
path: self.path,
arg: Some(self.arguments),
env: self.environment,
input_data: {
let mut bytes = Vec::new();
match self.stdin.as_ref().map(|p| (p.to_str(), p)) {
Some((Some("-"), _)) => io::stdin().read_to_end(&mut bytes).map(Some),
Some((_, p)) => File::open(p).and_then(|mut f| f.read_to_end(&mut bytes)).map(Some),
None => Ok(None),
}?.map(|_| bytes)
},
capture_output: Some(!self.no_wait),
};
log::trace!("QEMU GA Exec {:#?}", guest_exec);
let qga::GuestExec { pid } = qga.execute(guest_exec).await?;
log::trace!("QEMU GA PID {:?}", pid);
if self.no_wait {
return Ok(0)
}
let ctrlc = StreamExt::fuse(async_ctrlc::CtrlC::new().expect("ctrl+c"));
let mut ctrlc_counter = 0u8;
pin_mut!(ctrlc);
let timeout = sleep(Default::default()).fuse();
pin_mut!(timeout);
let status = Fuse::terminated();
pin_mut!(status);
let status = loop {
select! {
_ = ctrlc.next() => {
ctrlc_counter = ctrlc_counter.saturating_add(1);
match ctrlc_counter {
1 => {
let os_info = qga.execute(qga::guest_get_osinfo { }).await?;
qga.execute(guest_kill(pid, os_info, false)).await?;
timeout.set(sleep(Duration::from_millis(1)).fuse());
},
2 => {
let os_info = qga.execute(qga::guest_get_osinfo { }).await?;
qga.execute(guest_kill(pid, os_info, true)).await?;
timeout.set(sleep(Duration::from_millis(1)).fuse());
},
_ => {
return Ok(32)
},
}
},
_ = timeout => {
status.set(qga.execute(qga::guest_exec_status { pid }).fuse());
},
status = status => {
let status = status?;
timeout.set(sleep(Duration::from_millis(5)).fuse());
if let Some(err) = &status.err_data {
io::copy(&mut &err[..], &mut io::stderr())?;
}
if let Some(out) = &status.out_data {
io::copy(&mut &out[..], &mut io::stdout())?;
}
if status.exited {
break status
}
},
}
};
log::trace!("QEMU GA ExecStatus {:?}", status);
if matches!(status.err_truncated, Some(true)) {
log::warn!("STDERR truncated")
}
if matches!(status.out_truncated, Some(true)) {
log::warn!("STDOUT truncated")
}
match status.exited {
false => Ok(1),
true => match (status.exitcode, status.signal) {
(Some(code), _) => Ok(code as i32),
_ if ctrlc_counter > 0 => Ok(128 + SIGINT),
(None, Some(signal)) if signal > 0 && signal < 128 => Ok(128 + signal as i32),
(None, Some(_)) => Ok(125),
_ => Ok(0),
},
}
}
}
|
//! Application state.
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use druid::kurbo::{Affine, BezPath, Point, Rect, Shape, Size, Vec2};
use druid::{Data, Lens, WindowId};
use norad::glyph::{Contour, ContourPoint, Glyph, GlyphName, PointType};
use norad::{FontInfo, Ufo};
use crate::bez_cache::BezCache;
use crate::edit_session::{EditSession, SessionId};
/// This is by convention.
const DEFAULT_UNITS_PER_EM: f64 = 1000.;
const DEFAULT_PREVIEW_FONT_SIZE: f64 = 96.0;
/// The top level data structure.
///
/// Currently this just wraps `Workspace`; in the future multiple workspaces
/// will be possible.
#[derive(Clone, Data, Default, Lens)]
pub struct AppState {
pub workspace: Workspace,
}
/// A workspace is a single font, corresponding to a UFO file on disk.
#[derive(Clone, Lens, Data, Default)]
pub struct Workspace {
pub font: Arc<FontObject>,
/// The currently selected glyph (in the main glyph list) if any.
//TODO: allow multiple selections
pub selected: Option<GlyphName>,
/// glyphs that are already open in an editor window
pub open_glyphs: Arc<HashMap<GlyphName, WindowId>>,
pub sessions: Arc<HashMap<SessionId, Arc<EditSession>>>,
pub(crate) previews: Arc<HashMap<SessionId, PreviewSession>>,
session_map: Arc<HashMap<GlyphName, SessionId>>,
// really just a store of the fully resolved Beziers of all glyphs.
cache: Arc<BezCache>,
pub info: SimpleFontInfo,
}
#[derive(Clone, Data)]
pub struct FontObject {
pub path: Option<Arc<Path>>,
#[data(ignore)]
pub ufo: Ufo,
placeholder: Arc<BezPath>,
}
/// The data type for a grid square.
///
/// Unlike GlyphDetail, this doesn't have a reference to the glyph itself,
/// which is expensive to find in large glyphsets.
#[derive(Debug, Clone, Data, Lens)]
pub(crate) struct GridGlyph {
pub name: GlyphName,
pub outline: Arc<BezPath>,
pub is_placeholder: bool,
pub is_selected: bool,
pub upm: f64,
}
/// Detailed information about a specific glyph.
///
/// This is used in the sidepanel, as well as in the editor window.
#[derive(Clone, Data, Lens)]
pub struct GlyphDetail {
pub glyph: Arc<Glyph>,
// the full outline, including things like components
pub outline: Arc<BezPath>,
metrics: FontMetrics,
is_placeholder: bool,
}
#[derive(Clone, Data, Lens)]
pub struct SimpleFontInfo {
metrics: FontMetrics,
pub family_name: Arc<str>,
pub style_name: Arc<str>,
}
/// Things in `FontInfo` that are relevant while editing or drawing.
#[derive(Clone, Data, Lens)]
pub struct FontMetrics {
pub units_per_em: f64,
pub descender: Option<f64>,
pub x_height: Option<f64>,
pub cap_height: Option<f64>,
pub ascender: Option<f64>,
pub italic_angle: Option<f64>,
}
/// The state for an editor view.
#[derive(Clone, Data, Lens)]
pub struct EditorState {
pub metrics: FontMetrics,
pub font: Workspace,
pub session: Arc<EditSession>,
}
/// The data for a preview window
#[derive(Clone, Data, Lens)]
pub struct PreviewState {
session: PreviewSession,
pub font: Workspace,
}
/// The stuff we store separately for each preview window
#[derive(Debug, Clone, Data, Lens)]
pub(crate) struct PreviewSession {
font_size: f64,
text: Arc<String>,
}
/// A type constructed by a lens to represent our sidebearings.
#[derive(Debug, Clone, Data, Lens)]
pub struct Sidebearings {
pub left: f64,
pub right: f64,
}
impl Workspace {
/// a lens into a particular editor view.
pub(crate) fn editor_state(id: SessionId) -> impl Lens<Workspace, EditorState> {
lenses::EditorState(id)
}
/// a lens into a particular editor view.
pub(crate) fn preview_state(id: SessionId) -> impl Lens<Workspace, PreviewState> {
lenses::PreviewState(id)
}
/// a lens for getting a `GridGlyph`.
pub(crate) fn glyph_grid(name: GlyphName) -> impl Lens<Workspace, Option<GridGlyph>> {
lenses::GridGlyph(name)
}
/// A lens or the currently selected glyph
#[allow(non_upper_case_globals)]
pub(crate) const selected_glyph: lenses::SelectedGlyph = lenses::SelectedGlyph;
pub fn set_file(&mut self, ufo: Ufo, path: impl Into<Option<PathBuf>>) {
let obj = FontObject {
path: path.into().map(Into::into),
ufo,
placeholder: Arc::new(placeholder_outline()),
};
self.font = obj.into();
self.info = SimpleFontInfo::from_font(&self.font);
self.build_path_cache();
}
fn build_path_cache(&mut self) {
let Workspace {
font,
cache,
sessions,
..
} = self;
Arc::make_mut(cache).reset(&font.ufo, &|name| {
sessions
.values()
.find(|sesh| sesh.name == *name)
.map(|sesh| &sesh.glyph)
.or_else(|| font.ufo.get_glyph(name))
});
}
pub fn save(&mut self) -> Result<(), Box<dyn Error>> {
let font_obj = Arc::make_mut(&mut self.font);
font_obj.update_info(&self.info);
// flush all open sessions
for session in self.sessions.values() {
let glyph = session.to_norad_glyph();
font_obj
.ufo
.get_default_layer_mut()
.unwrap()
.insert_glyph(glyph);
}
if let Some(path) = font_obj.path.as_ref() {
// very careful save: we write to a temporary location, then
// backup the existing data, then move data from the temporary
// location to the actual path
let temp_path = temp_write_path(path);
log::info!("saving to {:?}", temp_path);
font_obj.ufo.save(&temp_path)?;
if let Some(backup_path) = backup_ufo_at_path(path)? {
log::info!("backing up existing data to {:?}", backup_path);
}
fs::rename(&temp_path, path)?;
} else {
log::error!("save called with no path set");
}
Ok(())
}
pub fn get_or_create_session(&mut self, glyph_name: &GlyphName) -> Arc<EditSession> {
self.session_map
.get(glyph_name)
.and_then(|id| self.sessions.get(id))
.cloned()
.unwrap_or_else(|| {
let session = Arc::new(EditSession::new(glyph_name, self));
let session_id = session.id;
Arc::make_mut(&mut self.sessions).insert(session_id, session.clone());
Arc::make_mut(&mut self.session_map).insert(glyph_name.clone(), session_id);
session
})
}
pub fn new_preview_session(&mut self) -> SessionId {
let id = SessionId::next();
Arc::make_mut(&mut self.previews).insert(
id,
PreviewSession {
text: "Hamburgler".to_string().into(),
font_size: DEFAULT_PREVIEW_FONT_SIZE,
},
);
id
}
pub(crate) fn get_bezier(&self, name: &GlyphName) -> Option<Arc<BezPath>> {
self.cache.get(name)
}
/// After a glyph is edited this rebuilds the affected beziers.
pub(crate) fn invalidate_path(&mut self, name: &GlyphName) {
let Workspace {
font,
cache,
sessions,
..
} = self;
let to_inval = cache.glyphs_containing_component(name).to_vec();
for name in std::iter::once(name).chain(to_inval.iter()) {
Arc::make_mut(cache).rebuild(name, &|name| {
sessions
.values()
.find(|sesh| sesh.name == *name)
.map(|sesh| &sesh.glyph)
.or_else(|| font.ufo.get_glyph(name))
});
}
}
/// Returns the upm for this font.
///
/// This is needed to correctly scale the points in the glyph.
pub fn units_per_em(&self) -> f64 {
self.font
.ufo
.font_info
.as_ref()
.and_then(|info| info.units_per_em.map(|v| v.get()))
.unwrap_or(DEFAULT_UNITS_PER_EM)
}
pub fn add_new_glyph(&mut self) -> GlyphName {
let mut name = String::from("newGlyph");
let mut counter = 0;
while self.font.ufo.get_glyph(name.as_str()).is_some() {
counter += 1;
name = format!("newGlyph.{}", counter);
}
let name: GlyphName = name.into();
let glyph = norad::Glyph::new_named(name.clone());
self.font_mut()
.ufo
.get_default_layer_mut()
.unwrap()
.insert_glyph(glyph);
name
}
pub fn delete_selected_glyph(&mut self) -> Option<Arc<Glyph>> {
self.selected.take().and_then(|name| {
self.font_mut()
.ufo
.get_default_layer_mut()
.unwrap()
.remove_glyph(&name)
})
}
/// Rename a glyph everywhere it might be.
pub fn rename_glyph(&mut self, old_name: GlyphName, new_name: GlyphName) {
let font = self.font_mut();
let mut glyph = match font
.ufo
.get_default_layer_mut()
.unwrap()
.remove_glyph(&old_name)
{
Some(g) => g,
None => {
log::warn!("attempted to rename missing glyph '{}'", old_name);
return;
}
};
{
let glyph = Arc::make_mut(&mut glyph);
glyph.codepoints = crate::glyph_names::codepoints_for_glyph(&new_name);
glyph.name = new_name.clone();
}
font.ufo
.get_default_layer_mut()
.unwrap()
.insert_glyph(glyph);
// and if this is the selected glyph, change that too;
if self.selected.as_ref() == Some(&old_name) {
self.selected = Some(new_name.clone())
}
// if this glyph is open, rename that too;
if self.session_map.contains_key(&old_name) {
let session_map = Arc::make_mut(&mut self.session_map);
let session_id = session_map.remove(&old_name).unwrap();
session_map.insert(new_name.clone(), session_id);
let sessions = Arc::make_mut(&mut self.sessions);
let session = sessions.get_mut(&session_id).unwrap();
Arc::make_mut(session).rename(new_name.clone());
}
if self.open_glyphs.contains_key(&old_name) {
let open = Arc::make_mut(&mut self.open_glyphs);
let window = open.remove(&old_name).unwrap();
open.insert(new_name, window);
}
}
pub fn update_glyph_metadata(&mut self, changed: &Arc<Glyph>) {
// update the active session, if one exists
if let Some(session_id) = self.session_map.get(&changed.name) {
let sessions = Arc::make_mut(&mut self.sessions);
let session = sessions.get_mut(session_id).unwrap();
let session = Arc::make_mut(session);
session.update_glyph_metadata(changed);
}
// update the UFO;
if let Some(glyph) = self.font_mut().ufo.get_glyph_mut(&changed.name) {
glyph.advance = changed.advance.clone();
}
}
pub fn font_mut(&mut self) -> &mut FontObject {
Arc::make_mut(&mut self.font)
}
}
#[allow(non_upper_case_globals)]
impl GlyphDetail {
/// A lens for retrieving the glyph's codepoint
pub const codepoint: lenses::Codepoint = lenses::Codepoint;
/// A lens for the glyph's advance.
pub const advance: lenses::Advance = lenses::Advance;
/// A lens for the glyph's name.
pub const glyph_name: lenses::GlyphName = lenses::GlyphName;
/// Get the fully resolved (including components) bezier path for this glyph.
///
/// Returns the placeholder glyph if this glyph has no outline.
pub fn get_bezier(&self) -> Arc<BezPath> {
self.outline.clone()
}
/// Returns `true` if this glyph uses a placeholder path.
pub fn is_placeholder_glyph(&self) -> bool {
self.is_placeholder
}
/// Returns the first `char` in this glyph's codepoint list.
pub fn get_codepoint(&self) -> Option<char> {
self.glyph
.codepoints
.as_ref()
.and_then(|v| v.first())
.cloned()
}
/// The bounds of the metric square, in design space. (0, 0) is at the
/// left edge of the baseline, and y is up.
pub(crate) fn layout_bounds(&self) -> Rect {
layout_bounds(&self.glyph, &self.metrics)
}
/// The upm for the font this glyph belongs to.
pub fn upm(&self) -> f64 {
self.metrics.units_per_em
}
}
#[allow(non_upper_case_globals)]
impl EditorState {
/// a lens to return info on the current selection
pub const sidebearings: lenses::Sidebearings = lenses::Sidebearings;
pub const detail_glyph: lenses::EditorGlyph = lenses::EditorGlyph;
/// The bounds of the metric square, in design space. (0, 0) is at the
/// left edge of the baseline, and y is up.
pub(crate) fn layout_bounds(&self) -> Rect {
layout_bounds(&self.session.glyph, &self.metrics)
}
/// Returns a `Rect` representing, in the coordinate space of the canvas,
/// the total region occupied by outlines, components, anchors, and the metric
/// bounds.
pub fn content_region(&self) -> Rect {
let result = self.layout_bounds().union(self.session.work_bounds());
Rect::from_points((result.x0, -result.y0), (result.x1, -result.y1))
}
pub fn session_mut(&mut self) -> &mut EditSession {
Arc::make_mut(&mut self.session)
}
fn compute_sidebearings(&self) -> Sidebearings {
let content_region = self
.font
.get_bezier(&self.session.name)
.map(|p| p.bounding_box())
.unwrap_or_default();
let layout_bounds = self.layout_bounds();
// the content region if it contains components and a scale transform
// can need rounding.
let left = content_region.min_x().round();
let right = layout_bounds.width() - content_region.max_x().round();
Sidebearings { left, right }
}
}
impl PreviewState {
pub(crate) fn text(&self) -> &str {
&self.session.text
}
pub(crate) fn font_size(&self) -> f64 {
self.session.font_size
}
}
impl FontObject {
/// Update the actual `FontInfo` from the generated `SimpleFontInfo`
#[allow(clippy::float_cmp)]
fn update_info(&mut self, info: &SimpleFontInfo) {
// we don't want to change anything if we don't have to:
let existing_info = SimpleFontInfo::from_font(self);
if !existing_info.same(info) {
let font_info = self.ufo.font_info.get_or_insert_with(Default::default);
// we don't want to set anything that hasn't changed.
if existing_info.family_name != info.family_name {
font_info.family_name = Some(info.family_name.to_string());
}
if existing_info.style_name != info.style_name {
font_info.style_name = Some(info.style_name.to_string());
}
if existing_info.metrics.units_per_em != info.metrics.units_per_em {
font_info.units_per_em = info.metrics.units_per_em.try_into().ok();
}
if existing_info.metrics.descender != info.metrics.descender {
font_info.descender = info.metrics.descender.map(Into::into);
}
if existing_info.metrics.ascender != info.metrics.ascender {
font_info.ascender = info.metrics.ascender.map(Into::into);
}
if existing_info.metrics.x_height != info.metrics.x_height {
font_info.x_height = info.metrics.x_height.map(Into::into);
}
if existing_info.metrics.cap_height != info.metrics.cap_height {
font_info.cap_height = info.metrics.cap_height.map(Into::into);
}
if existing_info.metrics.italic_angle != info.metrics.italic_angle {
font_info.italic_angle = info.metrics.italic_angle.map(Into::into);
}
}
}
}
use std::convert::TryInto;
impl Default for FontObject {
fn default() -> FontObject {
let font_info = FontInfo {
family_name: Some(String::from("Untitled")),
..Default::default()
};
let mut ufo = Ufo::new();
ufo.font_info = Some(font_info);
FontObject {
path: None,
ufo,
placeholder: Arc::new(placeholder_outline()),
}
}
}
impl SimpleFontInfo {
fn from_font(font: &FontObject) -> Self {
SimpleFontInfo {
family_name: font
.ufo
.font_info
.as_ref()
.and_then(|f| f.family_name.as_ref().map(|s| s.as_str().into()))
.unwrap_or_else(|| "Untitled".into()),
style_name: font
.ufo
.font_info
.as_ref()
.and_then(|f| f.style_name.as_ref().map(|s| s.as_str().into()))
.unwrap_or_else(|| "Regular".into()),
metrics: font
.ufo
.font_info
.as_ref()
.map(FontMetrics::from)
.unwrap_or_default(),
}
}
pub(crate) fn font_metrics(&self) -> &FontMetrics {
&self.metrics
}
}
impl Default for SimpleFontInfo {
fn default() -> Self {
SimpleFontInfo {
metrics: Default::default(),
family_name: "".into(),
style_name: "".into(),
}
}
}
impl<'a> From<&'a FontInfo> for FontMetrics {
fn from(src: &'a FontInfo) -> FontMetrics {
FontMetrics {
units_per_em: src
.units_per_em
.map(|v| v.get())
.unwrap_or(DEFAULT_UNITS_PER_EM),
descender: src.descender.map(|v| v.get()),
x_height: src.x_height.map(|v| v.get()),
cap_height: src.cap_height.map(|v| v.get()),
ascender: src.ascender.map(|v| v.get()),
italic_angle: src.italic_angle.map(|v| v.get()),
}
}
}
impl Default for FontMetrics {
fn default() -> Self {
FontMetrics {
units_per_em: DEFAULT_UNITS_PER_EM,
descender: None,
x_height: None,
cap_height: None,
ascender: None,
italic_angle: None,
}
}
}
mod lenses {
use std::sync::Arc;
use druid::{Data, Lens};
use norad::GlyphName as GlyphName_;
use super::{
EditorState as EditorState_, GlyphDetail, GridGlyph as GridGlyph_,
PreviewState as PreviewState_, SessionId, Sidebearings as Sidebearings_, Workspace,
};
/// Workspace -> EditorState
pub struct EditorState(pub SessionId);
/// Workspace -> PreviewState
pub struct PreviewState(pub SessionId);
/// Workspace -> GridGlyph
pub struct GridGlyph(pub GlyphName_);
/// Workspace -> GlyphPlus
pub struct SelectedGlyph;
/// EditorState -> GlyphDetail
pub struct EditorGlyph;
/// GlyphPlus => GlyphName_
pub struct GlyphName;
/// GlyphPlus -> char
pub struct Codepoint;
pub struct Advance;
pub struct Sidebearings;
impl Lens<Workspace, EditorState_> for EditorState {
fn with<V, F: FnOnce(&EditorState_) -> V>(&self, data: &Workspace, f: F) -> V {
let metrics = data.info.metrics.clone();
let session = data.sessions.get(&self.0).cloned().unwrap();
let glyph = EditorState_ {
font: data.clone(),
metrics,
session,
};
f(&glyph)
}
fn with_mut<V, F: FnOnce(&mut EditorState_) -> V>(&self, data: &mut Workspace, f: F) -> V {
//FIXME: this is creating a new copy and then throwing it away
//this is just so that the signatures work for now, we aren't actually doing any
let metrics = data.info.metrics.clone();
let session = data.sessions.get(&self.0).unwrap().to_owned();
let mut glyph = EditorState_ {
font: data.clone(),
metrics,
session,
};
let v = f(&mut glyph);
if !data
.sessions
.get(&self.0)
.map(|s| s.same(&glyph.session))
.unwrap_or(true)
{
let name = glyph.session.name.clone();
Arc::make_mut(&mut data.sessions).insert(self.0, glyph.session);
data.invalidate_path(&name);
}
v
}
}
impl Lens<Workspace, PreviewState_> for PreviewState {
fn with<V, F: FnOnce(&PreviewState_) -> V>(&self, data: &Workspace, f: F) -> V {
//let metrics = data.info.metrics.clone();
let session = data.previews.get(&self.0).cloned().unwrap();
//let session = data.sessions.get(&self.0).cloned().unwrap();
let session = PreviewState_ {
font: data.clone(),
session,
};
f(&session)
}
fn with_mut<V, F: FnOnce(&mut PreviewState_) -> V>(&self, data: &mut Workspace, f: F) -> V {
//let metrics = data.info.metrics.clone();
let session = data.previews.get(&self.0).cloned().unwrap();
//let session = data.sessions.get(&self.0).cloned().unwrap();
let mut session = PreviewState_ {
font: data.clone(),
session,
};
let v = f(&mut session);
if !data
.previews
.get(&self.0)
.map(|s| s.same(&session.session))
.unwrap_or(true)
{
Arc::make_mut(&mut data.previews).insert(self.0, session.session);
}
v
}
}
impl Lens<EditorState_, Sidebearings_> for Sidebearings {
fn with<V, F: FnOnce(&Sidebearings_) -> V>(&self, data: &EditorState_, f: F) -> V {
let sidebearings = data.compute_sidebearings();
f(&sidebearings)
}
fn with_mut<V, F: FnOnce(&mut Sidebearings_) -> V>(
&self,
data: &mut EditorState_,
f: F,
) -> V {
let mut sidebearings = data.compute_sidebearings();
f(&mut sidebearings)
}
}
impl EditorGlyph {
fn make_data(state: &EditorState_) -> GlyphDetail {
let glyph = state.session.glyph.clone();
let outline = state.font.get_bezier(&glyph.name);
let is_placeholder = outline.is_none();
let metrics = state.font.info.metrics.clone();
GlyphDetail {
glyph,
outline: outline.unwrap_or_else(|| state.font.font.placeholder.clone()),
is_placeholder,
metrics,
}
}
}
impl Lens<EditorState_, GlyphDetail> for EditorGlyph {
fn with<V, F: FnOnce(&GlyphDetail) -> V>(&self, data: &EditorState_, f: F) -> V {
let g = EditorGlyph::make_data(data);
f(&g)
}
fn with_mut<V, F: FnOnce(&mut GlyphDetail) -> V>(
&self,
data: &mut EditorState_,
f: F,
) -> V {
let mut g = EditorGlyph::make_data(data);
let r = f(&mut g);
if !g.glyph.same(&data.session.glyph) {
data.session_mut().update_glyph_metadata(&g.glyph);
}
r
}
}
impl Lens<Workspace, Option<GlyphDetail>> for SelectedGlyph {
fn with<V, F: FnOnce(&Option<GlyphDetail>) -> V>(&self, data: &Workspace, f: F) -> V {
let selected = data.selected.as_ref().map(|name| {
let glyph = data
.font
.ufo
.get_glyph(name)
.expect("missing glyph in lens");
let outline = data.get_bezier(&glyph.name);
let is_placeholder = outline.is_none();
let metrics = data.info.metrics.clone();
GlyphDetail {
glyph: Arc::clone(glyph),
outline: outline.unwrap_or_else(|| data.font.placeholder.clone()),
metrics,
is_placeholder,
}
});
f(&selected)
}
fn with_mut<V, F: FnOnce(&mut Option<GlyphDetail>) -> V>(
&self,
data: &mut Workspace,
f: F,
) -> V {
let mut selected = data.selected.as_ref().map(|name| {
let glyph = data
.font
.ufo
.get_glyph(name)
.expect("missing glyph in lens");
let outline = data.get_bezier(&glyph.name);
let is_placeholder = outline.is_none();
let metrics = data.info.metrics.clone();
GlyphDetail {
glyph: Arc::clone(glyph),
outline: outline.unwrap_or_else(|| data.font.placeholder.clone()),
metrics,
is_placeholder,
}
});
let r = f(&mut selected);
if let Some(selected) = selected {
let is_same = data
.font
.ufo
.get_glyph(&selected.glyph.name)
.map(|g| g.same(&selected.glyph))
.unwrap_or(true);
if !is_same {
data.update_glyph_metadata(&selected.glyph);
data.selected = Some(selected.glyph.name.clone());
}
}
r
}
}
impl Lens<Workspace, Option<GridGlyph_>> for GridGlyph {
fn with<V, F: FnOnce(&Option<GridGlyph_>) -> V>(&self, data: &Workspace, f: F) -> V {
let outline = data.get_bezier(&self.0);
let is_selected = data.selected.as_ref() == Some(&self.0);
let glyph = Some(GridGlyph_ {
name: self.0.clone(),
is_placeholder: outline.is_none(),
outline: outline.unwrap_or_else(|| data.font.placeholder.clone()),
upm: data.units_per_em(),
is_selected,
});
f(&glyph)
}
fn with_mut<V, F: FnOnce(&mut Option<GridGlyph_>) -> V>(
&self,
data: &mut Workspace,
f: F,
) -> V {
let outline = data.get_bezier(&self.0);
let is_selected = data.selected.as_ref() == Some(&self.0);
let mut glyph = Some(GridGlyph_ {
name: self.0.clone(),
is_placeholder: outline.is_none(),
outline: outline.unwrap_or_else(|| data.font.placeholder.clone()),
upm: data.units_per_em(),
is_selected,
});
let r = f(&mut glyph);
// we track selections by having the grid item set this flag,
// and then we propogate that up to the workspace here.
if glyph.as_ref().map(|g| g.is_selected).unwrap_or(false) {
data.selected = Some(self.0.clone());
}
r
}
}
impl Lens<GlyphDetail, Option<char>> for Codepoint {
fn with<V, F: FnOnce(&Option<char>) -> V>(&self, data: &GlyphDetail, f: F) -> V {
let c = data.get_codepoint();
f(&c)
}
fn with_mut<V, F: FnOnce(&mut Option<char>) -> V>(
&self,
data: &mut GlyphDetail,
f: F,
) -> V {
let mut c = data.get_codepoint();
let r = f(&mut c);
let old = data.get_codepoint();
if c != old {
let glyph = Arc::make_mut(&mut data.glyph);
match c {
Some(c) => glyph.codepoints = Some(vec![c]),
None => glyph.codepoints = None,
}
}
r
}
}
impl Lens<GlyphDetail, f32> for Advance {
fn with<V, F: FnOnce(&f32) -> V>(&self, data: &GlyphDetail, f: F) -> V {
let advance = data.glyph.advance.as_ref().map(|a| a.width).unwrap_or(0.);
f(&advance)
}
#[allow(clippy::float_cmp)]
fn with_mut<V, F: FnOnce(&mut f32) -> V>(&self, data: &mut GlyphDetail, f: F) -> V {
let advance = data.glyph.advance.as_ref().map(|a| a.width).unwrap_or(0.);
let mut advance2 = advance;
let result = f(&mut advance2);
if advance2 != advance {
let glyph = Arc::make_mut(&mut data.glyph);
if advance2 == 0. {
glyph.advance = None;
} else {
let mut advance = glyph.advance.clone().unwrap_or_default();
advance.width = advance2;
glyph.advance = Some(advance);
}
}
result
}
}
impl Lens<GlyphDetail, GlyphName_> for GlyphName {
fn with<V, F: FnOnce(&GlyphName_) -> V>(&self, data: &GlyphDetail, f: F) -> V {
f(&data.glyph.name)
}
fn with_mut<V, F: FnOnce(&mut GlyphName_) -> V>(&self, data: &mut GlyphDetail, f: F) -> V {
// THIS DOESN'T DO ANYTHING! all the mutation happens
// as a result of the RENAME_GLYPH command.
let mut s = data.glyph.name.clone();
f(&mut s)
}
}
}
//FIXME: put this in some `GlyphExt` trait or something
/// Convert this glyph's path from the UFO representation into a `kurbo::BezPath`
/// (which we know how to draw.)
pub(crate) fn path_for_glyph(glyph: &Glyph) -> Option<BezPath> {
/// An outline can have multiple contours, which correspond to subpaths
fn add_contour(path: &mut BezPath, contour: &Contour) {
let mut close: Option<&ContourPoint> = None;
let start_idx = match contour
.points
.iter()
.position(|pt| pt.typ != PointType::OffCurve)
{
Some(idx) => idx,
None => return,
};
let first = &contour.points[start_idx];
path.move_to((first.x as f64, first.y as f64));
if first.typ != PointType::Move {
close = Some(first);
}
let mut controls = Vec::with_capacity(2);
let mut add_curve = |to_point: Point, controls: &mut Vec<Point>| {
match controls.as_slice() {
&[] => path.line_to(to_point),
&[a] => path.quad_to(a, to_point),
&[a, b] => path.curve_to(a, b, to_point),
_illegal => panic!("existence of second point implies first"),
};
controls.clear();
};
let mut idx = (start_idx + 1) % contour.points.len();
while idx != start_idx {
let next = &contour.points[idx];
let point = Point::new(next.x as f64, next.y as f64);
match next.typ {
PointType::OffCurve => controls.push(point),
PointType::Line => {
debug_assert!(controls.is_empty(), "line type cannot follow offcurve");
add_curve(point, &mut controls);
}
PointType::Curve => add_curve(point, &mut controls),
PointType::QCurve => {
log::warn!("quadratic curves are currently ignored");
add_curve(point, &mut controls);
}
PointType::Move => debug_assert!(false, "illegal move point in path?"),
}
idx = (idx + 1) % contour.points.len();
}
if let Some(to_close) = close.take() {
add_curve((to_close.x as f64, to_close.y as f64).into(), &mut controls);
}
}
if let Some(outline) = glyph.outline.as_ref() {
let mut path = BezPath::new();
outline
.contours
.iter()
.for_each(|c| add_contour(&mut path, c));
Some(path)
} else {
None
}
}
/// Returns a rect representing the metric bounds of this glyph; that is,
/// taking into account the font metrics (ascender, descender) as well as the
/// glyph's width.
///
/// This rect is in the same coordinate space as the glyph: y is up, and
/// (0, 0) is at the intersection of the baseline and the left sidebearing.
fn layout_bounds(glyph: &Glyph, metrics: &FontMetrics) -> Rect {
let upm = metrics.units_per_em;
let ascender = metrics.ascender.unwrap_or(upm * 0.8);
let descender = metrics.descender.unwrap_or(upm * -0.2);
let width = glyph.advance.as_ref().map(|a| a.width as f64);
let width = width.unwrap_or(upm / 2.0);
let work_size = Size::new(width, ascender + descender.abs());
let work_origin = Point::new(0., descender);
Rect::from_origin_size(work_origin, work_size)
}
/// a poorly drawn question mark glyph, used as a placeholder
fn placeholder_outline() -> BezPath {
let mut bez = BezPath::new();
bez.move_to((72.0, 505.0));
bez.line_to((196.0, 505.0));
bez.line_to((196.0, 425.0));
bez.line_to((72.0, 425.0));
bez.line_to((72.0, 505.0));
bez.close_path();
bez.move_to((72.0, 400.0));
bez.line_to((196.0, 400.0));
bez.line_to((196.0, 340.0));
bez.curve_to((196.0, 330.0), (198.0, 321.0), (207.0, 309.0));
bez.line_to((263.0, 240.0));
bez.curve_to((272.0, 228.0), (280.0, 214.0), (280.0, 191.0));
bez.line_to((280.0, 99.0));
bez.curve_to((280.0, 32.0), (240.0, 0.0), (138.0, 0.0));
bez.curve_to((43.0, 0.0), (1.0, 32.0), (0.0, 99.0));
bez.line_to((0.0, 188.0));
bez.line_to((125.0, 188.0));
bez.line_to((125.0, 110.0));
bez.curve_to((125.0, 95.0), (129.0, 89.0), (140.0, 89.0));
bez.curve_to((151.0, 89.0), (155.0, 95.0), (155.0, 110.0));
bez.line_to((155.0, 188.0));
bez.curve_to((155.0, 204.0), (150.0, 211.0), (143.0, 219.0));
bez.line_to((85.0, 287.0));
bez.curve_to((76.0, 299.0), (72.0, 310.0), (72.0, 325.0));
bez.line_to((72.0, 400.0));
bez.close_path();
bez.apply_affine(Affine::FLIP_Y);
bez.apply_affine(Affine::translate(Vec2::new(0.0, 500.0)));
bez
}
/// Move the contents of the file at `path` to another location.
///
/// If `path` exists, returns the backup location on success.
fn backup_ufo_at_path(path: &Path) -> Result<Option<PathBuf>, std::io::Error> {
if !path.exists() {
return Ok(None);
}
let backup_dir = format!(
"{}_backups",
path.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("Untitled")
);
let mut backup_dir = path.with_file_name(backup_dir);
if !backup_dir.exists() {
fs::create_dir(&backup_dir)?;
}
let backup_date = chrono::Local::now();
let date_str = backup_date.format("%Y-%m-%d_%Hh%Mm%Ss.ufo");
backup_dir.push(date_str.to_string());
if backup_dir.exists() {
fs::remove_dir_all(&backup_dir)?;
}
fs::rename(path, &backup_dir)?;
Ok(Some(backup_dir))
}
fn temp_write_path(path: &Path) -> PathBuf {
let mut n = 0;
let backup_date = chrono::Local::now();
let date_str = backup_date.format("%Y-%m-%d_%Hh%Mm%Ss");
let stem = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("Untitled");
loop {
let file_path = format!("{}-savefile-{}_{}.ufo", stem, date_str, n);
let full_path = path.with_file_name(file_path);
if !full_path.exists() {
break full_path;
}
n += 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn font_info_changes() {
let mut fontobj = FontObject::default();
let font_info = fontobj.ufo.font_info.clone().unwrap();
assert!(font_info.style_name.is_none());
assert!(font_info.descender.is_none());
assert_eq!(font_info.family_name, Some("Untitled".to_string()));
let mut info = SimpleFontInfo::from_font(&fontobj);
info.metrics.descender = Some(420.);
info.style_name = "Extra Cheese".into();
fontobj.update_info(&info);
let font_info = fontobj.ufo.font_info.clone().unwrap();
assert_eq!(font_info.style_name, Some("Extra Cheese".to_string()));
assert_eq!(font_info.descender, Some(420.0.into()));
// see that it also works if there's _no_ font info:
fontobj.ufo.font_info = None;
fontobj.update_info(&info);
let font_info = fontobj.ufo.font_info.clone().unwrap();
assert_eq!(font_info.style_name, Some("Extra Cheese".to_string()));
assert_eq!(font_info.descender, Some(420.0.into()));
}
}
|
use std::borrow::{Borrow, BorrowMut};
use std::env;
use std::error::Error;
use std::fs;
#[derive(Debug)]
pub struct Config {
pub query: String,
pub filename: String,
pub case_sensitive: bool,
}
impl Config {
pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string"),
};
let filename = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file name"),
};
// read var from env
// 如果 CASE_INSENSITIVE 被设置为任何值,is_err 会返回 false 并将进行大小写不敏感搜索
// 这里我们只关心 CASE_INSENSITIVE 是否被设置了而不关心所设置的值,所以使用了 is_err 而不是 unwrap/expect
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
Ok(Config {
query,
filename,
case_sensitive,
})
}
}
// Box<dyn Error> 意味着函数会返回实现了 Error trait 的类型,不过无需指定具体返回的值的类型
// dyn 表示 动态的(dynamic)
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.filename)?;
// println!("With text:\n{}", contents);
let results = if config.case_sensitive {
search(&config.query, &contents)
} else {
search_case_insensitive(&config.query, &contents)
};
for line in results {
println!("{}", line);
}
Ok(())
}
fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.contains(query))
.collect()
}
fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
// 关于迭代器的性能:迭代器作为一个高级的抽象,被编译成了与手写的底层代码大体一致性能的代码
// 迭代器是 Rust 的 零成本抽象(zero-cost abstractions) 之一,它意味着抽象并不会引入运行时开销
contents
.lines()
.filter(|line| {
line.to_lowercase()
.as_str()
.contains(query.to_lowercase().as_str())
})
.collect()
}
#[cfg(test)]
mod tests {
use crate::{search, search_case_insensitive, Config};
// #[test]
// #[ignore]
// fn not_enough_args() {
// let args = vec![String::from("/path/to/script")];
// let config = Config::new(&args);
// match config {
// Ok(c) => panic!("config should not be Ok"),
// Err(e) => {
// println!("err: {}", e);
// assert_eq!(e, "not enough arguments")
// }
// }
// }
//
// #[test]
// #[ignore]
// fn enough_args() {
// let args = vec![
// String::from("/path/to/script"),
// String::from("the"),
// String::from("poem.txt"),
// ];
// let config = Config::new(&args);
// match config {
// Ok(c) => (),
// Err(e) => {
// println!("err: {}", e);
// panic!("config should be Ok");
// }
// }
// }
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_incensitive() {
let query = "rUST";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
|
#![allow(non_snake_case)]
#![cfg(test)]
fn _returnSameI32(x: i32) -> i32 {
x
}
fn _returnDifferentI32(x: i32) -> i32 {
1
}
fn _returnSameString()
{
}
#[test]
fn Can_read_variable_in_inner_block() {
let x: i32 = 1;
{
let x2 = x;
assert_eq!(x2, x);
}
assert_eq!(x, 1);
}
#[test]
fn Can_read_copyable_variable_in_function_that_owns_and_returns() {
let x: i32 = 1;
let xSame = _returnSameI32(x);
assert_eq!(x, xSame);
}
#[test]
fn Can_read_copyable_variable_in_function_that_owns_and_does_not_return_it() {
let x: i32 = 1;
let xSame = _returnDifferentI32(x);
assert_eq!(x, xSame);
} |
use crate::Result;
use serde::{Deserialize, Serialize};
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
struct ResponseList {
topics: Vec<Topic>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Response {
topic: Topic,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Topic {
pub author: String,
pub last_replied_to_at: Option<String>,
pub locked: bool,
pub post_count: i64,
pub slug: String,
pub sticky: bool,
pub title: String,
pub user_id: i64,
pub view_count: i64,
}
impl crate::Client {
pub async fn topic<T: Into<String>>(&self, forum: T, thread: T) -> Result<Topic> {
let resp: Response = self
.request(
reqwest::Method::GET,
&format!(
"api/v1/json/forums/{}/topics/{}",
forum.into(),
thread.into()
),
)
.send()
.await?
.error_for_status()?
.json()
.await?;
Ok(resp.topic)
}
}
#[cfg(test)]
mod tests {
use httptest::{matchers::*, responders::*, Expectation, Server};
#[tokio::test]
async fn forums() {
let _ = pretty_env_logger::try_init();
let data: serde_json::Value =
serde_json::from_slice(include_bytes!("../testdata/forum_dis_topic_amamods.json"))
.unwrap();
let server = Server::run();
server.expect(
Expectation::matching(request::method_path(
"GET",
"/api/v1/json/forums/dis/topics/ask-the-mods-anything",
))
.respond_with(json_encoded(data)),
);
let cli =
crate::Client::with_baseurl("test", "42069", &format!("{}", server.url("/"))).unwrap();
cli.topic("dis", "ask-the-mods-anything").await.unwrap();
}
}
|
// 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.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct RequestQueryIdentification
{
expected_data_type: DataType,
expected_query_name: UncompressedName,
}
impl RequestQueryIdentification
{
pub(crate) fn matches<'message>(&self, received_data_type: DataType, received_query_name: WithoutCompressionParsedName<'message>) -> Result<(), DnsProtocolError>
{
if unlikely!(self.data_type != received_data_type)
{
return Err(ResponseWasForADifferentDataType)
}
let expected_query_name = self.expected_query_name.name();
if likely!(expected_query_name == received_query_name)
{
Ok(())
}
else
{
Err(ResponseWasForADifferentName)
}
}
}
|
#[macro_use]
mod macros;
mod hex;
mod object_id;
mod document;
mod array;
mod value;
pub mod linked_hash_map;
pub mod error;
pub mod vli;
mod datetime;
pub use object_id::{ObjectId, ObjectIdMaker};
pub use document::Document;
pub use array::Array;
pub use datetime::UTCDateTime;
pub use value::*;
pub use error::BsonErr;
pub type BsonResult<T> = Result<T, error::BsonErr>;
#[cfg(test)]
mod tests {
use crate::document::Document;
use crate::object_id::ObjectIdMaker;
#[test]
fn document_basic() {
let mut id_maker = ObjectIdMaker::new();
let _doc = Document::new(&mut id_maker);
assert_eq!(2 + 2, 4);
}
#[test]
fn print_value_size() {
let size = std::mem::size_of::<crate::Value>();
assert_eq!(size, 16);
}
}
|
// TODO find a better way of not compiling -bin for wasm32
#[cfg(target_arch="wasm32")]
fn main() {
}
#[cfg(not(target_arch="wasm32"))]
fn main() {
main_impl::main();
}
#[cfg(not(target_arch="wasm32"))]
mod main_impl {
extern crate mandelbrot;
extern crate image;
use self::mandelbrot::point::{Point, PlotSpace, point_resolver};
use self::mandelbrot::mandelbrot_paint::paint_mandelbrot;
use self::mandelbrot::sin_paint::sin_painter;
use ::std::f64;
use ::std::time::Instant;
use self::image::{RgbImage, ColorType};
fn print_time_since(start: Instant, desc: &str) {
let elapsed = start.elapsed();
let elapsed_micros = (elapsed.as_secs() * 1_000_000) as f64 + (elapsed.subsec_nanos() / 1000) as f64;
println!("{} took {:.2}ms", desc, elapsed_micros / 1000.0)
}
fn save(img: &RgbImage, path: &str) {
use std::fs::File;
use std::path::Path;
let save_start = Instant::now();
let ref mut fout = File::create(&Path::new(path)).unwrap();
let enc = image::png::PNGEncoder::new(fout);
let result = enc.encode(&img, img.width(), img.height(), ColorType::RGB(8));
match result {
Ok(_) => print_time_since(save_start, &format!("Saving {}", path)),
Err(e) => eprintln!("Saving {} failed: {}", path, e)
};
}
pub fn main() {
// TODO command line args
let (width, height) = (720, 720);
let ss_scale = 1;
let mut img = RgbImage::new(width * ss_scale, width * ss_scale);
//let plot_space = PlotSpace::with_centre(point::ORIGIN, 2.0 * f64::consts::PI, f64::consts::PI);
let plot_space = PlotSpace::with_centre(Point::new(-2.0/3.0, 0.0), 2.5, 2.5);
let resolve_point = point_resolver(img.width(), img.height(), plot_space);
//let paint_point = sin_painter(0.05);
let paint_point = paint_mandelbrot;
let total_pixels = img.width() * img.height();
let plot_start = Instant::now();
for (n, (x, y, px)) in (1..).zip(img.enumerate_pixels_mut()) {
let point = resolve_point(x, y);
*px = paint_point(point);
if n % (total_pixels / 200).max(1) == 0 {
use std::io::Write;
print!("\rPlotting: {:2.1}%", 100.0 * n as f64 / total_pixels as f64);
::std::io::stdout().flush().expect("If we can't flush stdout, we're in trouble");
}
}
println!();
print_time_since(plot_start, "Plotting");
let resize_start = Instant::now();
let resized_img = image::imageops::resize(&img, width, height, image::FilterType::CatmullRom);
print_time_since(resize_start, "Resizing");
save(&resized_img, "test.png");
}
}
|
//! Now we can draw all manner of colorful geometry, but that's not enough for an interesting
//! application.
//!
//! If we wanted to add keyboard support to our previous example, so that the user can use the left
//! and right arrow keys to move the square back ond forth, it would look like this:
//! ```no_run
//! extern crate quicksilver;
//!
//! use quicksilver::{
//! Result,
//! geom::{Rectangle, Vector},
//! graphics::{Background, Color},
//! input::Key, // We need the Key enum
//! lifecycle::{State, Window, run}
//! };
//!
//! struct Screen {
//! position: Vector // We need to store the position as state
//! }
//!
//! impl State for Screen {
//! fn new() -> Result<Screen> {
//! Ok(Screen {
//! position: Vector::new(50, 50)
//! })
//! }
//!
//! fn update(&mut self, window: &mut Window) -> Result<()> {
//! if window.keyboard()[Key::Right].is_down() {
//! self.position.x += 2.5;
//! }
//! if window.keyboard()[Key::Left].is_down() {
//! self.position.x -= 2.5;
//! }
//! Ok(())
//! }
//!
//! fn draw(&mut self, window: &mut Window) -> Result<()> {
//! window.clear(Color::WHITE)?;
//! window.draw(&Rectangle::new(self.position, (100, 200)), Background::Col(Color::RED));
//! Ok(())
//! }
//! }
//!
//! fn main() {
//! run::<Screen>("Hello World", Vector::new(800, 600), Default::default());
//! }
//! ```
//! Now we have very basic keyboard input controls. Every frame that the right arrow is held down,
//! the box will move 2.5 pixels to the right, and the same for left.
//!
//! The input API generally follows this principal: an input source is indexed by a button enum,
//! and returns a `ButtonState` enum. A button state can be `Pressed`, `Held`, `Released` or
//! `NotPressed`, and a convenience method `is_down` checks if the button is either pressed or
//! held.
//!
//! If we wanted to give the user more freedom, and allow them to use the mouse buttons or gamepad triggers instead of the arrow
//! keys, we could do that fairly easily:
//! ```no_run
//! extern crate quicksilver;
//!
//! use quicksilver::{
//! Result,
//! geom::{Rectangle, Vector},
//! graphics::{Background, Color},
//! input::{GamepadButton, Key, MouseButton}, // We need the mouse and gamepad buttons
//! lifecycle::{State, Window, run}
//! };
//!
//! struct Screen {
//! position: Vector // We need to store the position as state
//! }
//!
//! impl State for Screen {
//! fn new() -> Result<Screen> {
//! Ok(Screen {
//! position: Vector::new(50, 50)
//! })
//! }
//!
//! fn update(&mut self, window: &mut Window) -> Result<()> {
//! if window.keyboard()[Key::Right].is_down() ||
//! window.mouse()[MouseButton::Right].is_down() ||
//! window.gamepads().iter().any(|pad| pad[GamepadButton::TriggerRight].is_down())
//! {
//! self.position.x += 2.5;
//! }
//! if window.keyboard()[Key::Left].is_down() ||
//! window.mouse()[MouseButton::Left].is_down() ||
//! window.gamepads().iter().any(|pad| pad[GamepadButton::TriggerLeft].is_down())
//! {
//! self.position.x -= 2.5;
//! }
//! Ok(())
//! }
//!
//! fn draw(&mut self, window: &mut Window) -> Result<()> {
//! window.clear(Color::WHITE)?;
//! window.draw(&Rectangle::new(self.position, (100, 200)), Background::Col(Color::RED));
//! Ok(())
//! }
//! }
//!
//! fn main() {
//! run::<Screen>("Hello World", Vector::new(800, 600), Default::default());
//! }
//! ```
//! Unlike mice and keyboards, which generally are one-per-system, a machine may have many gamepads
//! connected. More advanced applications may wish to assign specific gamepads to specific
//! The input API generally follows this principal: an input source is indexed by a button enum,
//! and returns a `ButtonState` enum. A button state can be `Pressed`, `Held`, `Released` or
//! `NotPressed`, and a convenience method `is_down` checks if the button is either pressed or
//! held.
//! functions or specific users, but for our case checking against any gamepad does just fine.
//!
//! If we want to only apply an effect once per input submission, we have two options. One is to
//! check if the button state is exactly `Pressed`: that is, the button was not pressed the last
//! update, but now is. The other is to implement the `event` method of State, and listen for a
//! keypress event. To compare, here is an implementation that checks for `Pressed` for up and uses
//! an event for down:
//! ```no_run
//! extern crate quicksilver;
//!
//! use quicksilver::{
//! Result,
//! geom::{Rectangle, Vector},
//! graphics::{Background, Color},
//! input::{ButtonState, GamepadButton, Key, MouseButton}, // We need to match ButtonState
//! lifecycle::{Event, State, Window, run} // We need to match against Event
//! };
//!
//! struct Screen {
//! position: Vector // We need to store the position as state
//! }
//!
//! impl State for Screen {
//! fn new() -> Result<Screen> {
//! Ok(Screen {
//! position: Vector::new(50, 50)
//! })
//! }
//!
//! fn event(&mut self, event: &Event, window: &mut Window) -> Result<()> {
//! if let Event::Key(Key::Down, ButtonState::Pressed) = event {
//! self.position.y += 10.0;
//! }
//! Ok(())
//! }
//!
//! fn update(&mut self, window: &mut Window) -> Result<()> {
//! if window.keyboard()[Key::Right].is_down() ||
//! window.mouse()[MouseButton::Right].is_down() ||
//! window.gamepads().iter().any(|pad| pad[GamepadButton::TriggerRight].is_down())
//! {
//! self.position.x += 2.5;
//! }
//! if window.keyboard()[Key::Left].is_down() ||
//! window.mouse()[MouseButton::Left].is_down() ||
//! window.gamepads().iter().any(|pad| pad[GamepadButton::TriggerLeft].is_down())
//! {
//! self.position.x -= 2.5;
//! }
//! if window.keyboard()[Key::Up] == ButtonState::Pressed {
//! self.position.y -= 10.0;
//! }
//! Ok(())
//! }
//!
//! fn draw(&mut self, window: &mut Window) -> Result<()> {
//! window.clear(Color::WHITE)?;
//! window.draw(&Rectangle::new(self.position, (100, 200)), Background::Col(Color::RED));
//! Ok(())
//! }
//! }
//!
//! fn main() {
//! run::<Screen>("Hello World", Vector::new(800, 600), Default::default());
//! }
//! ```
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Comparator control/status register"]
pub comp_c1csr: COMP_C1CSR,
#[doc = "0x04 - Comparator control/status register"]
pub comp_c2csr: COMP_C2CSR,
#[doc = "0x08 - Comparator control/status register"]
pub comp_c3csr: COMP_C3CSR,
#[doc = "0x0c - Comparator control/status register"]
pub comp_c4csr: COMP_C4CSR,
#[doc = "0x10 - Comparator control/status register"]
pub comp_c5csr: COMP_C5CSR,
#[doc = "0x14 - Comparator control/status register"]
pub comp_c6csr: COMP_C6CSR,
#[doc = "0x18 - Comparator control/status register"]
pub comp_c7csr: COMP_C7CSR,
}
#[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c1csr](comp_c1csr) module"]
pub type COMP_C1CSR = crate::Reg<u32, _COMP_C1CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _COMP_C1CSR;
#[doc = "`read()` method returns [comp_c1csr::R](comp_c1csr::R) reader structure"]
impl crate::Readable for COMP_C1CSR {}
#[doc = "`write(|w| ..)` method takes [comp_c1csr::W](comp_c1csr::W) writer structure"]
impl crate::Writable for COMP_C1CSR {}
#[doc = "Comparator control/status register"]
pub mod comp_c1csr;
#[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c2csr](comp_c2csr) module"]
pub type COMP_C2CSR = crate::Reg<u32, _COMP_C2CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _COMP_C2CSR;
#[doc = "`read()` method returns [comp_c2csr::R](comp_c2csr::R) reader structure"]
impl crate::Readable for COMP_C2CSR {}
#[doc = "`write(|w| ..)` method takes [comp_c2csr::W](comp_c2csr::W) writer structure"]
impl crate::Writable for COMP_C2CSR {}
#[doc = "Comparator control/status register"]
pub mod comp_c2csr;
#[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c3csr](comp_c3csr) module"]
pub type COMP_C3CSR = crate::Reg<u32, _COMP_C3CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _COMP_C3CSR;
#[doc = "`read()` method returns [comp_c3csr::R](comp_c3csr::R) reader structure"]
impl crate::Readable for COMP_C3CSR {}
#[doc = "`write(|w| ..)` method takes [comp_c3csr::W](comp_c3csr::W) writer structure"]
impl crate::Writable for COMP_C3CSR {}
#[doc = "Comparator control/status register"]
pub mod comp_c3csr;
#[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c4csr](comp_c4csr) module"]
pub type COMP_C4CSR = crate::Reg<u32, _COMP_C4CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _COMP_C4CSR;
#[doc = "`read()` method returns [comp_c4csr::R](comp_c4csr::R) reader structure"]
impl crate::Readable for COMP_C4CSR {}
#[doc = "`write(|w| ..)` method takes [comp_c4csr::W](comp_c4csr::W) writer structure"]
impl crate::Writable for COMP_C4CSR {}
#[doc = "Comparator control/status register"]
pub mod comp_c4csr;
#[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c5csr](comp_c5csr) module"]
pub type COMP_C5CSR = crate::Reg<u32, _COMP_C5CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _COMP_C5CSR;
#[doc = "`read()` method returns [comp_c5csr::R](comp_c5csr::R) reader structure"]
impl crate::Readable for COMP_C5CSR {}
#[doc = "`write(|w| ..)` method takes [comp_c5csr::W](comp_c5csr::W) writer structure"]
impl crate::Writable for COMP_C5CSR {}
#[doc = "Comparator control/status register"]
pub mod comp_c5csr;
#[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c6csr](comp_c6csr) module"]
pub type COMP_C6CSR = crate::Reg<u32, _COMP_C6CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _COMP_C6CSR;
#[doc = "`read()` method returns [comp_c6csr::R](comp_c6csr::R) reader structure"]
impl crate::Readable for COMP_C6CSR {}
#[doc = "`write(|w| ..)` method takes [comp_c6csr::W](comp_c6csr::W) writer structure"]
impl crate::Writable for COMP_C6CSR {}
#[doc = "Comparator control/status register"]
pub mod comp_c6csr;
#[doc = "Comparator control/status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [comp_c7csr](comp_c7csr) module"]
pub type COMP_C7CSR = crate::Reg<u32, _COMP_C7CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _COMP_C7CSR;
#[doc = "`read()` method returns [comp_c7csr::R](comp_c7csr::R) reader structure"]
impl crate::Readable for COMP_C7CSR {}
#[doc = "`write(|w| ..)` method takes [comp_c7csr::W](comp_c7csr::W) writer structure"]
impl crate::Writable for COMP_C7CSR {}
#[doc = "Comparator control/status register"]
pub mod comp_c7csr;
|
#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]
pub struct Squares(pub usize);
#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]
pub struct Feet(pub usize);
#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]
pub struct Location(pub util::V2i);
impl Squares {
pub const FEET_PER: usize = 5;
}
impl From<Squares> for Feet {
fn from(s: Squares) -> Self {
Self(s.0 * Squares::FEET_PER)
}
}
impl From<Feet> for Squares {
fn from(f: Feet) -> Self {
Self(f.0 / Squares::FEET_PER)
}
}
|
//! Ffi wrapper for types defined outside the standard library.
//!
//! The modules here are named after the crates whose types are being wrapped.
//!
#[cfg(feature = "crossbeam-channel")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "channels")))]
pub mod crossbeam_channel;
pub mod parking_lot;
#[cfg(feature = "serde_json")]
#[cfg_attr(feature = "docsrs", doc(cfg(feature = "serde_json")))]
pub mod serde_json;
pub use self::parking_lot::{RMutex, ROnce, RRwLock};
#[cfg(feature = "serde_json")]
pub use self::serde_json::{RawValueBox, RawValueRef};
|
pub mod composite;
pub mod face_split;
pub mod livesplit;
pub mod llanfair;
pub mod llanfair2;
pub mod llanfair_gered;
pub mod portal2_live_timer;
pub mod shit_split;
pub mod splitterz;
pub mod splitty;
pub mod time_split_tracker;
pub mod urn;
pub mod wsplit;
mod bom_consumer;
mod xml_util;
|
#![allow(dead_code)]
use crate::{aocbail, regex, utils};
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashSet;
use std::str::FromStr;
use strum::EnumCount;
use strum_macros::{EnumCount as EnumCountMacro, EnumString};
use utils::{AOCError, AOCResult};
lazy_static! {
static ref YEAR_REGEX: Regex = regex!(r"^(\d\d\d\d)$");
static ref HEIGHT_REGEX: Regex = regex!(r"^(\d+)(in|cm)$");
static ref HAIR_REGEX: Regex = regex!(r"^#[0-9a-f]{6}$");
static ref EYE_REGEX: Regex = regex!(r"^amb|blu|brn|gry|grn|hzl|oth$");
static ref COUNTRY_REGEX: Regex = regex!(r"^\d{9}$");
}
#[derive(EnumString, EnumCountMacro, Eq, PartialEq, Hash)]
#[strum(serialize_all = "snake_case")]
pub enum PassportKey {
BYR,
IYR,
EYR,
HGT,
HCL,
ECL,
PID,
CID,
}
impl PassportKey {
fn is_valid_year(value: &str, min: usize, max: usize) -> bool {
for capture in YEAR_REGEX.captures_iter(value) {
if let Ok(year) = capture[1].parse::<usize>() {
return year >= min && year <= max;
}
}
return false;
}
pub fn is_valid(&self, value: &str) -> bool {
match self {
PassportKey::BYR => Self::is_valid_year(value, 1920, 2002),
PassportKey::IYR => Self::is_valid_year(value, 2010, 2020),
PassportKey::EYR => Self::is_valid_year(value, 2020, 2030),
PassportKey::HGT => {
for capture in HEIGHT_REGEX.captures_iter(value) {
if let Ok(height) = capture[1].parse::<usize>() {
return if &capture[2] == "cm" {
height >= 150 && height <= 193
} else {
height >= 59 && height <= 76
};
}
}
return false;
}
PassportKey::HCL => HAIR_REGEX.is_match(value),
PassportKey::ECL => EYE_REGEX.is_match(value),
PassportKey::PID => COUNTRY_REGEX.is_match(value),
PassportKey::CID => true,
}
}
}
pub struct Passport {
valid_data_only: bool,
entries: HashSet<PassportKey>,
}
impl Passport {
pub fn new(valid_data_only: bool) -> Self {
Passport {
valid_data_only,
entries: HashSet::new(),
}
}
pub fn parse_entry(&mut self, keyvalue: &str) -> AOCResult<()> {
let re = regex::Regex::new(r"^([a-z]+):([a-z0-9#]+)$")?;
for capture in re.captures_iter(keyvalue) {
let key: PassportKey = PassportKey::from_str(&capture[1])?;
if !self.valid_data_only || key.is_valid(&capture[2]) {
self.entries.insert(key);
}
return Ok(());
}
aocbail!("Unable to parse passport key from {}", keyvalue)
}
pub fn parse_entries(&mut self, input: &str) -> AOCResult<()> {
input
.split(" ")
.map(|entry: &str| self.parse_entry(entry))
.collect::<AOCResult<Vec<()>>>()
.and(Ok(()))
}
pub fn is_valid(&self) -> bool {
let mut expected_key_count = PassportKey::COUNT;
if !self.entries.contains(&PassportKey::CID) {
expected_key_count -= 1;
}
self.entries.len() == expected_key_count
}
}
pub fn day4() {
// 230
let mut input = utils::get_input("day4");
println!(
"Passport processing part 1: {}",
num_valid_passports(input, false).unwrap()
);
// 156
input = utils::get_input("day4");
println!(
"Passport processing part 2: {}",
num_valid_passports(input, true).unwrap()
);
}
pub fn num_valid_passports(
mut input: impl Iterator<Item = String>,
validate_data: bool,
) -> AOCResult<usize> {
let mut count: usize = 0;
let mut passport = Passport::new(validate_data);
while let Some(line) = input.next() {
if line.len() == 0 {
count += if passport.is_valid() { 1 } else { 0 };
passport = Passport::new(validate_data);
} else {
passport.parse_entries(&line)?;
}
}
count += if passport.is_valid() { 1 } else { 0 };
Ok(count)
}
#[test]
pub fn basic_passport_processing() {
let test_input = utils::get_input("test_day4");
assert_eq!(num_valid_passports(test_input, false).unwrap(), 2);
assert!(PassportKey::BYR.is_valid("2002"));
assert!(!PassportKey::BYR.is_valid("2003"));
assert!(PassportKey::HGT.is_valid("60in"));
assert!(PassportKey::HGT.is_valid("190cm"));
assert!(!PassportKey::HGT.is_valid("190in"));
assert!(!PassportKey::HGT.is_valid("190"));
assert!(PassportKey::HCL.is_valid("#123abc"));
assert!(!PassportKey::HCL.is_valid("#123abz"));
assert!(!PassportKey::HCL.is_valid("123abc"));
assert!(PassportKey::ECL.is_valid("brn"));
assert!(!PassportKey::ECL.is_valid("wat"));
assert!(PassportKey::PID.is_valid("000000001"));
assert!(!PassportKey::PID.is_valid("0123456789"));
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const CEventClass: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcdbec9c0_7a68_11d1_88f9_0080c7d771bf);
pub const CEventPublisher: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xab944620_79c6_11d1_88f9_0080c7d771bf);
pub const CEventSubscription: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7542e960_79c7_11d1_88f9_0080c7d771bf);
pub const CEventSystem: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e14fba2_2e22_11d1_9964_00c04fbbb345);
#[derive(:: core :: clone :: Clone)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct COMEVENTSYSCHANGEINFO {
pub cbSize: u32,
pub changeType: EOC_ChangeType,
pub objectId: super::super::super::Foundation::BSTR,
pub partitionId: super::super::super::Foundation::BSTR,
pub applicationId: super::super::super::Foundation::BSTR,
pub reserved: [::windows::core::GUID; 10],
}
#[cfg(feature = "Win32_Foundation")]
impl COMEVENTSYSCHANGEINFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for COMEVENTSYSCHANGEINFO {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for COMEVENTSYSCHANGEINFO {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("COMEVENTSYSCHANGEINFO").field("cbSize", &self.cbSize).field("changeType", &self.changeType).field("objectId", &self.objectId).field("partitionId", &self.partitionId).field("applicationId", &self.applicationId).field("reserved", &self.reserved).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for COMEVENTSYSCHANGEINFO {
fn eq(&self, other: &Self) -> bool {
self.cbSize == other.cbSize && self.changeType == other.changeType && self.objectId == other.objectId && self.partitionId == other.partitionId && self.applicationId == other.applicationId && self.reserved == other.reserved
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for COMEVENTSYSCHANGEINFO {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for COMEVENTSYSCHANGEINFO {
type Abi = ::core::mem::ManuallyDrop<Self>;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct EOC_ChangeType(pub i32);
pub const EOC_NewObject: EOC_ChangeType = EOC_ChangeType(0i32);
pub const EOC_ModifiedObject: EOC_ChangeType = EOC_ChangeType(1i32);
pub const EOC_DeletedObject: EOC_ChangeType = EOC_ChangeType(2i32);
impl ::core::convert::From<i32> for EOC_ChangeType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for EOC_ChangeType {
type Abi = Self;
}
pub const EventObjectChange: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd0565000_9df4_11d1_a281_00c04fca0aa7);
pub const EventObjectChange2: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbb07bacd_cd56_4e63_a8ff_cbf0355fb9f4);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IDontSupportEventSubscription(pub ::windows::core::IUnknown);
impl IDontSupportEventSubscription {}
unsafe impl ::windows::core::Interface for IDontSupportEventSubscription {
type Vtable = IDontSupportEventSubscription_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x784121f1_62a6_4b89_855f_d65f296de83a);
}
impl ::core::convert::From<IDontSupportEventSubscription> for ::windows::core::IUnknown {
fn from(value: IDontSupportEventSubscription) -> Self {
value.0
}
}
impl ::core::convert::From<&IDontSupportEventSubscription> for ::windows::core::IUnknown {
fn from(value: &IDontSupportEventSubscription) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDontSupportEventSubscription {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IDontSupportEventSubscription {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IDontSupportEventSubscription_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);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEnumEventObject(pub ::windows::core::IUnknown);
impl IEnumEventObject {
pub unsafe fn Clone(&self) -> ::windows::core::Result<IEnumEventObject> {
let mut result__: <IEnumEventObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumEventObject>(result__)
}
pub unsafe fn Next(&self, creqelem: u32, ppinterface: *mut ::core::option::Option<::windows::core::IUnknown>, cretelem: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(creqelem), ::core::mem::transmute(ppinterface), ::core::mem::transmute(cretelem)).ok()
}
pub unsafe fn Reset(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Skip(&self, cskipelem: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(cskipelem)).ok()
}
}
unsafe impl ::windows::core::Interface for IEnumEventObject {
type Vtable = IEnumEventObject_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf4a07d63_2e25_11d1_9964_00c04fbbb345);
}
impl ::core::convert::From<IEnumEventObject> for ::windows::core::IUnknown {
fn from(value: IEnumEventObject) -> Self {
value.0
}
}
impl ::core::convert::From<&IEnumEventObject> for ::windows::core::IUnknown {
fn from(value: &IEnumEventObject) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEnumEventObject {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEnumEventObject {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEnumEventObject_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, ppinterface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, creqelem: u32, ppinterface: *mut ::windows::core::RawPtr, cretelem: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cskipelem: u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventClass(pub ::windows::core::IUnknown);
impl IEventClass {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn EventClassID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetEventClassID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstreventclassid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstreventclassid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn EventClassName(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetEventClassName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstreventclassname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), bstreventclassname.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn OwnerSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetOwnerSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrownersid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), bstrownersid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn FiringInterfaceID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetFiringInterfaceID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrfiringinterfaceid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), bstrfiringinterfaceid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Description(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetDescription<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrdescription: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), bstrdescription.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn CustomConfigCLSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetCustomConfigCLSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrcustomconfigclsid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), bstrcustomconfigclsid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn TypeLib(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetTypeLib<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrtypelib: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), bstrtypelib.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IEventClass {
type Vtable = IEventClass_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb2b72a0_7a68_11d1_88f9_0080c7d771bf);
}
impl ::core::convert::From<IEventClass> for ::windows::core::IUnknown {
fn from(value: IEventClass) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventClass> for ::windows::core::IUnknown {
fn from(value: &IEventClass) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventClass {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventClass {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventClass> for super::IDispatch {
fn from(value: IEventClass) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventClass> for super::IDispatch {
fn from(value: &IEventClass) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventClass {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventClass {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventClass_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstreventclassid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstreventclassid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstreventclassname: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstreventclassname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrownersid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrownersid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrfiringinterfaceid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrfiringinterfaceid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrdescription: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrdescription: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrcustomconfigclsid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrcustomconfigclsid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrtypelib: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrtypelib: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventClass2(pub ::windows::core::IUnknown);
impl IEventClass2 {
pub unsafe fn GetTypeInfoCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetTypeInfo(&self, itinfo: u32, lcid: u32) -> ::windows::core::Result<super::ITypeInfo> {
let mut result__: <super::ITypeInfo as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(itinfo), ::core::mem::transmute(lcid), &mut result__).from_abi::<super::ITypeInfo>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetIDsOfNames(&self, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(riid), ::core::mem::transmute(rgsznames), ::core::mem::transmute(cnames), ::core::mem::transmute(lcid), ::core::mem::transmute(rgdispid)).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn Invoke(&self, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut super::VARIANT, pexcepinfo: *mut super::EXCEPINFO, puargerr: *mut u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(
::core::mem::transmute_copy(self),
::core::mem::transmute(dispidmember),
::core::mem::transmute(riid),
::core::mem::transmute(lcid),
::core::mem::transmute(wflags),
::core::mem::transmute(pdispparams),
::core::mem::transmute(pvarresult),
::core::mem::transmute(pexcepinfo),
::core::mem::transmute(puargerr),
)
.ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn EventClassID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetEventClassID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstreventclassid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstreventclassid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn EventClassName(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetEventClassName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstreventclassname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), bstreventclassname.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn OwnerSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetOwnerSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrownersid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), bstrownersid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn FiringInterfaceID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetFiringInterfaceID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrfiringinterfaceid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), bstrfiringinterfaceid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Description(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetDescription<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrdescription: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), bstrdescription.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn CustomConfigCLSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetCustomConfigCLSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrcustomconfigclsid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), bstrcustomconfigclsid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn TypeLib(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetTypeLib<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrtypelib: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), bstrtypelib.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PublisherID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetPublisherID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpublisherid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), bstrpublisherid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn MultiInterfacePublisherFilterCLSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetMultiInterfacePublisherFilterCLSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpubfilclsid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), bstrpubfilclsid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn AllowInprocActivation(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetAllowInprocActivation<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, fallowinprocactivation: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), fallowinprocactivation.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn FireInParallel(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetFireInParallel<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, ffireinparallel: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self), ffireinparallel.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IEventClass2 {
type Vtable = IEventClass2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfb2b72a1_7a68_11d1_88f9_0080c7d771bf);
}
impl ::core::convert::From<IEventClass2> for ::windows::core::IUnknown {
fn from(value: IEventClass2) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventClass2> for ::windows::core::IUnknown {
fn from(value: &IEventClass2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventClass2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventClass2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventClass2> for IEventClass {
fn from(value: IEventClass2) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventClass2> for IEventClass {
fn from(value: &IEventClass2) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IEventClass> for IEventClass2 {
fn into_param(self) -> ::windows::core::Param<'a, IEventClass> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IEventClass> for &IEventClass2 {
fn into_param(self) -> ::windows::core::Param<'a, IEventClass> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
impl ::core::convert::From<IEventClass2> for super::IDispatch {
fn from(value: IEventClass2) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventClass2> for super::IDispatch {
fn from(value: &IEventClass2) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventClass2 {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventClass2 {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventClass2_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstreventclassid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstreventclassid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstreventclassname: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstreventclassname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrownersid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrownersid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrfiringinterfaceid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrfiringinterfaceid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrdescription: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrdescription: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrcustomconfigclsid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrcustomconfigclsid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrtypelib: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrtypelib: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpublisherid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpublisherid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpubfilclsid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpubfilclsid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfallowinprocactivation: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fallowinprocactivation: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pffireinparallel: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ffireinparallel: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventControl(pub ::windows::core::IUnknown);
impl IEventControl {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetPublisherFilter<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, IPublisherFilter>>(&self, methodname: Param0, ppublisherfilter: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), methodname.into_param().abi(), ppublisherfilter.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn AllowInprocActivation(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetAllowInprocActivation<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, fallowinprocactivation: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), fallowinprocactivation.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetSubscriptions<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, methodname: Param0, optionalcriteria: Param1, optionalerrorindex: *const i32) -> ::windows::core::Result<IEventObjectCollection> {
let mut result__: <IEventObjectCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), methodname.into_param().abi(), optionalcriteria.into_param().abi(), ::core::mem::transmute(optionalerrorindex), &mut result__).from_abi::<IEventObjectCollection>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetDefaultQuery<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, methodname: Param0, criteria: Param1) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), methodname.into_param().abi(), criteria.into_param().abi(), &mut result__).from_abi::<i32>(result__)
}
}
unsafe impl ::windows::core::Interface for IEventControl {
type Vtable = IEventControl_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0343e2f4_86f6_11d1_b760_00c04fb926af);
}
impl ::core::convert::From<IEventControl> for ::windows::core::IUnknown {
fn from(value: IEventControl) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventControl> for ::windows::core::IUnknown {
fn from(value: &IEventControl) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventControl> for super::IDispatch {
fn from(value: IEventControl) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventControl> for super::IDispatch {
fn from(value: &IEventControl) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventControl {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventControl {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventControl_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, methodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, ppublisherfilter: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfallowinprocactivation: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fallowinprocactivation: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, methodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, optionalcriteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, optionalerrorindex: *const i32, ppcollection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, methodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, criteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, errorindex: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventObjectChange(pub ::windows::core::IUnknown);
impl IEventObjectChange {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ChangedSubscription<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, changetype: EOC_ChangeType, bstrsubscriptionid: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(changetype), bstrsubscriptionid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ChangedEventClass<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, changetype: EOC_ChangeType, bstreventclassid: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(changetype), bstreventclassid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ChangedPublisher<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, changetype: EOC_ChangeType, bstrpublisherid: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(changetype), bstrpublisherid.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IEventObjectChange {
type Vtable = IEventObjectChange_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf4a07d70_2e25_11d1_9964_00c04fbbb345);
}
impl ::core::convert::From<IEventObjectChange> for ::windows::core::IUnknown {
fn from(value: IEventObjectChange) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventObjectChange> for ::windows::core::IUnknown {
fn from(value: &IEventObjectChange) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventObjectChange {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventObjectChange {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventObjectChange_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, changetype: EOC_ChangeType, bstrsubscriptionid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, changetype: EOC_ChangeType, bstreventclassid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, changetype: EOC_ChangeType, bstrpublisherid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventObjectChange2(pub ::windows::core::IUnknown);
impl IEventObjectChange2 {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ChangedSubscription(&self, pinfo: *const COMEVENTSYSCHANGEINFO) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pinfo)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ChangedEventClass(&self, pinfo: *const COMEVENTSYSCHANGEINFO) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pinfo)).ok()
}
}
unsafe impl ::windows::core::Interface for IEventObjectChange2 {
type Vtable = IEventObjectChange2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7701a9c3_bd68_438f_83e0_67bf4f53a422);
}
impl ::core::convert::From<IEventObjectChange2> for ::windows::core::IUnknown {
fn from(value: IEventObjectChange2) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventObjectChange2> for ::windows::core::IUnknown {
fn from(value: &IEventObjectChange2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventObjectChange2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventObjectChange2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventObjectChange2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pinfo: *const ::core::mem::ManuallyDrop<COMEVENTSYSCHANGEINFO>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pinfo: *const ::core::mem::ManuallyDrop<COMEVENTSYSCHANGEINFO>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventObjectCollection(pub ::windows::core::IUnknown);
impl IEventObjectCollection {
pub unsafe fn _NewEnum(&self) -> ::windows::core::Result<::windows::core::IUnknown> {
let mut result__: <::windows::core::IUnknown as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn Item<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, objectid: Param0) -> ::windows::core::Result<super::VARIANT> {
let mut result__: <super::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), objectid.into_param().abi(), &mut result__).from_abi::<super::VARIANT>(result__)
}
pub unsafe fn NewEnum(&self) -> ::windows::core::Result<IEnumEventObject> {
let mut result__: <IEnumEventObject as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEnumEventObject>(result__)
}
pub unsafe fn Count(&self) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn Add<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, item: *const super::VARIANT, objectid: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(item), objectid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Remove<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, objectid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), objectid.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IEventObjectCollection {
type Vtable = IEventObjectCollection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf89ac270_d4eb_11d1_b682_00805fc79216);
}
impl ::core::convert::From<IEventObjectCollection> for ::windows::core::IUnknown {
fn from(value: IEventObjectCollection) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventObjectCollection> for ::windows::core::IUnknown {
fn from(value: &IEventObjectCollection) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventObjectCollection> for super::IDispatch {
fn from(value: IEventObjectCollection) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventObjectCollection> for super::IDispatch {
fn from(value: &IEventObjectCollection) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventObjectCollection_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppunkenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, objectid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, pitem: *mut ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenum: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcount: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, item: *const ::core::mem::ManuallyDrop<super::VARIANT>, objectid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, objectid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventProperty(pub ::windows::core::IUnknown);
impl IEventProperty {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Name(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, propertyname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), propertyname.into_param().abi()).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn Value(&self) -> ::windows::core::Result<super::VARIANT> {
let mut result__: <super::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::VARIANT>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn SetValue(&self, propertyvalue: *const super::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(propertyvalue)).ok()
}
}
unsafe impl ::windows::core::Interface for IEventProperty {
type Vtable = IEventProperty_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xda538ee2_f4de_11d1_b6bb_00805fc79216);
}
impl ::core::convert::From<IEventProperty> for ::windows::core::IUnknown {
fn from(value: IEventProperty) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventProperty> for ::windows::core::IUnknown {
fn from(value: &IEventProperty) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventProperty {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventProperty {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventProperty> for super::IDispatch {
fn from(value: IEventProperty) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventProperty> for super::IDispatch {
fn from(value: &IEventProperty) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventProperty {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventProperty {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventProperty_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propertyname: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propertyvalue: *mut ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propertyvalue: *const ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventPublisher(pub ::windows::core::IUnknown);
impl IEventPublisher {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PublisherID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetPublisherID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpublisherid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrpublisherid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PublisherName(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetPublisherName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpublishername: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), bstrpublishername.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PublisherType(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetPublisherType<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpublishertype: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), bstrpublishertype.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn OwnerSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetOwnerSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrownersid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), bstrownersid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Description(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetDescription<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrdescription: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), bstrdescription.into_param().abi()).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn GetDefaultProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0) -> ::windows::core::Result<super::VARIANT> {
let mut result__: <super::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi(), &mut result__).from_abi::<super::VARIANT>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn PutDefaultProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0, propertyvalue: *const super::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi(), ::core::mem::transmute(propertyvalue)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn RemoveDefaultProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi()).ok()
}
pub unsafe fn GetDefaultPropertyCollection(&self) -> ::windows::core::Result<IEventObjectCollection> {
let mut result__: <IEventObjectCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEventObjectCollection>(result__)
}
}
unsafe impl ::windows::core::Interface for IEventPublisher {
type Vtable = IEventPublisher_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe341516b_2e32_11d1_9964_00c04fbbb345);
}
impl ::core::convert::From<IEventPublisher> for ::windows::core::IUnknown {
fn from(value: IEventPublisher) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventPublisher> for ::windows::core::IUnknown {
fn from(value: &IEventPublisher) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventPublisher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventPublisher {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventPublisher> for super::IDispatch {
fn from(value: IEventPublisher) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventPublisher> for super::IDispatch {
fn from(value: &IEventPublisher) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventPublisher {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventPublisher {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventPublisher_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpublisherid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpublisherid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpublishername: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpublishername: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpublishertype: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpublishertype: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrownersid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrownersid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrdescription: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrdescription: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, propertyvalue: *mut ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, propertyvalue: *const ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, collection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventSubscription(pub ::windows::core::IUnknown);
impl IEventSubscription {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SubscriptionID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetSubscriptionID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrsubscriptionid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrsubscriptionid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SubscriptionName(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetSubscriptionName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrsubscriptionname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), bstrsubscriptionname.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PublisherID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetPublisherID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpublisherid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), bstrpublisherid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn EventClassID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetEventClassID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstreventclassid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), bstreventclassid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn MethodName(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetMethodName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrmethodname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), bstrmethodname.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SubscriberCLSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetSubscriberCLSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrsubscriberclsid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), bstrsubscriberclsid.into_param().abi()).ok()
}
pub unsafe fn SubscriberInterface(&self) -> ::windows::core::Result<::windows::core::IUnknown> {
let mut result__: <::windows::core::IUnknown as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
pub unsafe fn SetSubscriberInterface<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, psubscriberinterface: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), psubscriberinterface.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PerUser(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetPerUser<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, fperuser: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), fperuser.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn OwnerSID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetOwnerSID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrownersid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), bstrownersid.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Enabled(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetEnabled<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, fenabled: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), fenabled.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Description(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetDescription<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrdescription: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self), bstrdescription.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn MachineName(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).29)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetMachineName<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrmachinename: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).30)(::core::mem::transmute_copy(self), bstrmachinename.into_param().abi()).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn GetPublisherProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0) -> ::windows::core::Result<super::VARIANT> {
let mut result__: <super::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).31)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi(), &mut result__).from_abi::<super::VARIANT>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn PutPublisherProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0, propertyvalue: *const super::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).32)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi(), ::core::mem::transmute(propertyvalue)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn RemovePublisherProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).33)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi()).ok()
}
pub unsafe fn GetPublisherPropertyCollection(&self) -> ::windows::core::Result<IEventObjectCollection> {
let mut result__: <IEventObjectCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).34)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEventObjectCollection>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn GetSubscriberProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0) -> ::windows::core::Result<super::VARIANT> {
let mut result__: <super::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).35)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi(), &mut result__).from_abi::<super::VARIANT>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))]
pub unsafe fn PutSubscriberProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0, propertyvalue: *const super::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).36)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi(), ::core::mem::transmute(propertyvalue)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn RemoveSubscriberProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrpropertyname: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).37)(::core::mem::transmute_copy(self), bstrpropertyname.into_param().abi()).ok()
}
pub unsafe fn GetSubscriberPropertyCollection(&self) -> ::windows::core::Result<IEventObjectCollection> {
let mut result__: <IEventObjectCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).38)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IEventObjectCollection>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn InterfaceID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).39)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetInterfaceID<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, bstrinterfaceid: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).40)(::core::mem::transmute_copy(self), bstrinterfaceid.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IEventSubscription {
type Vtable = IEventSubscription_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4a6b0e15_2e38_11d1_9965_00c04fbbb345);
}
impl ::core::convert::From<IEventSubscription> for ::windows::core::IUnknown {
fn from(value: IEventSubscription) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventSubscription> for ::windows::core::IUnknown {
fn from(value: &IEventSubscription) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventSubscription {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventSubscription {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventSubscription> for super::IDispatch {
fn from(value: IEventSubscription) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventSubscription> for super::IDispatch {
fn from(value: &IEventSubscription) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventSubscription {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventSubscription {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventSubscription_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrsubscriptionid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrsubscriptionid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrsubscriptionname: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrsubscriptionname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrpublisherid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpublisherid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstreventclassid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstreventclassid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrmethodname: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrmethodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrsubscriberclsid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrsubscriberclsid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsubscriberinterface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psubscriberinterface: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfperuser: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fperuser: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrownersid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrownersid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfenabled: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fenabled: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrdescription: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrdescription: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrmachinename: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrmachinename: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, propertyvalue: *mut ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, propertyvalue: *const ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, collection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, propertyvalue: *mut ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, propertyvalue: *const ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrpropertyname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, collection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstrinterfaceid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrinterfaceid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IEventSystem(pub ::windows::core::IUnknown);
impl IEventSystem {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Query<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, progid: Param0, querycriteria: Param1, errorindex: *mut i32, ppinterface: *mut ::core::option::Option<::windows::core::IUnknown>) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), progid.into_param().abi(), querycriteria.into_param().abi(), ::core::mem::transmute(errorindex), ::core::mem::transmute(ppinterface)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Store<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, progid: Param0, pinterface: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), progid.into_param().abi(), pinterface.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Remove<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, progid: Param0, querycriteria: Param1) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), progid.into_param().abi(), querycriteria.into_param().abi(), &mut result__).from_abi::<i32>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn EventObjectChangeEventClassID(&self) -> ::windows::core::Result<super::super::super::Foundation::BSTR> {
let mut result__: <super::super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BSTR>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn QueryS<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, progid: Param0, querycriteria: Param1) -> ::windows::core::Result<::windows::core::IUnknown> {
let mut result__: <::windows::core::IUnknown as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), progid.into_param().abi(), querycriteria.into_param().abi(), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn RemoveS<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, progid: Param0, querycriteria: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), progid.into_param().abi(), querycriteria.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IEventSystem {
type Vtable = IEventSystem_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4e14fb9f_2e22_11d1_9964_00c04fbbb345);
}
impl ::core::convert::From<IEventSystem> for ::windows::core::IUnknown {
fn from(value: IEventSystem) -> Self {
value.0
}
}
impl ::core::convert::From<&IEventSystem> for ::windows::core::IUnknown {
fn from(value: &IEventSystem) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IEventSystem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IEventSystem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IEventSystem> for super::IDispatch {
fn from(value: IEventSystem) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IEventSystem> for super::IDispatch {
fn from(value: &IEventSystem) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IEventSystem {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IEventSystem {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IEventSystem_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, progid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, querycriteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, errorindex: *mut i32, ppinterface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, progid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, pinterface: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, progid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, querycriteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, errorindex: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbstreventclassid: *mut ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, progid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, querycriteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, ppinterface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, progid: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, querycriteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IFiringControl(pub ::windows::core::IUnknown);
impl IFiringControl {
pub unsafe fn FireSubscription<'a, Param0: ::windows::core::IntoParam<'a, IEventSubscription>>(&self, subscription: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), subscription.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IFiringControl {
type Vtable = IFiringControl_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0498c93_4efe_11d1_9971_00c04fbbb345);
}
impl ::core::convert::From<IFiringControl> for ::windows::core::IUnknown {
fn from(value: IFiringControl) -> Self {
value.0
}
}
impl ::core::convert::From<&IFiringControl> for ::windows::core::IUnknown {
fn from(value: &IFiringControl) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IFiringControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IFiringControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IFiringControl> for super::IDispatch {
fn from(value: IFiringControl) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IFiringControl> for super::IDispatch {
fn from(value: &IFiringControl) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for IFiringControl {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, super::IDispatch> for &IFiringControl {
fn into_param(self) -> ::windows::core::Param<'a, super::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IFiringControl_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, pctinfo: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const super::super::super::Foundation::PWSTR, cnames: u32, lcid: u32, rgdispid: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, subscription: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IMultiInterfaceEventControl(pub ::windows::core::IUnknown);
impl IMultiInterfaceEventControl {
pub unsafe fn SetMultiInterfacePublisherFilter<'a, Param0: ::windows::core::IntoParam<'a, IMultiInterfacePublisherFilter>>(&self, classfilter: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), classfilter.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetSubscriptions<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, eventiid: *const ::windows::core::GUID, bstrmethodname: Param1, optionalcriteria: Param2, optionalerrorindex: *const i32) -> ::windows::core::Result<IEventObjectCollection> {
let mut result__: <IEventObjectCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(eventiid), bstrmethodname.into_param().abi(), optionalcriteria.into_param().abi(), ::core::mem::transmute(optionalerrorindex), &mut result__).from_abi::<IEventObjectCollection>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetDefaultQuery<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>>(&self, eventiid: *const ::windows::core::GUID, bstrmethodname: Param1, bstrcriteria: Param2) -> ::windows::core::Result<i32> {
let mut result__: <i32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(eventiid), bstrmethodname.into_param().abi(), bstrcriteria.into_param().abi(), &mut result__).from_abi::<i32>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn AllowInprocActivation(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetAllowInprocActivation<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, fallowinprocactivation: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), fallowinprocactivation.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn FireInParallel(&self) -> ::windows::core::Result<super::super::super::Foundation::BOOL> {
let mut result__: <super::super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::BOOL>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SetFireInParallel<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, ffireinparallel: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ffireinparallel.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IMultiInterfaceEventControl {
type Vtable = IMultiInterfaceEventControl_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0343e2f5_86f6_11d1_b760_00c04fb926af);
}
impl ::core::convert::From<IMultiInterfaceEventControl> for ::windows::core::IUnknown {
fn from(value: IMultiInterfaceEventControl) -> Self {
value.0
}
}
impl ::core::convert::From<&IMultiInterfaceEventControl> for ::windows::core::IUnknown {
fn from(value: &IMultiInterfaceEventControl) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMultiInterfaceEventControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMultiInterfaceEventControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IMultiInterfaceEventControl_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, classfilter: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eventiid: *const ::windows::core::GUID, bstrmethodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, optionalcriteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, optionalerrorindex: *const i32, ppcollection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eventiid: *const ::windows::core::GUID, bstrmethodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, bstrcriteria: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, errorindex: *mut i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pfallowinprocactivation: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fallowinprocactivation: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pffireinparallel: *mut super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ffireinparallel: super::super::super::Foundation::BOOL) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IMultiInterfacePublisherFilter(pub ::windows::core::IUnknown);
impl IMultiInterfacePublisherFilter {
pub unsafe fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, IMultiInterfaceEventControl>>(&self, peic: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), peic.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PrepareToFire<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param2: ::windows::core::IntoParam<'a, IFiringControl>>(&self, iid: *const ::windows::core::GUID, methodname: Param1, firingcontrol: Param2) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(iid), methodname.into_param().abi(), firingcontrol.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IMultiInterfacePublisherFilter {
type Vtable = IMultiInterfacePublisherFilter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x465e5cc1_7b26_11d1_88fb_0080c7d771bf);
}
impl ::core::convert::From<IMultiInterfacePublisherFilter> for ::windows::core::IUnknown {
fn from(value: IMultiInterfacePublisherFilter) -> Self {
value.0
}
}
impl ::core::convert::From<&IMultiInterfacePublisherFilter> for ::windows::core::IUnknown {
fn from(value: &IMultiInterfacePublisherFilter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMultiInterfacePublisherFilter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IMultiInterfacePublisherFilter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IMultiInterfacePublisherFilter_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, peic: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: *const ::windows::core::GUID, methodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, firingcontrol: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IPublisherFilter(pub ::windows::core::IUnknown);
impl IPublisherFilter {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Initialize<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::IDispatch>>(&self, methodname: Param0, dispuserdefined: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), methodname.into_param().abi(), dispuserdefined.into_param().abi()).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn PrepareToFire<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, IFiringControl>>(&self, methodname: Param0, firingcontrol: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), methodname.into_param().abi(), firingcontrol.into_param().abi()).ok()
}
}
unsafe impl ::windows::core::Interface for IPublisherFilter {
type Vtable = IPublisherFilter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x465e5cc0_7b26_11d1_88fb_0080c7d771bf);
}
impl ::core::convert::From<IPublisherFilter> for ::windows::core::IUnknown {
fn from(value: IPublisherFilter) -> Self {
value.0
}
}
impl ::core::convert::From<&IPublisherFilter> for ::windows::core::IUnknown {
fn from(value: &IPublisherFilter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPublisherFilter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IPublisherFilter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IPublisherFilter_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, methodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, dispuserdefined: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, methodname: ::core::mem::ManuallyDrop<super::super::super::Foundation::BSTR>, firingcontrol: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
);
|
use crate::{Rectangle, Size};
use euclid::{vec2, point2, size2};
use std::num::Wrapping;
const LARGE_BUCKET: usize = 2;
const MEDIUM_BUCKET: usize = 1;
const SMALL_BUCKET: usize = 0;
const NUM_BUCKETS: usize = 3;
fn free_list_for_size(small_threshold: i32, large_threshold: i32, size: &Size) -> usize {
if size.width >= large_threshold || size.height >= large_threshold {
LARGE_BUCKET
} else if size.width >= small_threshold || size.height >= small_threshold {
MEDIUM_BUCKET
} else {
SMALL_BUCKET
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
struct AllocIndex(u32);
impl AllocIndex {
const NONE: AllocIndex = AllocIndex(std::u32::MAX);
fn index(self) -> usize {
self.0 as usize
}
fn is_none(self) -> bool {
self == AllocIndex::NONE
}
fn is_some(self) -> bool {
self != AllocIndex::NONE
}
}
/// ID referring to an allocated rectangle.
#[repr(C)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct AllocId(pub(crate) u32);
impl AllocId {
pub fn serialize(&self) -> u32 {
self.0
}
pub fn deserialize(bytes: u32) -> Self {
AllocId(bytes)
}
}
const GEN_MASK: u32 = 0xFF000000;
const IDX_MASK: u32 = 0x00FFFFFF;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum Orientation {
Vertical,
Horizontal,
}
impl Orientation {
fn flipped(self) -> Self {
match self {
Orientation::Vertical => Orientation::Horizontal,
Orientation::Horizontal => Orientation::Vertical,
}
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum NodeKind {
Container,
Alloc,
Free,
Unused,
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
struct Node {
parent: AllocIndex,
next_sibling: AllocIndex,
prev_sibling: AllocIndex,
kind: NodeKind,
orientation: Orientation,
rect: Rectangle,
}
/// Options to tweak the behavior of the atlas allocator.
#[repr(C)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct AllocatorOptions {
/// Round the rectangle sizes up to a multiple of this value.
///
/// Width and height alignments must be superior to zero.
///
/// Default value: (1, 1),
pub alignment: Size,
/// Value below which a size is considered small.
///
/// This is value is used to speed up the storage and lookup of free rectangles.
/// This value must be inferior or equal to `large_size_threshold`
///
/// Default value: 32,
pub small_size_threshold: i32,
/// Value above which a size is considered large.
///
/// This is value is used to speed up the storage and lookup of free rectangles.
/// This value must be inferior or equal to `large_size_threshold`
///
/// Default value: 256,
pub large_size_threshold: i32,
}
pub const DEFAULT_OPTIONS: AllocatorOptions = AllocatorOptions {
alignment: size2(1, 1),
large_size_threshold: 256,
small_size_threshold: 32,
};
impl Default for AllocatorOptions {
fn default() -> Self {
DEFAULT_OPTIONS
}
}
/// A dynamic texture atlas allocator using the guillotine algorithm.
///
/// The guillotine algorithm is assisted by a data structure that keeps track of
/// neighboring rectangles to provide fast deallocation and coalescing.
///
/// ## Goals
///
/// Coalescing free rectangles, in the context of dynamic atlas allocation can be
/// prohibitively expensive under real-time constraints if the algorithm needs to
/// visit a large amount of free rectangles to find merge candidates.
///
/// This implementation proposes a compromise with fast (constant time) search
/// for merge candidates at the expense of some (constant time) bookkeeping overhead
/// when allocating and removing rectangles and imperfect defragmentation (see the
/// "Limitations" section below.
///
/// The subdivision scheme uses the worst fit variant of the guillotine algorithm
/// for its simplicity and CPU efficiency.
///
/// ## The data structure
///
/// We maintain a tree with allocated and free rectangles as leaf nodes and
/// containers as non-leaf nodes.
///
/// The direct children of a Containers's form an ordered horizontal or vertical
/// sequence of rectangles that cover exactly their parent container's area.
///
/// For example, a subdivision such as this one:
///
/// ```ascii
/// +-----------+----------+---+---+--+---------+---+
/// | | | C | D |E | F | G |
/// | | +---+---+--+---------+---+
/// | A | B | |
/// | | | H |
/// | | | |
/// +------+----+----------+-+----------------------+
/// | | J | |
/// | I +-----------------+ L |
/// | | K | |
/// +------+-----------------+----------------------+
/// ```
///
/// Would have a tree of the form:
///
/// ```ascii
///
/// Tree | Layout
/// ---------------------+------------
/// |
/// # |
/// | |
/// +----+----+. . .|. vertical
/// | | |
/// # # |
/// | | |
/// +-+-+ . . +-+-+. .|. horizontal
/// | | | | | | |
/// A B # I # L |
/// | | |
/// +-+-+ . +-+-+. .|. vertical
/// | | | | |
/// # H J K |
/// | |
/// +-+-+-+-+. . . . . .|. horizontal
/// | | | | | |
/// C D E F G |
/// ```
///
/// Where container nodes are represented with "#".
///
/// Note that if a horizontal container is the direct child of another
/// horizontal container, we can merge the two into a single horizontal
/// sequence.
/// We use this property to always keep the tree in its simplest form.
/// In practice this means that the orientation of a container is always
/// the opposite of the orientation of its parent, if any.
///
/// The goal of this data structure is to quickly find neighboring free
/// rectangles that can be coalesced into fewer rectangles.
/// This structure guarantees that two consecutive children of the same
/// container, if both rectangles are free, can be coalesced into a single
/// one.
///
/// An important thing to note about this tree structure is that we only
/// use it to visit neighbor and parent nodes. As a result we don't care
/// about whether the tree is balanced, although flat sequences of children
/// tend to offer more opportunity for coalescing than deeply nested structures
/// Either way, the cost of finding potential merges is the same because
/// each node stores the indices of their siblings, and we never have to
/// traverse any global list of free rectangle nodes.
///
/// ### Merging siblings
///
/// As soon as two consecutive sibling nodes are marked as "free", they are coalesced
/// into a single node.
///
/// In the example below, we just deallocated the rectangle `B`, which is a sibling of
/// `A` which is free and `C` which is still allocated. `A` and `B` are merged and this
/// change is reflected on the tree as shown below:
///
/// ```ascii
/// +---+---+---+ # +-------+---+ #
/// | | |///| | | |///| |
/// | A | B |/C/| +---+---+ | AB |/C/| +---+---+
/// | | |///| | | | |///| | |
/// +---+---+---+ # D +-------+---+ # D
/// | D | | -> | D | |
/// | | +-+-+ | | +-+-+
/// | | | | | | | | |
/// +-----------+ A B C +-----------+ AB C
/// ```
///
/// ### Merging unique children with their parents
///
/// In the previous example `C` was an allocated slot. Let's now deallocate it:
///
/// ```ascii
/// +-------+---+ # +-----------+ # #
/// | | | | | | | |
/// | AB | C | +---+---+ | ABC | +---+---+ +---+---+
/// | | | | | | | | | | |
/// +-------+---+ # D +-----------+ # D ABC D
/// | D | | -> | D | | ->
/// | | +-+-+ | | +
/// | | | | | | |
/// +-----------+ AB C +-----------+ ABC
/// ```
///
/// Deallocating `C` allowed it to merge with the free rectangle `AB`, making the
/// resulting node `ABC` the only child of its parent container. As a result the
/// node `ABC` was lifted up the tree to replace its parent.
///
/// In this example, assuming `D` to also be a free rectangle, `ABC` and `D` would
/// be immediately merged and the resulting node `ABCD`, also being only child of
/// its parent container, would replace its parent, turning the tree into a single
/// node `ABCD`.
///
/// ### Limitations
///
/// This strategy can miss some opportunities for coalescing free rectangles
/// when the two sibling containers are split exactly the same way.
///
/// For example:
///
/// ```ascii
/// +---------+------+
/// | A | B |
/// | | |
/// +---------+------+
/// | C | D |
/// | | |
/// +---------+------+
/// ```
///
/// Could be the result of either a vertical followed with two horizontal splits,
/// or an horizontal then two vertical splits.
///
/// ```ascii
/// Tree | Layout Tree | Layout
/// -----------------+------------ -----------------+------------
/// # | # |
/// | | | |
/// +---+---+ . .|. Vertical +---+---+ . .|. Horizontal
/// | | | | | |
/// # # | or # # |
/// | | | | | |
/// +-+-+ . +-+-+ .|. Horizontal +-+-+ . +-+-+ .|. Vertical
/// | | | | | | | | | |
/// A B C D | A C B D |
/// ```
///
/// In the former case A can't be merged with C nor B with D because they are not siblings.
///
/// For a lot of workloads it is rather rare for two consecutive sibling containers to be
/// subdivided exactly the same way. In this situation losing the ability to merge rectangles
/// that aren't under the same container is good compromise between the CPU cost of coalescing
/// and the fragmentation of the atlas.
///
/// This algorithm is, however, not the best solution for very "structured" grid-like
/// subdivision patterns where the ability to merge across containers would have provided
/// frequent defragmentation opportunities.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone)]
pub struct AtlasAllocator {
nodes: Vec<Node>,
/// Free lists are split into a small a medium and a large bucket for faster lookups.
free_lists: [Vec<AllocIndex>; NUM_BUCKETS],
/// Index of the first element of an intrusive linked list of unused nodes.
/// The `next_sibling` member of unused node serves as the linked list link.
unused_nodes: AllocIndex,
/// We keep a per-node generation counter to reduce the likelihood of ID reuse bugs
/// going unnoticed.
generations: Vec<Wrapping<u8>>,
/// See `AllocatorOptions`.
alignment: Size,
/// See `AllocatorOptions`.
small_size_threshold: i32,
/// See `AllocatorOptions`.
large_size_threshold: i32,
/// Total size of the atlas.
size: Size,
/// Index of one of the top-level nodes in the tree.
root_node: AllocIndex,
}
// Some notes about the atlas's tree data structure:
//
// (AllocIndex::NONE) (AllocIndex::NONE)
// ^ ^
// | parent | parent
// +---------+ next sibling +---------+ next sibling
// ... ------|Container|---------------------->|Free |---> (AllocIndex::NONE)
// ----->| |<----------------------| |
// +---------+ previous sibling +---------+
// ^ ^
// | \____________________________
// | \
// | parent \ parent
// +---------+ next sibling +---------+ next sibling
// ... ------|Alloc |---------------------->|Container|---> (AllocIndex::NONE)
// ----->| |<----------------------| |
// +---------+ previous sibling +---------+
// ^ ^ ^
// / | \
// ...
//
// - Nodes are stored in a contiguous vector.
// - Links between the nodes are indices in the vector (AllocIndex), with a magic value
// AllocIndex::NONE that means no link.
// - Nodes have a link to their parent, but parents do not have a link to any of its children because
// we never need to traverse the structure from parent to child.
// - All nodes with the same parent are "siblings". An intrusive linked list allows traversing siblings
// in order. Consecutive siblings share an edge and can be merged if they are both "free".
// - There isn't necessarily a single root node. The top-most level of the tree can have several siblings
// and their parent index is equal to AllocIndex::NONE. AtlasAllocator::root_node only needs to refer
// to one of these top-level nodes.
// - After a rectangle has been deallocated, the slot for its node in the vector is not part of the
// tree anymore in the sense that no node from the tree points to it with its sibling list or parent
// index. This unused node is available for reuse in a future allocation, and is placed in another
// linked list (also using AllocIndex), a singly linked list this time, which reuses the next_sibling
// member of the node. So depending on whether the node kind is Unused or not, the next_sibling
// member is used different things.
// - We reuse nodes aggressively to avoid growing the vector whenever possible. This is important because
// the memory footprint of this data structure depends on the capacity of its vectors which don't
// get deallocated during the lifetime of the atlas.
// - Because nodes are aggressively reused, the same node indices will come up often. To avoid id reuse
// bugs, a parallel vector of generation counters is maintained.
// - The difference between AllocIndex and AllocId is that the latter embeds a generation ID to help
// finding id reuse bugs. AllocIndex however only contains the node offset. Internal links in the
// data structure use AllocIndex, and external users of the data structure only get to see AllocId.
impl AtlasAllocator {
/// Create an atlas allocator.
pub fn new(size: Size) -> Self {
AtlasAllocator::with_options(size, &DEFAULT_OPTIONS)
}
/// Create an atlas allocator with the provided options.
pub fn with_options(size: Size, options: &AllocatorOptions) -> Self {
assert!(options.alignment.width > 0);
assert!(options.alignment.height > 0);
assert!(size.width > 0);
assert!(size.height > 0);
assert!(options.large_size_threshold >= options.small_size_threshold);
let mut free_lists = [Vec::new(), Vec::new(), Vec::new()];
let bucket = free_list_for_size(
options.small_size_threshold,
options.large_size_threshold,
&size,
);
free_lists[bucket].push(AllocIndex(0));
AtlasAllocator {
nodes: vec![Node {
parent: AllocIndex::NONE,
next_sibling: AllocIndex::NONE,
prev_sibling: AllocIndex::NONE,
rect: size.into(),
kind: NodeKind::Free,
orientation: Orientation::Vertical,
}],
free_lists,
generations: vec![Wrapping(0)],
unused_nodes: AllocIndex::NONE,
alignment: options.alignment,
small_size_threshold: options.small_size_threshold,
large_size_threshold: options.large_size_threshold,
size,
root_node: AllocIndex(0),
}
}
/// The total size of the atlas.
pub fn size(&self) -> Size {
self.size
}
/// Allocate a rectangle in the atlas.
pub fn allocate(&mut self, mut requested_size: Size) -> Option<Allocation> {
if requested_size.is_empty() {
return None;
}
adjust_size(self.alignment.width, &mut requested_size.width);
adjust_size(self.alignment.height, &mut requested_size.height);
// Find a suitable free rect.
let chosen_id = self.find_suitable_rect(&requested_size);
if chosen_id.is_none() {
//println!("failed to allocate {:?}", requested_size);
//self.print_free_rects();
// No suitable free rect!
return None;
}
let chosen_node = self.nodes[chosen_id.index()].clone();
let chosen_rect = chosen_node.rect;
let allocated_rect = Rectangle {
min: chosen_rect.min,
max: chosen_rect.min + requested_size.to_vector(),
};
let current_orientation = chosen_node.orientation;
assert_eq!(chosen_node.kind, NodeKind::Free);
let (split_rect, leftover_rect, orientation) =
guillotine_rect(&chosen_node.rect, requested_size, current_orientation);
// Update the tree.
let allocated_id;
let split_id;
let leftover_id;
//println!("{:?} -> {:?}", current_orientation, orientation);
if orientation == current_orientation {
if !split_rect.is_empty() {
let next_sibling = chosen_node.next_sibling;
split_id = self.new_node();
self.nodes[split_id.index()] = Node {
parent: chosen_node.parent,
next_sibling,
prev_sibling: chosen_id,
rect: split_rect,
kind: NodeKind::Free,
orientation: current_orientation,
};
self.nodes[chosen_id.index()].next_sibling = split_id;
if next_sibling.is_some() {
self.nodes[next_sibling.index()].prev_sibling = split_id;
}
} else {
split_id = AllocIndex::NONE;
}
if !leftover_rect.is_empty() {
self.nodes[chosen_id.index()].kind = NodeKind::Container;
allocated_id = self.new_node();
leftover_id = self.new_node();
self.nodes[allocated_id.index()] = Node {
parent: chosen_id,
next_sibling: leftover_id,
prev_sibling: AllocIndex::NONE,
rect: allocated_rect,
kind: NodeKind::Alloc,
orientation: current_orientation.flipped(),
};
self.nodes[leftover_id.index()] = Node {
parent: chosen_id,
next_sibling: AllocIndex::NONE,
prev_sibling: allocated_id,
rect: leftover_rect,
kind: NodeKind::Free,
orientation: current_orientation.flipped(),
};
} else {
// No need to split for the leftover area, we can allocate directly in the chosen node.
allocated_id = chosen_id;
let node = &mut self.nodes[chosen_id.index()];
node.kind = NodeKind::Alloc;
node.rect = allocated_rect;
leftover_id = AllocIndex::NONE
}
} else {
self.nodes[chosen_id.index()].kind = NodeKind::Container;
if !split_rect.is_empty() {
split_id = self.new_node();
self.nodes[split_id.index()] = Node {
parent: chosen_id,
next_sibling: AllocIndex::NONE,
prev_sibling: AllocIndex::NONE,
rect: split_rect,
kind: NodeKind::Free,
orientation: current_orientation.flipped(),
};
} else {
split_id = AllocIndex::NONE;
}
if !leftover_rect.is_empty() {
let container_id = self.new_node();
self.nodes[container_id.index()] = Node {
parent: chosen_id,
next_sibling: split_id,
prev_sibling: AllocIndex::NONE,
rect: Rectangle::zero(),
kind: NodeKind::Container,
orientation: current_orientation.flipped(),
};
self.nodes[split_id.index()].prev_sibling = container_id;
allocated_id = self.new_node();
leftover_id = self.new_node();
self.nodes[allocated_id.index()] = Node {
parent: container_id,
next_sibling: leftover_id,
prev_sibling: AllocIndex::NONE,
rect: allocated_rect,
kind: NodeKind::Alloc,
orientation: current_orientation,
};
self.nodes[leftover_id.index()] = Node {
parent: container_id,
next_sibling: AllocIndex::NONE,
prev_sibling: allocated_id,
rect: leftover_rect,
kind: NodeKind::Free,
orientation: current_orientation,
};
} else {
allocated_id = self.new_node();
self.nodes[allocated_id.index()] = Node {
parent: chosen_id,
next_sibling: split_id,
prev_sibling: AllocIndex::NONE,
rect: allocated_rect,
kind: NodeKind::Alloc,
orientation: current_orientation.flipped(),
};
self.nodes[split_id.index()].prev_sibling = allocated_id;
leftover_id = AllocIndex::NONE;
}
}
assert_eq!(self.nodes[allocated_id.index()].kind, NodeKind::Alloc);
if split_id.is_some() {
self.add_free_rect(split_id, &split_rect.size());
}
if leftover_id.is_some() {
self.add_free_rect(leftover_id, &leftover_rect.size());
}
//println!("allocated {:?} split: {:?} leftover: {:?}", allocated_rect, split_rect, leftover_rect);
//self.print_free_rects();
#[cfg(feature = "checks")]
self.check_tree();
Some(Allocation {
id: self.alloc_id(allocated_id),
rectangle: allocated_rect,
})
}
/// Deallocate a rectangle in the atlas.
pub fn deallocate(&mut self, node_id: AllocId) {
let mut node_id = self.get_index(node_id);
assert!(node_id.index() < self.nodes.len());
assert_eq!(self.nodes[node_id.index()].kind, NodeKind::Alloc);
self.nodes[node_id.index()].kind = NodeKind::Free;
loop {
let orientation = self.nodes[node_id.index()].orientation;
let next = self.nodes[node_id.index()].next_sibling;
let prev = self.nodes[node_id.index()].prev_sibling;
// Try to merge with the next node.
if next.is_some() && self.nodes[next.index()].kind == NodeKind::Free {
self.merge_siblings(node_id, next, orientation);
}
// Try to merge with the previous node.
if prev.is_some() && self.nodes[prev.index()].kind == NodeKind::Free {
self.merge_siblings(prev, node_id, orientation);
node_id = prev;
}
// If this node is now a unique child. We collapse it into its parent and try to merge
// again at the parent level.
let parent = self.nodes[node_id.index()].parent;
if self.nodes[node_id.index()].prev_sibling.is_none()
&& self.nodes[node_id.index()].next_sibling.is_none()
&& parent.is_some()
{
debug_assert_eq!(self.nodes[parent.index()].kind, NodeKind::Container);
self.mark_node_unused(node_id);
// Replace the parent container with a free node.
self.nodes[parent.index()].rect = self.nodes[node_id.index()].rect;
self.nodes[parent.index()].kind = NodeKind::Free;
// Start again at the parent level.
node_id = parent;
} else {
let size = self.nodes[node_id.index()].rect.size();
self.add_free_rect(node_id, &size);
break;
}
}
#[cfg(feature = "checks")]
self.check_tree();
}
pub fn is_empty(&self) -> bool {
let root = &self.nodes[self.root_node.index()];
root.kind == NodeKind::Free && root.next_sibling.is_none()
}
/// Drop all rectangles, clearing the atlas to its initial state.
pub fn clear(&mut self) {
self.nodes.clear();
self.nodes.push(Node {
parent: AllocIndex::NONE,
next_sibling: AllocIndex::NONE,
prev_sibling: AllocIndex::NONE,
rect: self.size.into(),
kind: NodeKind::Free,
orientation: Orientation::Vertical,
});
self.root_node = AllocIndex(0);
self.generations.clear();
self.generations.push(Wrapping(0));
self.unused_nodes = AllocIndex::NONE;
let bucket = free_list_for_size(
self.small_size_threshold,
self.large_size_threshold,
&self.size,
);
for i in 0..NUM_BUCKETS {
self.free_lists[i].clear();
}
self.free_lists[bucket].push(AllocIndex(0));
}
/// Clear the allocator and reset its size and options.
pub fn reset(&mut self, size: Size, options: &AllocatorOptions) {
self.alignment = options.alignment;
self.small_size_threshold = options.small_size_threshold;
self.large_size_threshold = options.large_size_threshold;
self.size = size;
self.clear();
}
/// Recompute the allocations in the atlas and returns a list of the changes.
///
/// Previous ids and rectangles are not valid anymore after this operation as each id/rectangle
/// pair is assigned to new values which are communicated in the returned change list.
/// Rearranging the atlas can help reduce fragmentation.
pub fn rearrange(&mut self) -> ChangeList {
let size = self.size;
self.resize_and_rearrange(size)
}
/// Identical to `AtlasAllocator::rearrange`, also allowing to change the size of the atlas.
pub fn resize_and_rearrange(&mut self, new_size: Size) -> ChangeList {
let mut allocs = Vec::with_capacity(self.nodes.len());
for (i, node) in self.nodes.iter().enumerate() {
if node.kind != NodeKind::Alloc {
continue;
}
let id = self.alloc_id(AllocIndex(i as u32));
allocs.push(Allocation {
id,
rectangle: node.rect,
});
}
allocs.sort_by_key(|alloc| safe_area(&alloc.rectangle));
allocs.reverse();
self.size = new_size;
self.clear();
let mut changes = Vec::new();
let mut failures = Vec::new();
for old in allocs {
let size = old.rectangle.size();
if let Some(new) = self.allocate(size) {
changes.push(Change { old, new });
} else {
failures.push(old);
}
}
ChangeList { changes, failures }
}
/// Resize the atlas without changing the allocations.
///
/// This method is not allowed to shrink the width or height of the atlas.
pub fn grow(&mut self, new_size: Size) {
assert!(new_size.width >= self.size.width);
assert!(new_size.height >= self.size.height);
let old_size = self.size;
self.size = new_size;
let dx = new_size.width - old_size.width;
let dy = new_size.height - old_size.height;
// If there is only one node and it is free, just grow it.
let root = &mut self.nodes[self.root_node.index()];
if root.kind == NodeKind::Free && root.rect.size() == old_size {
root.rect.max = root.rect.min + new_size.to_vector();
return;
}
let root_orientation = root.orientation;
let grows_in_root_orientation = match root_orientation {
Orientation::Horizontal => dx > 0,
Orientation::Vertical => dy > 0,
};
// If growing along the orientation of the root node, find the right-or-bottom-most sibling
// and either grow it (if it is free) or append a free node next.
if grows_in_root_orientation {
let mut sibling = self.root_node;
while self.nodes[sibling.index()].next_sibling != AllocIndex::NONE {
sibling = self.nodes[sibling.index()].next_sibling;
}
let node = &mut self.nodes[sibling.index()];
if node.kind == NodeKind::Free {
node.rect.max += match root_orientation {
Orientation::Horizontal => vec2(dx, 0),
Orientation::Vertical => vec2(0, dy),
};
} else {
let rect = match root_orientation {
Orientation::Horizontal => {
let min = point2(node.rect.max.x, node.rect.min.y);
let max = min + vec2(dx, node.rect.height());
Rectangle { min, max }
}
Orientation::Vertical => {
let min = point2(node.rect.min.x, node.rect.max.y);
let max = min + vec2(node.rect.width(), dy);
Rectangle { min, max }
}
};
let next = self.new_node();
self.nodes[sibling.index()].next_sibling = next;
self.nodes[next.index()] = Node {
kind: NodeKind::Free,
rect,
prev_sibling: sibling,
next_sibling: AllocIndex::NONE,
parent: AllocIndex::NONE,
orientation: root_orientation,
};
self.add_free_rect(next, &rect.size());
}
}
let grows_in_opposite_orientation = match root_orientation {
Orientation::Horizontal => dy > 0,
Orientation::Vertical => dx > 0,
};
if grows_in_opposite_orientation {
let free_node = self.new_node();
let new_root = self.new_node();
let old_root = self.root_node;
self.root_node = new_root;
let new_root_orientation = root_orientation.flipped();
let min = match new_root_orientation {
Orientation::Horizontal => point2(old_size.width, 0),
Orientation::Vertical => point2(0, old_size.height),
};
let max = point2(new_size.width, new_size.height);
let rect = Rectangle { min, max };
self.nodes[free_node.index()] = Node {
parent: AllocIndex::NONE,
prev_sibling: new_root,
next_sibling: AllocIndex::NONE,
kind: NodeKind::Free,
rect,
orientation: new_root_orientation,
};
self.nodes[new_root.index()] = Node {
parent: AllocIndex::NONE,
prev_sibling: AllocIndex::NONE,
next_sibling: free_node,
kind: NodeKind::Container,
rect: Rectangle::zero(),
orientation: new_root_orientation,
};
self.add_free_rect(free_node, &rect.size());
// Update the nodes that need to be re-parented to the new-root.
let mut iter = old_root;
while iter != AllocIndex::NONE {
self.nodes[iter.index()].parent = new_root;
iter = self.nodes[iter.index()].next_sibling;
}
// That second loop might not be necessary, I think that the root is always the first
// sibling.
let mut iter = self.nodes[old_root.index()].next_sibling;
while iter != AllocIndex::NONE {
self.nodes[iter.index()].parent = new_root;
iter = self.nodes[iter.index()].prev_sibling;
}
}
#[cfg(feature = "checks")]
self.check_tree();
}
/// Invoke a callback for each free rectangle in the atlas.
pub fn for_each_free_rectangle<F>(&self, mut callback: F)
where
F: FnMut(&Rectangle),
{
for node in &self.nodes {
if node.kind == NodeKind::Free {
callback(&node.rect);
}
}
}
/// Invoke a callback for each allocated rectangle in the atlas.
pub fn for_each_allocated_rectangle<F>(&self, mut callback: F)
where
F: FnMut(AllocId, &Rectangle),
{
for (i, node) in self.nodes.iter().enumerate() {
if node.kind != NodeKind::Alloc {
continue;
}
let id = self.alloc_id(AllocIndex(i as u32));
callback(id, &node.rect);
}
}
fn find_suitable_rect(&mut self, requested_size: &Size) -> AllocIndex {
let ideal_bucket = free_list_for_size(
self.small_size_threshold,
self.large_size_threshold,
requested_size,
);
let use_worst_fit = ideal_bucket == LARGE_BUCKET;
for bucket in ideal_bucket..NUM_BUCKETS {
let mut candidate_score = if use_worst_fit { 0 } else { std::i32::MAX };
let mut candidate = None;
let mut freelist_idx = 0;
while freelist_idx < self.free_lists[bucket].len() {
let id = self.free_lists[bucket][freelist_idx];
// During tree simplification we don't remove merged nodes from the free list, so we have
// to handle it here.
// This is a tad awkward, but lets us avoid having to maintain a doubly linked list for
// the free list (which would be needed to remove nodes during tree simplification).
if self.nodes[id.index()].kind != NodeKind::Free {
// remove the element from the free list
self.free_lists[bucket].swap_remove(freelist_idx);
continue;
}
let size = self.nodes[id.index()].rect.size();
let dx = size.width - requested_size.width;
let dy = size.height - requested_size.height;
if dx >= 0 && dy >= 0 {
if dx == 0 || dy == 0 {
// Perfect fit!
candidate = Some((id, freelist_idx));
break;
}
// Favor the largest minimum dimension, except for small
// allocations.
let score = i32::min(dx, dy);
if (use_worst_fit && score > candidate_score)
|| (!use_worst_fit && score < candidate_score)
{
candidate_score = score;
candidate = Some((id, freelist_idx));
}
}
freelist_idx += 1;
}
if let Some((id, freelist_idx)) = candidate {
self.free_lists[bucket].swap_remove(freelist_idx);
return id;
}
}
AllocIndex::NONE
}
fn new_node(&mut self) -> AllocIndex {
let idx = self.unused_nodes;
if idx.index() < self.nodes.len() {
self.unused_nodes = self.nodes[idx.index()].next_sibling;
self.generations[idx.index()] += Wrapping(1);
debug_assert_eq!(self.nodes[idx.index()].kind, NodeKind::Unused);
return idx;
}
self.nodes.push(Node {
parent: AllocIndex::NONE,
next_sibling: AllocIndex::NONE,
prev_sibling: AllocIndex::NONE,
rect: Rectangle::zero(),
kind: NodeKind::Unused,
orientation: Orientation::Horizontal,
});
self.generations.push(Wrapping(0));
AllocIndex(self.nodes.len() as u32 - 1)
}
fn mark_node_unused(&mut self, id: AllocIndex) {
debug_assert!(self.nodes[id.index()].kind != NodeKind::Unused);
self.nodes[id.index()].kind = NodeKind::Unused;
self.nodes[id.index()].next_sibling = self.unused_nodes;
self.unused_nodes = id;
}
#[allow(dead_code)]
fn print_free_rects(&self) {
println!("Large:");
for &id in &self.free_lists[LARGE_BUCKET] {
if self.nodes[id.index()].kind == NodeKind::Free {
println!(" - {:?} #{:?}", self.nodes[id.index()].rect, id);
}
}
println!("Medium:");
for &id in &self.free_lists[MEDIUM_BUCKET] {
if self.nodes[id.index()].kind == NodeKind::Free {
println!(" - {:?} #{:?}", self.nodes[id.index()].rect, id);
}
}
println!("Small:");
for &id in &self.free_lists[SMALL_BUCKET] {
if self.nodes[id.index()].kind == NodeKind::Free {
println!(" - {:?} #{:?}", self.nodes[id.index()].rect, id);
}
}
}
#[cfg(feature = "checks")]
fn check_siblings(&self, id: AllocIndex, next: AllocIndex, orientation: Orientation) {
if next.is_none() {
return;
}
if self.nodes[next.index()].prev_sibling != id {
panic!("error: #{:?}'s next sibling #{:?} has prev sibling #{:?}", id, next, self.nodes[next.index()].prev_sibling);
}
assert_eq!(self.nodes[next.index()].prev_sibling, id);
match self.nodes[id.index()].kind {
NodeKind::Container | NodeKind::Unused => {
return;
}
_ => {}
}
match self.nodes[next.index()].kind {
NodeKind::Container | NodeKind::Unused => {
return;
}
_ => {}
}
let r1 = self.nodes[id.index()].rect;
let r2 = self.nodes[next.index()].rect;
match orientation {
Orientation::Horizontal => {
assert_eq!(r1.min.y, r2.min.y);
assert_eq!(r1.max.y, r2.max.y);
}
Orientation::Vertical => {
assert_eq!(r1.min.x, r2.min.x);
assert_eq!(r1.max.x, r2.max.x);
}
}
}
#[cfg(feature = "checks")]
fn check_tree(&self) {
for node_idx in 0..self.nodes.len() {
let node = &self.nodes[node_idx];
if node.kind == NodeKind::Unused {
if node.next_sibling.is_some() {
assert_eq!(self.nodes[node.next_sibling.index()].kind, NodeKind::Unused);
}
continue;
}
let mut iter = node.next_sibling;
while iter.is_some() {
assert_eq!(self.nodes[iter.index()].orientation, node.orientation);
assert_eq!(self.nodes[iter.index()].parent, node.parent);
assert!(self.nodes[iter.index()].kind != NodeKind::Unused);
let next = self.nodes[iter.index()].next_sibling;
#[cfg(feature = "checks")]
self.check_siblings(iter, next, node.orientation);
iter = next;
}
if node.parent.is_some() {
if self.nodes[node.parent.index()].kind != NodeKind::Container {
panic!("error: child: {:?} parent: {:?}", node_idx, node.parent);
}
assert_eq!(
self.nodes[node.parent.index()].orientation,
node.orientation.flipped()
);
assert_eq!(self.nodes[node.parent.index()].kind, NodeKind::Container);
}
}
}
fn add_free_rect(&mut self, id: AllocIndex, size: &Size) {
debug_assert_eq!(self.nodes[id.index()].kind, NodeKind::Free);
let bucket = free_list_for_size(self.small_size_threshold, self.large_size_threshold, size);
//println!("add free rect #{:?} size {} bucket {}", id, size, bucket);
self.free_lists[bucket].push(id);
}
// Merge `next` into `node` and append `next` to a list of available `nodes`vector slots.
fn merge_siblings(&mut self, node: AllocIndex, next: AllocIndex, orientation: Orientation) {
debug_assert_eq!(self.nodes[node.index()].kind, NodeKind::Free);
debug_assert_eq!(self.nodes[next.index()].kind, NodeKind::Free);
let r1 = self.nodes[node.index()].rect;
let r2 = self.nodes[next.index()].rect;
//println!("merge {} #{:?} and {} #{:?} {:?}", r1, node, r2, next, orientation);
let merge_size = self.nodes[next.index()].rect.size();
match orientation {
Orientation::Horizontal => {
debug_assert_eq!(r1.min.y, r2.min.y);
debug_assert_eq!(r1.max.y, r2.max.y);
self.nodes[node.index()].rect.max.x += merge_size.width;
}
Orientation::Vertical => {
debug_assert_eq!(r1.min.x, r2.min.x);
debug_assert_eq!(r1.max.x, r2.max.x);
self.nodes[node.index()].rect.max.y += merge_size.height;
}
}
// Remove the merged node from the sibling list.
let next_next = self.nodes[next.index()].next_sibling;
self.nodes[node.index()].next_sibling = next_next;
if next_next.is_some() {
self.nodes[next_next.index()].prev_sibling = node;
}
// Add the merged node to the list of available slots in the nodes vector.
self.mark_node_unused(next);
}
fn alloc_id(&self, index: AllocIndex) -> AllocId {
let generation = self.generations[index.index()].0 as u32;
debug_assert!(index.0 & IDX_MASK == index.0);
AllocId(index.0 + (generation << 24))
}
fn get_index(&self, id: AllocId) -> AllocIndex {
let idx = id.0 & IDX_MASK;
let expected_generation = (self.generations[idx as usize].0 as u32) << 24;
assert_eq!(id.0 & GEN_MASK, expected_generation);
AllocIndex(idx)
}
}
impl std::ops::Index<AllocId> for AtlasAllocator {
type Output = Rectangle;
fn index(&self, index: AllocId) -> &Rectangle {
let idx = self.get_index(index);
&self.nodes[idx.index()].rect
}
}
/// A simpler atlas allocator implementation that can allocate rectangles but not deallocate them.
pub struct SimpleAtlasAllocator {
free_rects: [Vec<Rectangle>; 3],
alignment: Size,
small_size_threshold: i32,
large_size_threshold: i32,
size: Size,
}
impl SimpleAtlasAllocator {
/// Create a simple atlas allocator with default options.
pub fn new(size: Size) -> Self {
Self::with_options(size, &DEFAULT_OPTIONS)
}
/// Create a simple atlas allocator with the provided options.
pub fn with_options(size: Size, options: &AllocatorOptions) -> Self {
let bucket = free_list_for_size(
options.small_size_threshold,
options.large_size_threshold,
&size,
);
let mut free_rects = [Vec::new(), Vec::new(), Vec::new()];
free_rects[bucket].push(size.into());
SimpleAtlasAllocator {
free_rects,
alignment: options.alignment,
small_size_threshold: options.small_size_threshold,
large_size_threshold: options.large_size_threshold,
size,
}
}
/// Drop all rectangles, clearing the atlas to its initial state.
pub fn clear(&mut self) {
for i in 0..NUM_BUCKETS {
self.free_rects[i].clear();
}
let bucket = free_list_for_size(
self.small_size_threshold,
self.large_size_threshold,
&self.size,
);
self.free_rects[bucket].push(self.size.into());
}
/// Clear the allocator and reset its size and options.
pub fn reset(&mut self, size: Size, options: &AllocatorOptions) {
self.alignment = options.alignment;
self.small_size_threshold = options.small_size_threshold;
self.large_size_threshold = options.large_size_threshold;
self.size = size;
self.clear();
}
pub fn is_empty(&self) -> bool {
for b in 0..NUM_BUCKETS {
for rect in &self.free_rects[b] {
return rect.size() == self.size;
}
}
// This should be unreachable.
return false;
}
/// The total size of the atlas.
pub fn size(&self) -> Size {
self.size
}
/// Allocate a rectangle in the atlas.
pub fn allocate(&mut self, mut requested_size: Size) -> Option<Rectangle> {
if requested_size.is_empty() {
return None;
}
adjust_size(self.alignment.width, &mut requested_size.width);
adjust_size(self.alignment.height, &mut requested_size.height);
let ideal_bucket = free_list_for_size(
self.small_size_threshold,
self.large_size_threshold,
&requested_size,
);
let use_worst_fit = ideal_bucket == LARGE_BUCKET;
let mut chosen_rect = None;
for bucket in ideal_bucket..NUM_BUCKETS {
let mut candidate_score = if use_worst_fit { 0 } else { std::i32::MAX };
let mut candidate = None;
for (index, rect) in self.free_rects[bucket].iter().enumerate() {
let dx = rect.width() - requested_size.width;
let dy = rect.height() - requested_size.height;
if dx >= 0 && dy >= 0 {
if dx == 0 || dy == 0 {
// Perfect fit!
candidate = Some(index);
break;
}
let score = i32::min(dx, dy);
if (use_worst_fit && score > candidate_score)
|| (!use_worst_fit && score < candidate_score)
{
candidate_score = score;
candidate = Some(index);
}
}
}
if let Some(index) = candidate {
let rect = self.free_rects[bucket].remove(index);
chosen_rect = Some(rect);
break;
}
}
if let Some(rect) = chosen_rect {
let (split_rect, leftover_rect, _) =
guillotine_rect(&rect, requested_size, Orientation::Vertical);
self.add_free_rect(&split_rect);
self.add_free_rect(&leftover_rect);
return Some(Rectangle {
min: rect.min,
max: rect.min + requested_size.to_vector(),
});
}
None
}
/// Resize the atlas without changing the allocations.
///
/// This method is not allowed to shrink the width or height of the atlas.
pub fn grow(&mut self, new_size: Size) {
assert!(new_size.width >= self.size.width);
assert!(new_size.height >= self.size.height);
let (split_rect, leftover_rect, _) =
guillotine_rect(&new_size.into(), self.size, Orientation::Vertical);
self.size = new_size;
self.add_free_rect(&split_rect);
self.add_free_rect(&leftover_rect);
}
/// Initialize this simple allocator with the content of an atlas allocator.
pub fn init_from_allocator(&mut self, src: &AtlasAllocator) {
self.size = src.size;
self.small_size_threshold = src.small_size_threshold;
self.large_size_threshold = src.large_size_threshold;
for bucket in 0..NUM_BUCKETS {
for id in src.free_lists[bucket].iter() {
// During tree simplification we don't remove merged nodes from the free list, so we have
// to handle it here.
// This is a tad awkward, but lets us avoid having to maintain a doubly linked list for
// the free list (which would be needed to remove nodes during tree simplification).
if src.nodes[id.index()].kind != NodeKind::Free {
continue;
}
self.free_rects[bucket].push(src.nodes[id.index()].rect);
}
}
}
fn add_free_rect(&mut self, rect: &Rectangle) {
if rect.width() < self.alignment.width || rect.height() < self.alignment.height {
return;
}
let bucket = free_list_for_size(
self.small_size_threshold,
self.large_size_threshold,
&rect.size(),
);
self.free_rects[bucket].push(*rect);
}
}
fn adjust_size(alignment: i32, size: &mut i32) {
let rem = *size % alignment;
if rem > 0 {
*size += alignment - rem;
}
}
/// Compute the area, saturating at i32::MAX instead of overflowing.
fn safe_area(rect: &Rectangle) -> i32 {
rect.width().checked_mul(rect.height()).unwrap_or(std::i32::MAX)
}
fn guillotine_rect(
chosen_rect: &Rectangle,
requested_size: Size,
default_orientation: Orientation,
) -> (Rectangle, Rectangle, Orientation) {
// Decide whether to split horizontally or vertically.
//
// If the chosen free rectangle is bigger than the requested size, we subdivide it
// into an allocated rectangle, a split rectangle and a leftover rectangle:
//
// +-----------+-------------+
// |///////////| |
// |/allocated/| |
// |///////////| |
// +-----------+ |
// | |
// | chosen |
// | |
// +-------------------------+
//
// Will be split into either:
//
// +-----------+-------------+
// |///////////| |
// |/allocated/| leftover |
// |///////////| |
// +-----------+-------------+
// | |
// | split |
// | |
// +-------------------------+
//
// or:
//
// +-----------+-------------+
// |///////////| |
// |/allocated/| |
// |///////////| split |
// +-----------+ |
// | | |
// | leftover | |
// | | |
// +-----------+-------------+
let candidate_leftover_rect_to_right = Rectangle {
min: chosen_rect.min + vec2(requested_size.width, 0),
max: point2(chosen_rect.max.x, chosen_rect.min.y + requested_size.height),
};
let candidate_leftover_rect_to_bottom = Rectangle {
min: chosen_rect.min + vec2(0, requested_size.height),
max: point2(chosen_rect.min.x + requested_size.width, chosen_rect.max.y),
};
let split_rect;
let leftover_rect;
let orientation;
if requested_size == chosen_rect.size() {
// Perfect fit.
orientation = default_orientation;
split_rect = Rectangle::zero();
leftover_rect = Rectangle::zero();
} else if safe_area(&candidate_leftover_rect_to_right) > safe_area(&candidate_leftover_rect_to_bottom) {
leftover_rect = candidate_leftover_rect_to_bottom;
split_rect = Rectangle {
min: candidate_leftover_rect_to_right.min,
max: point2(candidate_leftover_rect_to_right.max.x, chosen_rect.max.y),
};
orientation = Orientation::Horizontal;
} else {
leftover_rect = candidate_leftover_rect_to_right;
split_rect = Rectangle {
min: candidate_leftover_rect_to_bottom.min,
max: point2(chosen_rect.max.x, candidate_leftover_rect_to_bottom.max.y),
};
orientation = Orientation::Vertical;
}
(split_rect, leftover_rect, orientation)
}
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Allocation {
pub id: AllocId,
pub rectangle: Rectangle,
}
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Change {
pub old: Allocation,
pub new: Allocation,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChangeList {
pub changes: Vec<Change>,
pub failures: Vec<Allocation>,
}
impl ChangeList {
pub fn empty() -> Self {
ChangeList {
changes: Vec::new(),
failures: Vec::new(),
}
}
}
/// Dump a visual representation of the atlas in SVG format.
pub fn dump_svg(atlas: &AtlasAllocator, output: &mut dyn std::io::Write) -> std::io::Result<()> {
use svg_fmt::*;
writeln!(
output,
"{}",
BeginSvg {
w: atlas.size.width as f32,
h: atlas.size.height as f32
}
)?;
dump_into_svg(atlas, None, output)?;
writeln!(output, "{}", EndSvg)
}
/// Dump a visual representation of the atlas in SVG, omitting the beginning and end of the
/// SVG document, so that it can be included in a larger document.
///
/// If a rectangle is provided, translate and scale the output to fit it.
pub fn dump_into_svg(atlas: &AtlasAllocator, rect: Option<&Rectangle>, output: &mut dyn std::io::Write) -> std::io::Result<()> {
use svg_fmt::*;
let (sx, sy, tx, ty) = if let Some(rect) = rect {
(
rect.width() as f32 / atlas.size.width as f32,
rect.height() as f32 / atlas.size.height as f32,
rect.min.x as f32,
rect.min.y as f32,
)
} else {
(1.0, 1.0, 0.0, 0.0)
};
for node in &atlas.nodes {
let color = match node.kind {
NodeKind::Free => rgb(50, 50, 50),
NodeKind::Alloc => rgb(70, 70, 180),
_ => {
continue;
}
};
let (x, y) = node.rect.min.to_f32().to_tuple();
let (w, h) = node.rect.size().to_f32().to_tuple();
writeln!(
output,
r#" {}"#,
rectangle(tx + x * sx, ty + y * sy, w * sx, h * sy)
.fill(color)
.stroke(Stroke::Color(black(), 1.0))
)?;
}
Ok(())
}
#[test]
fn atlas_basic() {
let mut atlas = AtlasAllocator::new(size2(1000, 1000));
let full = atlas.allocate(size2(1000, 1000)).unwrap().id;
assert!(atlas.allocate(size2(1, 1)).is_none());
atlas.deallocate(full);
let a = atlas.allocate(size2(100, 1000)).unwrap().id;
let b = atlas.allocate(size2(900, 200)).unwrap().id;
let c = atlas.allocate(size2(300, 200)).unwrap().id;
let d = atlas.allocate(size2(200, 300)).unwrap().id;
let e = atlas.allocate(size2(100, 300)).unwrap().id;
let f = atlas.allocate(size2(100, 300)).unwrap().id;
let g = atlas.allocate(size2(100, 300)).unwrap().id;
atlas.deallocate(b);
atlas.deallocate(f);
atlas.deallocate(c);
atlas.deallocate(e);
let h = atlas.allocate(size2(500, 200)).unwrap().id;
atlas.deallocate(a);
let i = atlas.allocate(size2(500, 200)).unwrap().id;
atlas.deallocate(g);
atlas.deallocate(h);
atlas.deallocate(d);
atlas.deallocate(i);
let full = atlas.allocate(size2(1000, 1000)).unwrap().id;
assert!(atlas.allocate(size2(1, 1)).is_none());
atlas.deallocate(full);
}
#[test]
fn atlas_random_test() {
let mut atlas = AtlasAllocator::with_options(
size2(1000, 1000),
&AllocatorOptions {
alignment: size2(5, 2),
..DEFAULT_OPTIONS
},
);
let a = 1103515245;
let c = 12345;
let m = usize::pow(2, 31);
let mut seed: usize = 37;
let mut rand = || {
seed = (a * seed + c) % m;
seed
};
let mut n: usize = 0;
let mut misses: usize = 0;
let mut allocated = Vec::new();
for _ in 0..500000 {
if rand() % 5 > 2 && !allocated.is_empty() {
// deallocate something
let nth = rand() % allocated.len();
let id = allocated[nth];
allocated.remove(nth);
atlas.deallocate(id);
} else {
// allocate something
let size = size2((rand() % 300) as i32 + 5, (rand() % 300) as i32 + 5);
if let Some(alloc) = atlas.allocate(size) {
allocated.push(alloc.id);
n += 1;
} else {
misses += 1;
}
}
}
while let Some(id) = allocated.pop() {
atlas.deallocate(id);
}
println!("added/removed {} rectangles, {} misses", n, misses);
println!(
"nodes.cap: {}, free_list.cap: {}/{}/{}",
atlas.nodes.capacity(),
atlas.free_lists[LARGE_BUCKET].capacity(),
atlas.free_lists[MEDIUM_BUCKET].capacity(),
atlas.free_lists[SMALL_BUCKET].capacity(),
);
let full = atlas.allocate(size2(1000, 1000)).unwrap().id;
assert!(atlas.allocate(size2(1, 1)).is_none());
atlas.deallocate(full);
}
#[test]
fn test_grow() {
let mut atlas = AtlasAllocator::new(size2(1000, 1000));
atlas.grow(size2(2000, 2000));
let full = atlas.allocate(size2(2000, 2000)).unwrap().id;
assert!(atlas.allocate(size2(1, 1)).is_none());
atlas.deallocate(full);
let a = atlas.allocate(size2(100, 100)).unwrap().id;
atlas.grow(size2(3000, 3000));
let b = atlas.allocate(size2(1000, 2900)).unwrap().id;
atlas.grow(size2(4000, 4000));
atlas.deallocate(b);
atlas.deallocate(a);
let full = atlas.allocate(size2(4000, 4000)).unwrap().id;
assert!(atlas.allocate(size2(1, 1)).is_none());
atlas.deallocate(full);
}
#[test]
fn clear_empty() {
let mut atlas = AtlasAllocator::new(size2(1000, 1000));
assert!(atlas.is_empty());
assert!(atlas.allocate(size2(10, 10)).is_some());
assert!(!atlas.is_empty());
atlas.clear();
assert!(atlas.is_empty());
let a = atlas.allocate(size2(10, 10)).unwrap().id;
let b = atlas.allocate(size2(20, 20)).unwrap().id;
assert!(!atlas.is_empty());
atlas.deallocate(b);
atlas.deallocate(a);
assert!(atlas.is_empty());
atlas.clear();
assert!(atlas.is_empty());
atlas.clear();
assert!(atlas.is_empty());
}
#[test]
fn simple_atlas() {
let mut atlas = SimpleAtlasAllocator::new(size2(1000, 1000));
assert!(atlas.allocate(size2(1, 1001)).is_none());
assert!(atlas.allocate(size2(1001, 1)).is_none());
let mut rectangles = Vec::new();
rectangles.push(atlas.allocate(size2(100, 1000)).unwrap());
rectangles.push(atlas.allocate(size2(900, 200)).unwrap());
rectangles.push(atlas.allocate(size2(300, 200)).unwrap());
rectangles.push(atlas.allocate(size2(200, 300)).unwrap());
rectangles.push(atlas.allocate(size2(100, 300)).unwrap());
rectangles.push(atlas.allocate(size2(100, 300)).unwrap());
rectangles.push(atlas.allocate(size2(100, 300)).unwrap());
assert!(atlas.allocate(size2(800, 800)).is_none());
for i in 0..rectangles.len() {
for j in 0..rectangles.len() {
if i == j {
continue;
}
assert!(!rectangles[i].intersects(&rectangles[j]));
}
}
}
#[test]
fn allocate_zero() {
let mut atlas = SimpleAtlasAllocator::new(size2(1000, 1000));
assert!(atlas.allocate(size2(0, 0)).is_none());
}
#[test]
fn allocate_negative() {
let mut atlas = SimpleAtlasAllocator::new(size2(1000, 1000));
assert!(atlas.allocate(size2(-1, 1)).is_none());
assert!(atlas.allocate(size2(1, -1)).is_none());
assert!(atlas.allocate(size2(-1, -1)).is_none());
assert!(atlas.allocate(size2(-167114179, -718142)).is_none());
}
#[test]
fn issue_25() {
let mut allocator = AtlasAllocator::new(Size::new(65536, 65536));
allocator.allocate(Size::new(2,2));
allocator.allocate(Size::new(65500,2));
allocator.allocate(Size::new(2, 65500));
}
|
// scene.rs
//
// Copyright (c) 2019, Univerisity of Minnesota
//
// Author: Bridger Herman (herma582@umn.edu)
//! A scene, specified by a json file
use std::collections::HashMap;
use glam::{Quat, Vec2, Vec3};
use wasm_bindgen::prelude::*;
use crate::entity::EntityId;
use crate::light::{PointLight, SpotLight};
use crate::material::Material;
use crate::mesh::Mesh;
use crate::resources::{load_image_resource, load_text_resource};
use crate::script_manager::WreScript;
use crate::shader::{load_shader, Shader};
use crate::texture::Texture;
use crate::transform::Transform;
#[wasm_bindgen(module = "/assets/loadWreScript.js")]
extern "C" {
#[wasm_bindgen]
pub fn loadWreScript(name: &str, eid: EntityId) -> WreScript;
}
/// A prefab loaded from the scene file
#[derive(Debug, Serialize, Deserialize)]
struct JsonPrefab {
/// Path to the mesh that should be drawn
mesh: Option<String>,
/// Names of the scripts that should be attached to this prefab
scripts: Vec<String>,
/// Name of the shader that should be used to render this object
shader: Option<String>,
}
/// The fog in the scene
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct JsonFog {
pub color: Vec3,
pub density: f32,
}
/// Each entity in the scene file. Optional fields are represented as `Option`
/// type
#[derive(Debug, Serialize, Deserialize)]
struct JsonEntity {
/// The name of the prefab that this entity is made out of
prefab: String,
/// Position: part of transform
position: Option<Vec3>,
/// Rotation (xyz euler angles): part of transform
rotation: Option<Vec3>,
/// Scale: part of transform
scale: Option<Vec3>,
}
/// Subset of user camera info defined in scene
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonCamera {
position: Vec3,
rotation: Vec2,
}
/// The scene file, loaded from JSON format
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonScene {
/// Prefabs that can be used in the scene
prefabs: HashMap<String, JsonPrefab>,
/// Lights in the scene
point_lights: Vec<PointLight>,
spot_lights: Vec<SpotLight>,
/// Objects in the scene
entities: Vec<JsonEntity>,
/// User camera information
camera: JsonCamera,
/// Fog in the scene
fog: Option<JsonFog>,
}
/// The actual scene, containing all the de-duplicated resources loaded into WRE
/// format (entities, meshes, textures)
#[derive(Debug, Default)]
pub struct Scene {
/// Prefabs that are available to entities in the scene
prefabs: HashMap<String, JsonPrefab>,
/// All the point lights in the scene
pub point_lights: Vec<PointLight>,
pub spot_lights: Vec<SpotLight>,
/// The meshes in the scene (path, Mesh)
pub meshes: HashMap<String, Mesh>,
/// The textures in the scene (path, Texture)
pub textures: HashMap<String, Texture>,
/// The obj materials available
pub materials: HashMap<String, Material>,
/// The shaders that this scene's materials use (name, Shader)
pub shaders: HashMap<String, Shader>,
/// Fog
pub fog: JsonFog,
}
impl Scene {
pub fn get_shader_by_id(&self, shader_id: usize) -> Option<&Shader> {
if let Some((_name, shader)) =
self.shaders.iter().find(|(_n, s)| s.id == shader_id)
{
Some(&shader)
} else {
None
}
}
pub fn get_texture_by_id(&self, texture_id: usize) -> Option<&Texture> {
if let Some((_name, texture)) =
self.textures.iter().find(|(_n, t)| t.id == texture_id)
{
Some(&texture)
} else {
None
}
}
}
#[wasm_bindgen]
pub async fn load_scene_async(scene_path: String) -> Result<(), JsValue> {
let scene_text_js = load_text_resource(scene_path.clone()).await?;
let scene_text_string = scene_text_js.as_string().unwrap_or_else(|| {
error_panic!("Unable to convert to string");
});
// Load the scene using serde
let json_scene: JsonScene = serde_json::from_str(&scene_text_string)
.unwrap_or_else(|err| {
error_panic!("Unable to parse scene with serde: {:?}", err);
});
// Default scene (populated by contents of json scene)
let mut scene = Scene::default();
// Move the lights and fog over
scene.point_lights = json_scene.point_lights;
scene.spot_lights = json_scene.spot_lights;
scene.fog = json_scene.fog.unwrap_or_default();
// Convert spot light radians
for s in scene.spot_lights.iter_mut() {
s.angle_inside = s.angle_inside.to_radians();
s.angle_outside = s.angle_outside.to_radians();
}
// Load all the information about the prefabs (meshes, materials, shaders)
for (_name, prefab) in json_scene.prefabs.iter() {
// Don't load any shaders twice
let shader_name =
prefab.shader.clone().unwrap_or("phong_forward".to_string());
if scene.shaders.get(&shader_name).is_none() {
let shader = load_shader(&shader_name, scene.shaders.len()).await?;
scene.shaders.insert(shader_name.clone(), shader);
}
if let Some(mesh) = &prefab.mesh {
// Don't load any mesh twice
if scene.meshes.get(mesh).is_none() {
let obj_text_js = load_text_resource(mesh.clone()).await?;
let obj_text = obj_text_js.as_string().unwrap_or_else(|| {
error_panic!("Unable to convert obj to string");
});
scene
.meshes
.insert(mesh.clone(), Mesh::from_obj_str(&obj_text));
trace!("Loaded mesh {}", mesh);
// Find the texture(s) associated with this object's material
let mtl_name = mesh.replace("obj", "mtl");
let mtl_text_js = load_text_resource(mtl_name.clone()).await?;
let mtl_text = mtl_text_js.as_string().unwrap_or_else(|| {
error_panic!("Unable to convert mtl to string");
});
let texture_name = mtl_text
.lines()
.find(|line| line.to_lowercase().starts_with("map_kd"));
let tex_id = if let Some(name) = texture_name {
// Mutate the texture name so it can be found on the server
let path = format!(
"./resources/textures/{}",
name.split_whitespace().collect::<Vec<_>>()[1]
);
// And only load the texture if it's not already there
if let Some(tex) = scene.textures.get(&path) {
Some(tex.id)
} else {
let tex_id = scene.textures.len();
let img_js = load_image_resource(path.clone()).await?;
let mut bytes = vec![0u8; img_js.length() as usize];
img_js.copy_to(&mut bytes);
scene.textures.insert(
path.clone(),
Texture::init_from_image(tex_id, &bytes),
);
trace!("Loaded texture {}", path);
Some(tex_id)
}
} else {
None
};
let mut material = Material::from_mtl_str(&mtl_text);
material.set_texture_id(tex_id);
material.shader_id = scene.shaders[&shader_name].id;
scene.materials.insert(mtl_name.clone(), material);
trace!("Loaded material {}", mtl_name);
}
}
}
// Move the prefabs over to the scene
scene.prefabs = json_scene.prefabs;
// Populate the scene with entities
for entity in &json_scene.entities {
let rotation = entity.rotation.unwrap_or_default();
let transform = Transform::new(
entity.position.unwrap_or_default(),
Quat::from_rotation_ypr(rotation.y(), rotation.z(), rotation.x()),
entity.scale.unwrap_or(Vec3::one()),
);
let eid = wre_entities!().create();
wre_entities_mut!(eid).set_transform(&transform);
trace!("Initializing entity {}", eid);
// Connect the mesh with this entity
if let Some(mesh_path) = &scene.prefabs[&entity.prefab].mesh {
let mesh = scene.meshes.get_mut(mesh_path).unwrap_or_else(|| {
error_panic!("Mesh {:?} not loaded from a prefab", mesh_path);
});
mesh.attached_to.push(eid);
trace!("Attached mesh {:?} to entity {:?}", mesh_path, eid);
// Add the material and connect it with the shader
let mtl_path = mesh_path.replace("obj", "mtl");
let material = scene.materials.get(&mtl_path).unwrap();
wre_entities_mut!(eid).set_material(material);
trace!("Attached material {:?} to entity {:?}", mtl_path, eid);
}
// Attach the scripts to this entity
for script_name in &scene.prefabs[&entity.prefab].scripts {
let script = loadWreScript(script_name, eid);
wre_scripts!().add_script(eid, script);
trace!("Attached script {:?} to entity {}", script_name, eid);
}
}
// The post-processing shader must be loaded before the scene can be
// rendered!
wre_render_system!().load_post_processing_shader().await?;
wre_render_system!().add_scene(scene);
info!("Loaded Scene: {:?}", scene_path);
wre_camera!().set_position(json_scene.camera.position);
wre_camera!().set_rotation(json_scene.camera.rotation);
Ok(())
}
|
use super::super::*;
use range::Range;
use dungeon::generator::*;
use std::cmp::{min, max, Ordering};
use std::f32;
// Strolneg, M, god of not ingesting poisonous plants and avoiding poison in general, paranoid
// Zarad-dul, F, goddess of creating holes in people, trees, and the ground, etc; consumed with an all-encompassing rage
// Iahu, M, god of pointy objects, perpetually lost (so don't pray to him unless you have a map) and befuddled
// Eregek, F, goddess of strangulation, careless (and might strangle you accidentally, should you ask for help)
// Gzolneb, M, god of death by crushing, deeply insecure and prone to overkilling everything ever
// Urra, F, goddess of ducking and anxiety attacks, fidgety, twitchy, and high-strung
lazy_static! {
static ref SEED: Vec<usize> = vec![1, 2, 3, 4];
static ref MONSTER_POOL: Vec<Monster> = vec![
MonsterBuilder::new("goblin", 1, 3).difficulty(1).spawn()
];
static ref TEMPLATE_MONSTER_POOL: Vec<TemplateMonster> =
vec![TemplateMonster::new(MonsterBuilder::new("servant_of_{}", 1, 3).difficulty(2).spawn(), hashmap!("strolneg".into() => vec![]))];
static ref THEME_KEYWORD_POOL: Vec<Keyword> = vec![
// Gods
"strolneg", "zarad-dul", "iahu", "eregek", "gzolneb", "urra",
// Creature types
"spider", "goblin", "elf",
// Magical effects
"giant"]
.iter().map(|x: &&str| Keyword::from(x.to_string().clone())).collect();
static ref GENERATOR: Generator<'static> = Generator::new(MONSTER_POOL.as_slice(),
TEMPLATE_MONSTER_POOL.as_slice(),
THEME_KEYWORD_POOL.as_slice(),
10,
5,
3,
3,
Range::new(2, 2),
Range::new(4, 2),
false);
}
/// Verify that dungeon is generated
#[test]
fn is_generated() {
// Arrange
// Act
let dungeon = GENERATOR.generate(&SEED.as_slice());
// Assert
assert!(dungeon.rooms.len() != 0);
}
#[test]
fn correct_main_path_length() {
// Arrange
let arch_count = 2;
let num_areas_in_arch = 2;
let num_main_rooms_in_area = 5;
let g = Generator::new(MONSTER_POOL.as_slice(),
TEMPLATE_MONSTER_POOL.as_slice(),
THEME_KEYWORD_POOL.as_slice(),
8,
5,
3,
arch_count,
Range::new(num_areas_in_arch, 1),
Range::new(num_main_rooms_in_area, 1),
false);
// Act
let dungeon = g.generate(&SEED.as_slice());
// Assert
let expected_area_count = arch_count * num_areas_in_arch * num_main_rooms_in_area;
assert_eq!(dungeon.rooms.len(), expected_area_count);
}
#[test]
fn passage_works() {
let rooms = vec![Room::new(&Keyword { id: "A".to_string() }, None),
Room::new(&Keyword { id: "B".to_string() }, None)];
let mut dungeon = Dungeon::new(rooms);
dungeon.create_passage(0, CompassPoint::East, 1);
let room_a = dungeon.get_room(0);
let room_b = dungeon.get_room(1);
assert_eq!(dungeon.get_room(dungeon.get_adjacent(0, CompassPoint::East).unwrap()).keyword,
room_b.keyword);
assert_eq!(dungeon.get_room(dungeon.get_adjacent(1, CompassPoint::West).unwrap()).keyword,
room_a.keyword);
}
// Verify that dungeons generated with a specific seed are always identical
#[test]
fn dungeon_is_deterministic() {
let dungeon_a = GENERATOR.generate(&SEED);
let dungeon_b = GENERATOR.generate(&SEED);
assert_eq!(dungeon_a.rooms.len(), dungeon_b.rooms.len());
for r in 0..dungeon_a.rooms.len() {
assert_eq!(dungeon_a.get_room(r).keyword, dungeon_b.get_room(r).keyword)
}
}
// TODO: verify that dungeons respect their invariant arguments
/*
* TODO: verify that sub-dungeons always only contain theme keywords of their
* super-dungeons
*/
#[test]
fn theme_calculation_works() {
let monster_1 = MonsterBuilder::new("goblin", 1, 1).difficulty(10).keywords(vec!["goblin"].as_slice()).spawn();
let monster_2 = MonsterBuilder::new("demon", 1, 1).difficulty(10).keywords(vec!["demon"].as_slice()).spawn();
let monster_3 = MonsterBuilder::new("demon-goblin", 1, 1).difficulty(10).keywords(vec!["goblin", "demon"].as_slice()).spawn();
let theme_1: Vec<Keyword> = vec!["goblin".into()];
let theme_2: Vec<Keyword> = vec!["demon".into()];
let theme_3: Vec<Keyword> = vec!["goblin".into(), "demon".into()];
// Act
let m1_in_t1 = evaluate_theme(&monster_1, theme_1.as_slice());
let m2_in_t1 = evaluate_theme(&monster_2, theme_1.as_slice());
let m3_in_t1 = evaluate_theme(&monster_3, theme_1.as_slice());
let m1_in_t2 = evaluate_theme(&monster_1, theme_2.as_slice());
let m2_in_t2 = evaluate_theme(&monster_2, theme_2.as_slice());
let m3_in_t2 = evaluate_theme(&monster_3, theme_2.as_slice());
let m1_in_t3 = evaluate_theme(&monster_1, theme_3.as_slice());
let m2_in_t3 = evaluate_theme(&monster_2, theme_3.as_slice());
let m3_in_t3 = evaluate_theme(&monster_3, theme_3.as_slice());
const MAX_DELTA: f32 = 0.01;
// Assert
assert!( (m1_in_t1 - 1.0).abs() < MAX_DELTA );
assert!( (m2_in_t1 - 0.0).abs() < MAX_DELTA );
assert!( (m3_in_t1 - 1.0).abs() < MAX_DELTA );
assert!( (m1_in_t2 - 0.0).abs() < MAX_DELTA );
assert!( (m2_in_t2 - 1.0).abs() < MAX_DELTA );
assert!( (m3_in_t2 - 1.0).abs() < MAX_DELTA );
assert!( (m1_in_t3 - 0.5).abs() < MAX_DELTA );
assert!( (m2_in_t3 - 0.5).abs() < MAX_DELTA );
assert!( (m3_in_t3 - 1.0).abs() < MAX_DELTA );
}
#[test]
fn difficulty_is_normalized() {
let goblin = MonsterBuilder::new("goblin", 1, 3).difficulty(1).spawn();
let demon = MonsterBuilder::new("demon", 15, 40).difficulty(10).spawn();
assert_eq!(goblin.normalized_difficulty(), 0.1);
assert_eq!(demon.normalized_difficulty(), 1.);
}
|
/*!
Hashes相关的命令定义、解析
所有涉及到的命令参考[Redis Command Reference]
[Redis Command Reference]: https://redis.io/commands#hash
*/
use std::slice::Iter;
#[derive(Debug)]
pub struct HDEL<'a> {
pub key: &'a [u8],
pub fields: Vec<&'a [u8]>,
}
pub(crate) fn parse_hdel(mut iter: Iter<Vec<u8>>) -> HDEL {
let key = iter.next().unwrap();
let mut fields = Vec::new();
while let Some(field) = iter.next() {
fields.push(field.as_slice());
}
HDEL { key, fields }
}
#[derive(Debug)]
pub struct HINCRBY<'a> {
pub key: &'a [u8],
pub field: &'a [u8],
pub increment: &'a [u8],
}
pub(crate) fn parse_hincrby(mut iter: Iter<Vec<u8>>) -> HINCRBY {
let key = iter.next().unwrap();
let field = iter.next().unwrap();
let increment = iter.next().unwrap();
HINCRBY { key, field, increment }
}
#[derive(Debug)]
pub struct HMSET<'a> {
pub key: &'a [u8],
pub fields: Vec<Field<'a>>,
}
#[derive(Debug)]
pub struct HSET<'a> {
pub key: &'a [u8],
pub fields: Vec<Field<'a>>,
}
#[derive(Debug)]
pub struct Field<'a> {
pub name: &'a [u8],
pub value: &'a [u8],
}
pub(crate) fn parse_hmset(mut iter: Iter<Vec<u8>>) -> HMSET {
let key = iter.next().unwrap();
let mut fields = Vec::new();
loop {
if let Some(field) = iter.next() {
if let Some(value) = iter.next() {
let field = Field { name: field, value };
fields.push(field);
} else {
panic!("HMSET缺失field value");
}
} else {
break;
}
}
HMSET { key, fields }
}
pub(crate) fn parse_hset(mut iter: Iter<Vec<u8>>) -> HSET {
let key = iter.next().unwrap();
let mut fields = Vec::new();
loop {
if let Some(field) = iter.next() {
if let Some(value) = iter.next() {
let field = Field { name: field, value };
fields.push(field);
} else {
panic!("HSET缺失field value");
}
} else {
break;
}
}
HSET { key, fields }
}
#[derive(Debug)]
pub struct HSETNX<'a> {
pub key: &'a [u8],
pub field: &'a [u8],
pub value: &'a [u8],
}
pub(crate) fn parse_hsetnx(mut iter: Iter<Vec<u8>>) -> HSETNX {
let key = iter.next().unwrap();
let field = iter.next().unwrap();
let value = iter.next().unwrap();
HSETNX { key, field, value }
}
|
use proconio::{input, marker::Chars};
fn main() {
input! {
_n: usize,
s: Chars,
};
let mut inner = false;
let mut ans = String::new();
for ch in s {
if ch == '"' {
inner = !inner;
}
if ch == ',' && !inner {
ans.push('.');
} else {
ans.push(ch);
}
}
println!("{}", ans);
}
|
//! Parsing of HTTP requests that conform to the [V2 Write API] only.
//!
//! [V2 Write API]:
//! https://docs.influxdata.com/influxdb/v2.6/api/#operation/PostWrite
use async_trait::async_trait;
use data_types::{NamespaceName, OrgBucketMappingError};
use hyper::{Body, Request};
use super::{
v2::{V2WriteParseError, WriteParamsV2},
WriteParams, WriteRequestUnifier,
};
use crate::server::http::Error;
/// Request parsing errors when operating in "single tenant" mode.
#[derive(Debug, Error)]
pub enum MultiTenantExtractError {
/// A failure to map a org & bucket to a reasonable [`NamespaceName`].
#[error(transparent)]
InvalidOrgAndBucket(#[from] OrgBucketMappingError),
/// A [`WriteParamsV2`] failed to be parsed from the HTTP request.
#[error(transparent)]
ParseV2Request(#[from] V2WriteParseError),
}
/// Implement a by-ref conversion to avoid "moving" the inner errors when only
/// matching against the variants is necessary (the actual error content is
/// discarded, replaced with only a HTTP code)
impl From<&MultiTenantExtractError> for hyper::StatusCode {
fn from(value: &MultiTenantExtractError) -> Self {
// Exhaustively match the inner parser errors to ensure new additions
// have to be explicitly mapped and are not accidentally mapped to a
// "catch all" code.
match value {
MultiTenantExtractError::InvalidOrgAndBucket(_) => Self::BAD_REQUEST,
MultiTenantExtractError::ParseV2Request(
V2WriteParseError::NoQueryParams | V2WriteParseError::DecodeFail(_),
) => Self::BAD_REQUEST,
}
}
}
/// Request parsing for cloud2 / multi-tenant deployments.
///
/// This handler respects the [V2 Write API] without modification, and rejects
/// any V1 write requests.
///
/// [V2 Write API]:
/// https://docs.influxdata.com/influxdb/v2.6/api/#operation/PostWrite
#[derive(Debug, Default)]
pub struct MultiTenantRequestUnifier;
#[async_trait]
impl WriteRequestUnifier for MultiTenantRequestUnifier {
async fn parse_v1(&self, _req: &Request<Body>) -> Result<WriteParams, Error> {
Err(Error::NoHandler)
}
async fn parse_v2(&self, req: &Request<Body>) -> Result<WriteParams, Error> {
Ok(parse_v2(req)?)
}
}
// Parse a V2 write request for multi tenant mode.
fn parse_v2(req: &Request<Body>) -> Result<WriteParams, MultiTenantExtractError> {
let write_params = WriteParamsV2::try_from(req)?;
let namespace = NamespaceName::from_org_and_bucket(write_params.org, write_params.bucket)?;
Ok(WriteParams {
namespace,
precision: write_params.precision,
})
}
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use data_types::NamespaceNameError;
use super::*;
use crate::server::http::write::Precision;
#[tokio::test]
async fn test_parse_v1_always_errors() {
let unifier = MultiTenantRequestUnifier;
let got = unifier.parse_v1(&Request::default()).await;
assert_matches!(got, Err(Error::NoHandler));
}
macro_rules! test_parse_v2 {
(
$name:ident,
query_string = $query_string:expr, // A query string including the ?
want = $($want:tt)+ // A pattern match for assert_matches!
) => {
paste::paste! {
#[tokio::test]
async fn [<test_parse_v2_ $name>]() {
let unifier = MultiTenantRequestUnifier;
let query = $query_string;
let request = Request::builder()
.uri(format!("https://itsallbroken.com/ignored{query}"))
.method("POST")
.body(Body::from(""))
.unwrap();
let got = unifier.parse_v2(&request).await;
assert_matches!(got, $($want)+);
}
}
};
}
test_parse_v2!(
no_query_string,
query_string = "",
want = Err(Error::MultiTenantError(
MultiTenantExtractError::ParseV2Request(V2WriteParseError::NoQueryParams)
))
);
test_parse_v2!(
empty_query_string,
query_string = "?",
want = Err(Error::MultiTenantError(
MultiTenantExtractError::InvalidOrgAndBucket(
OrgBucketMappingError::NoOrgBucketSpecified
)
))
);
// While this is allowed in single-tenant, it is NOT allowed in multi-tenant
test_parse_v2!(
bucket_only,
query_string = "?bucket=bananas",
want = Err(Error::MultiTenantError(
MultiTenantExtractError::InvalidOrgAndBucket(
OrgBucketMappingError::NoOrgBucketSpecified
)
))
);
test_parse_v2!(
org_only,
query_string = "?org=bananas",
want = Err(Error::MultiTenantError(
MultiTenantExtractError::InvalidOrgAndBucket(
OrgBucketMappingError::NoOrgBucketSpecified
)
))
);
test_parse_v2!(
no_org_no_bucket,
query_string = "?wat=isthis",
want = Err(Error::MultiTenantError(
MultiTenantExtractError::InvalidOrgAndBucket(
OrgBucketMappingError::NoOrgBucketSpecified
)
))
);
test_parse_v2!(
encoded_separator,
query_string = "?org=cool_confusing&bucket=bucket",
want = Ok(WriteParams {
namespace,
..
}) => {
assert_eq!(namespace.as_str(), "cool_confusing_bucket");
}
);
test_parse_v2!(
encoded_case_sensitive,
query_string = "?org=Captialize&bucket=bucket",
want = Ok(WriteParams {
namespace,
..
}) => {
assert_eq!(namespace.as_str(), "Captialize_bucket");
}
);
test_parse_v2!(
encoded_quotation,
query_string = "?org=cool'confusing&bucket=bucket",
want = Err(Error::MultiTenantError(
MultiTenantExtractError::InvalidOrgAndBucket(
OrgBucketMappingError::InvalidNamespaceName(NamespaceNameError::BadChars { .. })
)
))
);
test_parse_v2!(
start_nonalphanumeric,
query_string = "?org=_coolconfusing&bucket=bucket",
want = Ok(WriteParams {
namespace,
..
}) => {
assert_eq!(namespace.as_str(), "_coolconfusing_bucket");
}
);
test_parse_v2!(
minimum_length_possible,
query_string = "?org=o&bucket=b",
want = Ok(WriteParams {
namespace,
..
}) => {
assert_eq!(namespace.as_str().len(), 3);
}
);
// Expected usage (no org) with precision
test_parse_v2!(
with_precision,
query_string = "?org=banana&bucket=cool&precision=ms",
want = Ok(WriteParams {
namespace,
precision
}) => {
assert_eq!(namespace.as_str(), "banana_cool");
assert_matches!(precision, Precision::Milliseconds);
}
);
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::test::types::{
StepResult, StepResultItem, TestPlan, TestPlanTest, TestResult, TestResultItem, TestResults,
},
fidl_fuchsia_sys, fuchsia_async as fasync,
fuchsia_syslog::macros::*,
futures::{channel::mpsc, prelude::*},
serde_json::Value,
std::{collections::HashMap, fmt, fs::File, io::Write},
test_executor::TestEvent,
uuid::Uuid,
};
struct Step {
pub result: StepResult,
logs: Option<String>,
}
impl Step {
pub fn default() -> Step {
Step { result: StepResult::default(), logs: None }
}
pub fn add_log(&mut self, log: String) {
match &mut self.logs {
Some(s) => s.push_str(&log),
None => self.logs = Some(log),
}
}
pub fn take_logs(&mut self) -> String {
self.logs.take().unwrap_or_else(|| "".to_string())
}
}
#[derive(Debug)]
pub struct TestFacade {}
impl TestFacade {
pub fn new() -> TestFacade {
TestFacade {}
}
pub async fn run_plan(&self, plan: TestPlan) -> Result<Value, failure::Error> {
let mut results = TestResults::default();
for test in plan.tests.iter() {
match test {
TestPlanTest::ComponentUrl(c) => {
let result = self.run_test_component(c.to_string()).await?;
results.results.push(TestResultItem::Result(result));
}
}
}
serde_json::to_value(results).map_err(|e| format_err!("Not able to format results: {}", e))
}
pub async fn run_test(&self, url: String) -> Result<Value, failure::Error> {
let test_results = self.run_test_component(url).await?;
serde_json::to_value(test_results)
.map_err(|e| format_err!("Not able to format test results: {}", e))
}
async fn run_test_component(&self, url: String) -> Result<TestResult, failure::Error> {
let launcher = match fuchsia_component::client::connect_to_service::<
fidl_fuchsia_sys::LauncherMarker,
>() {
Ok(l) => l,
Err(e) => return Err(e),
};
let (sender, mut recv) = mpsc::channel(1);
let (remote, test_fut) =
test_executor::run_test_component(launcher, url.clone(), sender).remote_handle();
fasync::spawn(remote);
#[derive(PartialEq)]
enum TestOutcome {
Passed,
Failed,
Inconclusive,
Error,
};
impl fmt::Display for TestOutcome {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TestOutcome::Passed => write!(f, "passed"),
TestOutcome::Failed => write!(f, "failed"),
TestOutcome::Inconclusive => write!(f, "inconclusive"),
TestOutcome::Error => write!(f, "error"),
}
}
}
let mut test_outcome = TestOutcome::Passed;
let mut current_step_map = HashMap::new();
while let Some(test_event) = recv.next().await {
match test_event {
TestEvent::TestCaseStarted { test_case_name } => {
let step = Step {
result: StepResult {
name: test_case_name.clone(),
..StepResult::default()
},
..Step::default()
};
current_step_map.insert(test_case_name, step);
}
TestEvent::TestCaseFinished { test_case_name, outcome } => {
match current_step_map.get_mut(&test_case_name) {
Some(step) => {
step.result.outcome = match outcome {
test_executor::Outcome::Passed => "passed".to_string(),
test_executor::Outcome::Failed => {
if test_outcome == TestOutcome::Passed {
test_outcome = TestOutcome::Failed;
}
"failed".to_string()
}
test_executor::Outcome::Error => {
test_outcome = TestOutcome::Error;
"error".to_string()
}
};
}
None => {
return Err(format_err!("test case: '{}' not found", test_case_name));
}
}
}
TestEvent::LogMessage { test_case_name, msg } => {
match current_step_map.get_mut(&test_case_name) {
Some(step) => {
step.add_log(msg);
}
None => {
return Err(format_err!("test case: '{}' not found", test_case_name));
}
}
}
}
}
test_fut.await.map_err(|e| format_err!("Error running test: {}", e))?;
let mut step_results = Vec::<StepResultItem>::new();
for (_, mut step) in current_step_map {
if step.result.outcome == "".to_string() {
// step not completed, test might have crashed.
match test_outcome {
TestOutcome::Passed | TestOutcome::Failed => {
test_outcome = TestOutcome::Inconclusive;
}
_ => {}
}
step.result.outcome = "inconclusive".to_string();
}
let logs = step.take_logs();
if logs.len() > 0 {
// TODO(anmittal): Display log until host can pull logs and display it.
fx_log_info!("logs: {}", logs);
let filename = format!("/data/{}", &Uuid::new_v4().to_string());
let mut file = File::create(&filename)?;
write!(file, "{}", logs)?;
step.result.primary_log_path = filename.clone();
}
step_results.push(StepResultItem::Result(step.result));
}
let mut test_result = TestResult::default();
test_result.outcome = test_outcome.to_string();
test_result.steps = step_results;
Ok(test_result)
}
}
|
use scanner_proc_macro::insert_scanner;
#[insert_scanner]
fn main() {
let t = scan!(usize);
for _ in 0..t {
let n = scan!(usize);
let s = scan!(String);
solve(n, s);
}
}
fn solve(n: usize, s: String) {
let mo = 998244353_u64;
let mut dp = vec![0; n + 1];
dp[0] = 1;
dp[1] = 26;
for i in 2..=n {
dp[i] = dp[i - 2] * 26 % mo;
}
let mut ans = 0;
for (i, ch) in s.chars().take(n / 2).enumerate() {
if ch == 'A' {
continue;
}
let d = ch as u64 - 'A' as u64;
assert!((i + 1) * 2 <= n);
ans += d * dp[n - (i + 1) * 2];
ans %= mo;
}
let t: String = s.chars().take(n / 2).collect();
let u: String = t.chars().rev().collect();
if n % 2 == 1 {
let m = s.chars().nth(n / 2).unwrap();
ans += m as u64 - 'A' as u64;
ans %= mo;
let x = format!("{}{}{}", t, m, u);
if x <= s {
ans += 1;
ans %= mo;
}
} else {
let x = format!("{}{}", t, u);
if x <= s {
ans += 1;
ans %= mo;
}
}
println!("{}", ans);
}
|
//mod binary_search_tree;
mod directed_graph;
mod linked_list;
mod linked_list_persistent; |
use crate::window::Geometry;
pub struct Screen<W> {
window: W,
workspace: usize,
view: Geometry,
}
impl<W> Screen<W> {
pub fn new(window: W, view: Geometry) -> Self {
Screen {
window,
workspace: 0,
view
}
}
pub fn get_view(&self) -> &Geometry {
&self.view
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct BitmapCreateOptions(pub u32);
impl BitmapCreateOptions {
pub const None: Self = Self(0u32);
pub const IgnoreImageCache: Self = Self(8u32);
}
impl ::core::marker::Copy for BitmapCreateOptions {}
impl ::core::clone::Clone for BitmapCreateOptions {
fn clone(&self) -> Self {
*self
}
}
pub type BitmapImage = *mut ::core::ffi::c_void;
pub type BitmapSource = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct DecodePixelType(pub i32);
impl DecodePixelType {
pub const Physical: Self = Self(0i32);
pub const Logical: Self = Self(1i32);
}
impl ::core::marker::Copy for DecodePixelType {}
impl ::core::clone::Clone for DecodePixelType {
fn clone(&self) -> Self {
*self
}
}
pub type DownloadProgressEventArgs = *mut ::core::ffi::c_void;
pub type DownloadProgressEventHandler = *mut ::core::ffi::c_void;
pub type RenderTargetBitmap = *mut ::core::ffi::c_void;
pub type SoftwareBitmapSource = *mut ::core::ffi::c_void;
pub type SurfaceImageSource = *mut ::core::ffi::c_void;
pub type SvgImageSource = *mut ::core::ffi::c_void;
pub type SvgImageSourceFailedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SvgImageSourceLoadStatus(pub i32);
impl SvgImageSourceLoadStatus {
pub const Success: Self = Self(0i32);
pub const NetworkError: Self = Self(1i32);
pub const InvalidFormat: Self = Self(2i32);
pub const Other: Self = Self(3i32);
}
impl ::core::marker::Copy for SvgImageSourceLoadStatus {}
impl ::core::clone::Clone for SvgImageSourceLoadStatus {
fn clone(&self) -> Self {
*self
}
}
pub type SvgImageSourceOpenedEventArgs = *mut ::core::ffi::c_void;
pub type VirtualSurfaceImageSource = *mut ::core::ffi::c_void;
pub type WriteableBitmap = *mut ::core::ffi::c_void;
pub type XamlRenderingBackgroundTask = *mut ::core::ffi::c_void;
|
// 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;
use wayland::{WlSubcompositor, WlSubcompositorRequest};
use crate::client::Client;
use crate::object::{ObjectRef, RequestReceiver};
/// An implementation of the wl_subcompositor global.
pub struct Subcompositor;
impl Subcompositor {
/// Creates a new `Subcompositor`.
pub fn new() -> Self {
Subcompositor
}
}
impl RequestReceiver<WlSubcompositor> for Subcompositor {
fn receive(
this: ObjectRef<Self>,
request: WlSubcompositorRequest,
client: &mut Client,
) -> Result<(), Error> {
match request {
WlSubcompositorRequest::Destroy => {
client.delete_id(this.id())?;
}
WlSubcompositorRequest::GetSubsurface { .. } => {}
}
Ok(())
}
}
|
use futures_core::future::BoxFuture;
use serde::de::DeserializeOwned;
use crate::connection::ConnectionSource;
use crate::cursor::Cursor;
use crate::executor::Execute;
use crate::pool::Pool;
use crate::sqlite::{Sqlite, SqliteArguments, SqliteConnection, SqliteRow};
use crate::sqlite::statement::Step;
use crate::decode::json_decode;
pub struct SqliteCursor<'c, 'q> {
pub(super) source: ConnectionSource<'c, SqliteConnection>,
query: &'q str,
arguments: Option<SqliteArguments>,
pub(super) statement: Option<Option<usize>>,
}
impl crate::cursor::private::Sealed for SqliteCursor<'_, '_> {}
impl<'c, 'q> Cursor<'c, 'q> for SqliteCursor<'c, 'q> {
type Database = Sqlite;
#[doc(hidden)]
fn from_pool<E>(pool: &Pool<SqliteConnection>, query: E) -> Self
where
Self: Sized,
E: Execute<'q, Sqlite>,
{
let (query, arguments) = query.into_parts();
Self {
source: ConnectionSource::Pool(pool.clone()),
statement: None,
query,
arguments,
}
}
#[doc(hidden)]
fn from_connection<E>(conn: &'c mut SqliteConnection, query: E) -> Self
where
Self: Sized,
E: Execute<'q, Sqlite>,
{
let (query, arguments) = query.into_parts();
Self {
source: ConnectionSource::ConnectionRef(conn),
statement: None,
query,
arguments,
}
}
fn next(&mut self) -> BoxFuture<crate::Result<Option<SqliteRow<'_>>>> {
Box::pin(next(self))
}
fn decode_json<T>(&mut self) -> BoxFuture<Result<T, crate::Error>>
where T: DeserializeOwned {
Box::pin(async move {
let arr = self.fetch_json().await?;
let r = json_decode(arr)?;
return Ok(r);
})
}
fn fetch_json(&mut self) -> BoxFuture<'_, Result<Vec<serde_json::Value>, crate::Error>> {
Box::pin(async move {
let mut arr = vec![];
while let Some(row) = self.next().await? as Option<SqliteRow<'_>> {
let mut m = serde_json::Map::new();
//TODO is sqlite column is true?
let keys = row.values;
for x in 0..keys {
let key = x.to_string();
let v: serde_json::Value = row.json_decode_impl(key.as_str()).unwrap();
m.insert(key, v);
}
arr.push(serde_json::Value::Object(m));
}
return Ok(arr);
})
}
}
async fn next<'a, 'c: 'a, 'q: 'a>(
cursor: &'a mut SqliteCursor<'c, 'q>,
) -> crate::Result<Option<SqliteRow<'a>>> {
let conn = cursor.source.resolve().await?;
loop {
if cursor.statement.is_none() {
let key = conn.prepare(&mut cursor.query, cursor.arguments.is_some())?;
if let Some(arguments) = &mut cursor.arguments {
conn.statement_mut(key).bind(arguments)?;
}
cursor.statement = Some(key);
}
let key = cursor.statement.unwrap();
let statement = conn.statement_mut(key);
let step = statement.step().await?;
match step {
Step::Row => {
return Ok(Some(SqliteRow {
values: statement.data_count(),
statement: key,
connection: conn,
}));
}
Step::Done if cursor.query.is_empty() => {
return Ok(None);
}
Step::Done => {
cursor.statement = None;
// continue
}
}
}
}
|
extern crate cgmath;
extern crate collision;
use cgmath::{BaseFloat, Decomposed, EuclideanSpace, One, Rotation, Transform};
pub use collision::{Interpolate, TranslationInterpolate};
/// Pose abstraction
pub trait Pose<P, R>: Transform<P>
where
P: EuclideanSpace,
{
/// New pose
fn new(position: P, rotation: R) -> Self;
/// Set rotation
fn set_rotation(&mut self, rotation: R);
/// Set position
fn set_position(&mut self, position: P);
/// Read rotation
fn rotation(&self) -> R;
/// Read position
fn position(&self) -> P;
}
pub trait PhysicsTime<S> {
fn delta_seconds(&self) -> S;
}
impl<P, R> Pose<P, R> for Decomposed<P::Diff, R>
where
P: EuclideanSpace,
P::Scalar: BaseFloat,
R: Rotation<P>,
{
fn new(position: P, rotation: R) -> Self {
Decomposed {
rot: rotation,
disp: position.to_vec(),
scale: P::Scalar::one(),
}
}
fn set_rotation(&mut self, rotation: R) {
self.rot = rotation;
}
fn set_position(&mut self, position: P) {
self.disp = position.to_vec();
}
fn rotation(&self) -> R {
self.rot
}
fn position(&self) -> P {
P::from_vec(self.disp)
}
}
|
//! [GitHub](https://github.com/kuretchi/spella)
//!
//! A competitive programming library for Rust.
pub mod algebra;
pub mod byte;
pub mod io;
pub mod sequences;
|
use std::{
fs::File,
io::{self, BufReader, Write},
};
use flate2::read::MultiGzDecoder;
use vcf::{VCFReader, VCFRecord};
use crate::error::Error;
pub trait VcfRecordInspector<R> {
fn inspect_record(&mut self, record: &VCFRecord) -> crate::Result<()>;
fn get_result(&mut self) -> crate::Result<R>;
}
pub fn get_vcf_reader(input: &str) -> crate::Result<VCFReader<BufReader<MultiGzDecoder<File>>>> {
Ok(VCFReader::new(BufReader::new(MultiGzDecoder::new(
File::open(input)?,
)))?)
}
pub struct RecordCounter {
n_records: u32,
}
impl RecordCounter {
pub fn new() -> RecordCounter {
RecordCounter { n_records: 0 }
}
}
impl VcfRecordInspector<u32> for RecordCounter {
fn inspect_record(&mut self, _record: &VCFRecord) -> crate::Result<()> {
self.n_records += 1;
Ok(())
}
fn get_result(&mut self) -> crate::Result<u32> {
Ok(self.n_records)
}
}
pub fn apply_record_inspector<B: io::BufRead, R, I: VcfRecordInspector<R>>(
reader: &mut VCFReader<B>,
inspector: &mut I,
) -> crate::Result<R> {
let mut record = reader.empty_record();
loop {
let has_record = reader.next_record(&mut record)?;
if has_record {
inspector.inspect_record(&record)?;
} else {
break inspector.get_result();
}
}
}
pub struct VariantListWriter<W: Write> {
write: W,
}
impl<W: Write> VariantListWriter<W> {
pub fn new(write: W) -> VariantListWriter<W> {
VariantListWriter { write }
}
}
impl<W: Write> VcfRecordInspector<()> for VariantListWriter<W> {
fn inspect_record(&mut self, record: &VCFRecord) -> crate::Result<()> {
for id in &record.id {
self.write.write(id)?;
self.write.write(b"\n")?;
}
Ok(())
}
fn get_result(&mut self) -> crate::Result<()> {
self.write.flush()?;
Ok(())
}
}
pub struct MafWriter<W: Write> {
write: W,
}
impl<W: Write> MafWriter<W> {
pub fn new(write: W) -> MafWriter<W> {
MafWriter { write }
}
}
const KEY_GT: &[u8; 2] = b"GT";
impl<W: Write> VcfRecordInspector<()> for MafWriter<W> {
fn inspect_record(&mut self, record: &VCFRecord) -> Result<(), Error> {
static GENOTYPE_SPLIT_CHARACTERS: &[char] = &['|', '/'];
// let alts: Vec<&Vec<u8>> = record.header().alt_list().collect();
let alts = &record.alternative;
println!("alts.len() == {}", alts.len());
let mut alt_counts = vec![0u64; alts.len()];
for sample in record.header().samples() {
if let Some(genotypes) = record.genotype(sample, KEY_GT) {
for genotype_bytes in genotypes {
let genotype = std::str::from_utf8(genotype_bytes)?;
for i_allele_str in genotype.split(GENOTYPE_SPLIT_CHARACTERS) {
if let Ok(i_alt) = i_allele_str.parse::<usize>() {
if i_alt > 0 {
alt_counts[i_alt - 1] += 1;
}
}
}
}
}
}
println!("alts.len() = {}", alts.len());
for i in 0..alts.len() {
let alt = &alts[i];
let alt_count = alt_counts[i];
println!("alt = {}", std::str::from_utf8(alt).unwrap());
println!("alt_count = {}", alt_count);
let mut is_first = true;
for id in &record.id {
if is_first {
is_first = false
} else {
self.write.write(b", ")?;
}
self.write.write(&id)?;
}
self.write.write(b"\t")?;
self.write.write(&alt)?;
self.write.write(b"\t")?;
self.write.write(alt_count.to_string().as_bytes())?;
self.write.write(b"\n")?;
}
Ok(())
}
fn get_result(&mut self) -> crate::Result<()> {
self.write.flush()?;
Ok(())
}
}
|
#[doc = "Reader of register D3CCIPR"]
pub type R = crate::R<u32, super::D3CCIPR>;
#[doc = "Writer for register D3CCIPR"]
pub type W = crate::W<u32, super::D3CCIPR>;
#[doc = "Register D3CCIPR `reset()`'s with value 0"]
impl crate::ResetValue for super::D3CCIPR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "LPUART1 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum LPUART1SEL_A {
#[doc = "0: rcc_pclk_d3 selected as peripheral clock"]
RCC_PCLK_D3 = 0,
#[doc = "1: pll2_q selected as peripheral clock"]
PLL2_Q = 1,
#[doc = "2: pll3_q selected as peripheral clock"]
PLL3_Q = 2,
#[doc = "3: hsi_ker selected as peripheral clock"]
HSI_KER = 3,
#[doc = "4: csi_ker selected as peripheral clock"]
CSI_KER = 4,
#[doc = "5: LSE selected as peripheral clock"]
LSE = 5,
}
impl From<LPUART1SEL_A> for u8 {
#[inline(always)]
fn from(variant: LPUART1SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `LPUART1SEL`"]
pub type LPUART1SEL_R = crate::R<u8, LPUART1SEL_A>;
impl LPUART1SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, LPUART1SEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(LPUART1SEL_A::RCC_PCLK_D3),
1 => Val(LPUART1SEL_A::PLL2_Q),
2 => Val(LPUART1SEL_A::PLL3_Q),
3 => Val(LPUART1SEL_A::HSI_KER),
4 => Val(LPUART1SEL_A::CSI_KER),
5 => Val(LPUART1SEL_A::LSE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK_D3`"]
#[inline(always)]
pub fn is_rcc_pclk_d3(&self) -> bool {
*self == LPUART1SEL_A::RCC_PCLK_D3
}
#[doc = "Checks if the value of the field is `PLL2_Q`"]
#[inline(always)]
pub fn is_pll2_q(&self) -> bool {
*self == LPUART1SEL_A::PLL2_Q
}
#[doc = "Checks if the value of the field is `PLL3_Q`"]
#[inline(always)]
pub fn is_pll3_q(&self) -> bool {
*self == LPUART1SEL_A::PLL3_Q
}
#[doc = "Checks if the value of the field is `HSI_KER`"]
#[inline(always)]
pub fn is_hsi_ker(&self) -> bool {
*self == LPUART1SEL_A::HSI_KER
}
#[doc = "Checks if the value of the field is `CSI_KER`"]
#[inline(always)]
pub fn is_csi_ker(&self) -> bool {
*self == LPUART1SEL_A::CSI_KER
}
#[doc = "Checks if the value of the field is `LSE`"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == LPUART1SEL_A::LSE
}
}
#[doc = "Write proxy for field `LPUART1SEL`"]
pub struct LPUART1SEL_W<'a> {
w: &'a mut W,
}
impl<'a> LPUART1SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPUART1SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_pclk_d3 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk_d3(self) -> &'a mut W {
self.variant(LPUART1SEL_A::RCC_PCLK_D3)
}
#[doc = "pll2_q selected as peripheral clock"]
#[inline(always)]
pub fn pll2_q(self) -> &'a mut W {
self.variant(LPUART1SEL_A::PLL2_Q)
}
#[doc = "pll3_q selected as peripheral clock"]
#[inline(always)]
pub fn pll3_q(self) -> &'a mut W {
self.variant(LPUART1SEL_A::PLL3_Q)
}
#[doc = "hsi_ker selected as peripheral clock"]
#[inline(always)]
pub fn hsi_ker(self) -> &'a mut W {
self.variant(LPUART1SEL_A::HSI_KER)
}
#[doc = "csi_ker selected as peripheral clock"]
#[inline(always)]
pub fn csi_ker(self) -> &'a mut W {
self.variant(LPUART1SEL_A::CSI_KER)
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(LPUART1SEL_A::LSE)
}
#[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 = "I2C4 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum I2C4SEL_A {
#[doc = "0: rcc_pclk4 selected as peripheral clock"]
RCC_PCLK4 = 0,
#[doc = "1: pll3_r selected as peripheral clock"]
PLL3_R = 1,
#[doc = "2: hsi_ker selected as peripheral clock"]
HSI_KER = 2,
#[doc = "3: csi_ker selected as peripheral clock"]
CSI_KER = 3,
}
impl From<I2C4SEL_A> for u8 {
#[inline(always)]
fn from(variant: I2C4SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `I2C4SEL`"]
pub type I2C4SEL_R = crate::R<u8, I2C4SEL_A>;
impl I2C4SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> I2C4SEL_A {
match self.bits {
0 => I2C4SEL_A::RCC_PCLK4,
1 => I2C4SEL_A::PLL3_R,
2 => I2C4SEL_A::HSI_KER,
3 => I2C4SEL_A::CSI_KER,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK4`"]
#[inline(always)]
pub fn is_rcc_pclk4(&self) -> bool {
*self == I2C4SEL_A::RCC_PCLK4
}
#[doc = "Checks if the value of the field is `PLL3_R`"]
#[inline(always)]
pub fn is_pll3_r(&self) -> bool {
*self == I2C4SEL_A::PLL3_R
}
#[doc = "Checks if the value of the field is `HSI_KER`"]
#[inline(always)]
pub fn is_hsi_ker(&self) -> bool {
*self == I2C4SEL_A::HSI_KER
}
#[doc = "Checks if the value of the field is `CSI_KER`"]
#[inline(always)]
pub fn is_csi_ker(&self) -> bool {
*self == I2C4SEL_A::CSI_KER
}
}
#[doc = "Write proxy for field `I2C4SEL`"]
pub struct I2C4SEL_W<'a> {
w: &'a mut W,
}
impl<'a> I2C4SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: I2C4SEL_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "rcc_pclk4 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk4(self) -> &'a mut W {
self.variant(I2C4SEL_A::RCC_PCLK4)
}
#[doc = "pll3_r selected as peripheral clock"]
#[inline(always)]
pub fn pll3_r(self) -> &'a mut W {
self.variant(I2C4SEL_A::PLL3_R)
}
#[doc = "hsi_ker selected as peripheral clock"]
#[inline(always)]
pub fn hsi_ker(self) -> &'a mut W {
self.variant(I2C4SEL_A::HSI_KER)
}
#[doc = "csi_ker selected as peripheral clock"]
#[inline(always)]
pub fn csi_ker(self) -> &'a mut W {
self.variant(I2C4SEL_A::CSI_KER)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
#[doc = "LPTIM2 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum LPTIM2SEL_A {
#[doc = "0: rcc_pclk4 selected as peripheral clock"]
RCC_PCLK4 = 0,
#[doc = "1: pll2_p selected as peripheral clock"]
PLL2_P = 1,
#[doc = "2: pll3_r selected as peripheral clock"]
PLL3_R = 2,
#[doc = "3: LSE selected as peripheral clock"]
LSE = 3,
#[doc = "4: LSI selected as peripheral clock"]
LSI = 4,
#[doc = "5: PER selected as peripheral clock"]
PER = 5,
}
impl From<LPTIM2SEL_A> for u8 {
#[inline(always)]
fn from(variant: LPTIM2SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `LPTIM2SEL`"]
pub type LPTIM2SEL_R = crate::R<u8, LPTIM2SEL_A>;
impl LPTIM2SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, LPTIM2SEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(LPTIM2SEL_A::RCC_PCLK4),
1 => Val(LPTIM2SEL_A::PLL2_P),
2 => Val(LPTIM2SEL_A::PLL3_R),
3 => Val(LPTIM2SEL_A::LSE),
4 => Val(LPTIM2SEL_A::LSI),
5 => Val(LPTIM2SEL_A::PER),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK4`"]
#[inline(always)]
pub fn is_rcc_pclk4(&self) -> bool {
*self == LPTIM2SEL_A::RCC_PCLK4
}
#[doc = "Checks if the value of the field is `PLL2_P`"]
#[inline(always)]
pub fn is_pll2_p(&self) -> bool {
*self == LPTIM2SEL_A::PLL2_P
}
#[doc = "Checks if the value of the field is `PLL3_R`"]
#[inline(always)]
pub fn is_pll3_r(&self) -> bool {
*self == LPTIM2SEL_A::PLL3_R
}
#[doc = "Checks if the value of the field is `LSE`"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == LPTIM2SEL_A::LSE
}
#[doc = "Checks if the value of the field is `LSI`"]
#[inline(always)]
pub fn is_lsi(&self) -> bool {
*self == LPTIM2SEL_A::LSI
}
#[doc = "Checks if the value of the field is `PER`"]
#[inline(always)]
pub fn is_per(&self) -> bool {
*self == LPTIM2SEL_A::PER
}
}
#[doc = "Write proxy for field `LPTIM2SEL`"]
pub struct LPTIM2SEL_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM2SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM2SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_pclk4 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk4(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::RCC_PCLK4)
}
#[doc = "pll2_p selected as peripheral clock"]
#[inline(always)]
pub fn pll2_p(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::PLL2_P)
}
#[doc = "pll3_r selected as peripheral clock"]
#[inline(always)]
pub fn pll3_r(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::PLL3_R)
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::LSE)
}
#[doc = "LSI selected as peripheral clock"]
#[inline(always)]
pub fn lsi(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::LSI)
}
#[doc = "PER selected as peripheral clock"]
#[inline(always)]
pub fn per(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::PER)
}
#[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 << 10)) | (((value as u32) & 0x07) << 10);
self.w
}
}
#[doc = "LPTIM3,4,5 kernel clock source selection"]
pub type LPTIM345SEL_A = LPTIM2SEL_A;
#[doc = "Reader of field `LPTIM345SEL`"]
pub type LPTIM345SEL_R = crate::R<u8, LPTIM2SEL_A>;
#[doc = "Write proxy for field `LPTIM345SEL`"]
pub struct LPTIM345SEL_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM345SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM345SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_pclk4 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk4(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::RCC_PCLK4)
}
#[doc = "pll2_p selected as peripheral clock"]
#[inline(always)]
pub fn pll2_p(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::PLL2_P)
}
#[doc = "pll3_r selected as peripheral clock"]
#[inline(always)]
pub fn pll3_r(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::PLL3_R)
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::LSE)
}
#[doc = "LSI selected as peripheral clock"]
#[inline(always)]
pub fn lsi(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::LSI)
}
#[doc = "PER selected as peripheral clock"]
#[inline(always)]
pub fn per(self) -> &'a mut W {
self.variant(LPTIM2SEL_A::PER)
}
#[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 << 13)) | (((value as u32) & 0x07) << 13);
self.w
}
}
#[doc = "SAR ADC kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum ADCSEL_A {
#[doc = "0: pll2_p selected as peripheral clock"]
PLL2_P = 0,
#[doc = "1: pll3_r selected as peripheral clock"]
PLL3_R = 1,
#[doc = "2: PER selected as peripheral clock"]
PER = 2,
}
impl From<ADCSEL_A> for u8 {
#[inline(always)]
fn from(variant: ADCSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `ADCSEL`"]
pub type ADCSEL_R = crate::R<u8, ADCSEL_A>;
impl ADCSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, ADCSEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(ADCSEL_A::PLL2_P),
1 => Val(ADCSEL_A::PLL3_R),
2 => Val(ADCSEL_A::PER),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PLL2_P`"]
#[inline(always)]
pub fn is_pll2_p(&self) -> bool {
*self == ADCSEL_A::PLL2_P
}
#[doc = "Checks if the value of the field is `PLL3_R`"]
#[inline(always)]
pub fn is_pll3_r(&self) -> bool {
*self == ADCSEL_A::PLL3_R
}
#[doc = "Checks if the value of the field is `PER`"]
#[inline(always)]
pub fn is_per(&self) -> bool {
*self == ADCSEL_A::PER
}
}
#[doc = "Write proxy for field `ADCSEL`"]
pub struct ADCSEL_W<'a> {
w: &'a mut W,
}
impl<'a> ADCSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: ADCSEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "pll2_p selected as peripheral clock"]
#[inline(always)]
pub fn pll2_p(self) -> &'a mut W {
self.variant(ADCSEL_A::PLL2_P)
}
#[doc = "pll3_r selected as peripheral clock"]
#[inline(always)]
pub fn pll3_r(self) -> &'a mut W {
self.variant(ADCSEL_A::PLL3_R)
}
#[doc = "PER selected as peripheral clock"]
#[inline(always)]
pub fn per(self) -> &'a mut W {
self.variant(ADCSEL_A::PER)
}
#[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 << 16)) | (((value as u32) & 0x03) << 16);
self.w
}
}
#[doc = "Sub-Block A of SAI4 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum SAI4ASEL_A {
#[doc = "0: pll1_q selected as peripheral clock"]
PLL1_Q = 0,
#[doc = "1: pll2_p selected as peripheral clock"]
PLL2_P = 1,
#[doc = "2: pll3_p selected as peripheral clock"]
PLL3_P = 2,
#[doc = "3: i2s_ckin selected as peripheral clock"]
I2S_CKIN = 3,
#[doc = "4: PER selected as peripheral clock"]
PER = 4,
}
impl From<SAI4ASEL_A> for u8 {
#[inline(always)]
fn from(variant: SAI4ASEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `SAI4ASEL`"]
pub type SAI4ASEL_R = crate::R<u8, SAI4ASEL_A>;
impl SAI4ASEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, SAI4ASEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(SAI4ASEL_A::PLL1_Q),
1 => Val(SAI4ASEL_A::PLL2_P),
2 => Val(SAI4ASEL_A::PLL3_P),
3 => Val(SAI4ASEL_A::I2S_CKIN),
4 => Val(SAI4ASEL_A::PER),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PLL1_Q`"]
#[inline(always)]
pub fn is_pll1_q(&self) -> bool {
*self == SAI4ASEL_A::PLL1_Q
}
#[doc = "Checks if the value of the field is `PLL2_P`"]
#[inline(always)]
pub fn is_pll2_p(&self) -> bool {
*self == SAI4ASEL_A::PLL2_P
}
#[doc = "Checks if the value of the field is `PLL3_P`"]
#[inline(always)]
pub fn is_pll3_p(&self) -> bool {
*self == SAI4ASEL_A::PLL3_P
}
#[doc = "Checks if the value of the field is `I2S_CKIN`"]
#[inline(always)]
pub fn is_i2s_ckin(&self) -> bool {
*self == SAI4ASEL_A::I2S_CKIN
}
#[doc = "Checks if the value of the field is `PER`"]
#[inline(always)]
pub fn is_per(&self) -> bool {
*self == SAI4ASEL_A::PER
}
}
#[doc = "Write proxy for field `SAI4ASEL`"]
pub struct SAI4ASEL_W<'a> {
w: &'a mut W,
}
impl<'a> SAI4ASEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI4ASEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "pll1_q selected as peripheral clock"]
#[inline(always)]
pub fn pll1_q(self) -> &'a mut W {
self.variant(SAI4ASEL_A::PLL1_Q)
}
#[doc = "pll2_p selected as peripheral clock"]
#[inline(always)]
pub fn pll2_p(self) -> &'a mut W {
self.variant(SAI4ASEL_A::PLL2_P)
}
#[doc = "pll3_p selected as peripheral clock"]
#[inline(always)]
pub fn pll3_p(self) -> &'a mut W {
self.variant(SAI4ASEL_A::PLL3_P)
}
#[doc = "i2s_ckin selected as peripheral clock"]
#[inline(always)]
pub fn i2s_ckin(self) -> &'a mut W {
self.variant(SAI4ASEL_A::I2S_CKIN)
}
#[doc = "PER selected as peripheral clock"]
#[inline(always)]
pub fn per(self) -> &'a mut W {
self.variant(SAI4ASEL_A::PER)
}
#[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 << 21)) | (((value as u32) & 0x07) << 21);
self.w
}
}
#[doc = "Sub-Block B of SAI4 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum SAI4BSEL_A {
#[doc = "0: pll1_q selected as peripheral clock"]
PLL1_Q = 0,
#[doc = "1: pll2_p selected as peripheral clock"]
PLL2_P = 1,
#[doc = "2: pll3_p selected as peripheral clock"]
PLL3_P = 2,
#[doc = "3: i2s_ckin selected as peripheral clock"]
I2S_CKIN = 3,
#[doc = "4: PER selected as peripheral clock"]
PER = 4,
}
impl From<SAI4BSEL_A> for u8 {
#[inline(always)]
fn from(variant: SAI4BSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `SAI4BSEL`"]
pub type SAI4BSEL_R = crate::R<u8, SAI4BSEL_A>;
impl SAI4BSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, SAI4BSEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(SAI4BSEL_A::PLL1_Q),
1 => Val(SAI4BSEL_A::PLL2_P),
2 => Val(SAI4BSEL_A::PLL3_P),
3 => Val(SAI4BSEL_A::I2S_CKIN),
4 => Val(SAI4BSEL_A::PER),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PLL1_Q`"]
#[inline(always)]
pub fn is_pll1_q(&self) -> bool {
*self == SAI4BSEL_A::PLL1_Q
}
#[doc = "Checks if the value of the field is `PLL2_P`"]
#[inline(always)]
pub fn is_pll2_p(&self) -> bool {
*self == SAI4BSEL_A::PLL2_P
}
#[doc = "Checks if the value of the field is `PLL3_P`"]
#[inline(always)]
pub fn is_pll3_p(&self) -> bool {
*self == SAI4BSEL_A::PLL3_P
}
#[doc = "Checks if the value of the field is `I2S_CKIN`"]
#[inline(always)]
pub fn is_i2s_ckin(&self) -> bool {
*self == SAI4BSEL_A::I2S_CKIN
}
#[doc = "Checks if the value of the field is `PER`"]
#[inline(always)]
pub fn is_per(&self) -> bool {
*self == SAI4BSEL_A::PER
}
}
#[doc = "Write proxy for field `SAI4BSEL`"]
pub struct SAI4BSEL_W<'a> {
w: &'a mut W,
}
impl<'a> SAI4BSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI4BSEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "pll1_q selected as peripheral clock"]
#[inline(always)]
pub fn pll1_q(self) -> &'a mut W {
self.variant(SAI4BSEL_A::PLL1_Q)
}
#[doc = "pll2_p selected as peripheral clock"]
#[inline(always)]
pub fn pll2_p(self) -> &'a mut W {
self.variant(SAI4BSEL_A::PLL2_P)
}
#[doc = "pll3_p selected as peripheral clock"]
#[inline(always)]
pub fn pll3_p(self) -> &'a mut W {
self.variant(SAI4BSEL_A::PLL3_P)
}
#[doc = "i2s_ckin selected as peripheral clock"]
#[inline(always)]
pub fn i2s_ckin(self) -> &'a mut W {
self.variant(SAI4BSEL_A::I2S_CKIN)
}
#[doc = "PER selected as peripheral clock"]
#[inline(always)]
pub fn per(self) -> &'a mut W {
self.variant(SAI4BSEL_A::PER)
}
#[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 << 24)) | (((value as u32) & 0x07) << 24);
self.w
}
}
#[doc = "SPI6 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum SPI6SEL_A {
#[doc = "0: rcc_pclk4 selected as peripheral clock"]
RCC_PCLK4 = 0,
#[doc = "1: pll2_q selected as peripheral clock"]
PLL2_Q = 1,
#[doc = "2: pll3_q selected as peripheral clock"]
PLL3_Q = 2,
#[doc = "3: hsi_ker selected as peripheral clock"]
HSI_KER = 3,
#[doc = "4: csi_ker selected as peripheral clock"]
CSI_KER = 4,
#[doc = "5: HSE selected as peripheral clock"]
HSE = 5,
}
impl From<SPI6SEL_A> for u8 {
#[inline(always)]
fn from(variant: SPI6SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `SPI6SEL`"]
pub type SPI6SEL_R = crate::R<u8, SPI6SEL_A>;
impl SPI6SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, SPI6SEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(SPI6SEL_A::RCC_PCLK4),
1 => Val(SPI6SEL_A::PLL2_Q),
2 => Val(SPI6SEL_A::PLL3_Q),
3 => Val(SPI6SEL_A::HSI_KER),
4 => Val(SPI6SEL_A::CSI_KER),
5 => Val(SPI6SEL_A::HSE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK4`"]
#[inline(always)]
pub fn is_rcc_pclk4(&self) -> bool {
*self == SPI6SEL_A::RCC_PCLK4
}
#[doc = "Checks if the value of the field is `PLL2_Q`"]
#[inline(always)]
pub fn is_pll2_q(&self) -> bool {
*self == SPI6SEL_A::PLL2_Q
}
#[doc = "Checks if the value of the field is `PLL3_Q`"]
#[inline(always)]
pub fn is_pll3_q(&self) -> bool {
*self == SPI6SEL_A::PLL3_Q
}
#[doc = "Checks if the value of the field is `HSI_KER`"]
#[inline(always)]
pub fn is_hsi_ker(&self) -> bool {
*self == SPI6SEL_A::HSI_KER
}
#[doc = "Checks if the value of the field is `CSI_KER`"]
#[inline(always)]
pub fn is_csi_ker(&self) -> bool {
*self == SPI6SEL_A::CSI_KER
}
#[doc = "Checks if the value of the field is `HSE`"]
#[inline(always)]
pub fn is_hse(&self) -> bool {
*self == SPI6SEL_A::HSE
}
}
#[doc = "Write proxy for field `SPI6SEL`"]
pub struct SPI6SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SPI6SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI6SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_pclk4 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk4(self) -> &'a mut W {
self.variant(SPI6SEL_A::RCC_PCLK4)
}
#[doc = "pll2_q selected as peripheral clock"]
#[inline(always)]
pub fn pll2_q(self) -> &'a mut W {
self.variant(SPI6SEL_A::PLL2_Q)
}
#[doc = "pll3_q selected as peripheral clock"]
#[inline(always)]
pub fn pll3_q(self) -> &'a mut W {
self.variant(SPI6SEL_A::PLL3_Q)
}
#[doc = "hsi_ker selected as peripheral clock"]
#[inline(always)]
pub fn hsi_ker(self) -> &'a mut W {
self.variant(SPI6SEL_A::HSI_KER)
}
#[doc = "csi_ker selected as peripheral clock"]
#[inline(always)]
pub fn csi_ker(self) -> &'a mut W {
self.variant(SPI6SEL_A::CSI_KER)
}
#[doc = "HSE selected as peripheral clock"]
#[inline(always)]
pub fn hse(self) -> &'a mut W {
self.variant(SPI6SEL_A::HSE)
}
#[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 << 28)) | (((value as u32) & 0x07) << 28);
self.w
}
}
impl R {
#[doc = "Bits 0:2 - LPUART1 kernel clock source selection"]
#[inline(always)]
pub fn lpuart1sel(&self) -> LPUART1SEL_R {
LPUART1SEL_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bits 8:9 - I2C4 kernel clock source selection"]
#[inline(always)]
pub fn i2c4sel(&self) -> I2C4SEL_R {
I2C4SEL_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 10:12 - LPTIM2 kernel clock source selection"]
#[inline(always)]
pub fn lptim2sel(&self) -> LPTIM2SEL_R {
LPTIM2SEL_R::new(((self.bits >> 10) & 0x07) as u8)
}
#[doc = "Bits 13:15 - LPTIM3,4,5 kernel clock source selection"]
#[inline(always)]
pub fn lptim345sel(&self) -> LPTIM345SEL_R {
LPTIM345SEL_R::new(((self.bits >> 13) & 0x07) as u8)
}
#[doc = "Bits 16:17 - SAR ADC kernel clock source selection"]
#[inline(always)]
pub fn adcsel(&self) -> ADCSEL_R {
ADCSEL_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bits 21:23 - Sub-Block A of SAI4 kernel clock source selection"]
#[inline(always)]
pub fn sai4asel(&self) -> SAI4ASEL_R {
SAI4ASEL_R::new(((self.bits >> 21) & 0x07) as u8)
}
#[doc = "Bits 24:26 - Sub-Block B of SAI4 kernel clock source selection"]
#[inline(always)]
pub fn sai4bsel(&self) -> SAI4BSEL_R {
SAI4BSEL_R::new(((self.bits >> 24) & 0x07) as u8)
}
#[doc = "Bits 28:30 - SPI6 kernel clock source selection"]
#[inline(always)]
pub fn spi6sel(&self) -> SPI6SEL_R {
SPI6SEL_R::new(((self.bits >> 28) & 0x07) as u8)
}
}
impl W {
#[doc = "Bits 0:2 - LPUART1 kernel clock source selection"]
#[inline(always)]
pub fn lpuart1sel(&mut self) -> LPUART1SEL_W {
LPUART1SEL_W { w: self }
}
#[doc = "Bits 8:9 - I2C4 kernel clock source selection"]
#[inline(always)]
pub fn i2c4sel(&mut self) -> I2C4SEL_W {
I2C4SEL_W { w: self }
}
#[doc = "Bits 10:12 - LPTIM2 kernel clock source selection"]
#[inline(always)]
pub fn lptim2sel(&mut self) -> LPTIM2SEL_W {
LPTIM2SEL_W { w: self }
}
#[doc = "Bits 13:15 - LPTIM3,4,5 kernel clock source selection"]
#[inline(always)]
pub fn lptim345sel(&mut self) -> LPTIM345SEL_W {
LPTIM345SEL_W { w: self }
}
#[doc = "Bits 16:17 - SAR ADC kernel clock source selection"]
#[inline(always)]
pub fn adcsel(&mut self) -> ADCSEL_W {
ADCSEL_W { w: self }
}
#[doc = "Bits 21:23 - Sub-Block A of SAI4 kernel clock source selection"]
#[inline(always)]
pub fn sai4asel(&mut self) -> SAI4ASEL_W {
SAI4ASEL_W { w: self }
}
#[doc = "Bits 24:26 - Sub-Block B of SAI4 kernel clock source selection"]
#[inline(always)]
pub fn sai4bsel(&mut self) -> SAI4BSEL_W {
SAI4BSEL_W { w: self }
}
#[doc = "Bits 28:30 - SPI6 kernel clock source selection"]
#[inline(always)]
pub fn spi6sel(&mut self) -> SPI6SEL_W {
SPI6SEL_W { w: self }
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use common_base::base::tokio;
use common_meta_raft_store::state_machine::testing::pretty_snapshot;
use common_meta_raft_store::state_machine::testing::snapshot_logs;
use common_meta_raft_store::state_machine::SerializableSnapshot;
use common_meta_sled_store::openraft::async_trait::async_trait;
use common_meta_sled_store::openraft::testing::StoreBuilder;
use common_meta_sled_store::openraft::RaftSnapshotBuilder;
use common_meta_sled_store::openraft::RaftStorage;
use common_meta_sled_store::openraft::StorageHelper;
use common_meta_types::new_log_id;
use common_meta_types::CommittedLeaderId;
use common_meta_types::Entry;
use common_meta_types::EntryPayload;
use common_meta_types::LogId;
use common_meta_types::Membership;
use common_meta_types::StorageError;
use common_meta_types::StoredMembership;
use common_meta_types::TypeConfig;
use common_meta_types::Vote;
use databend_meta::init_meta_ut;
use databend_meta::store::RaftStoreBare;
use databend_meta::Opened;
use maplit::btreeset;
use pretty_assertions::assert_eq;
use tracing::debug;
use tracing::info;
use crate::tests::service::MetaSrvTestContext;
struct MetaStoreBuilder {
pub test_contexts: Arc<Mutex<Vec<MetaSrvTestContext>>>,
}
#[async_trait]
impl StoreBuilder<TypeConfig, RaftStoreBare> for MetaStoreBuilder {
async fn run_test<Fun, Ret, Res>(&self, t: Fun) -> Result<Ret, StorageError>
where
Res: Future<Output = Result<Ret, StorageError>> + Send,
Fun: Fn(RaftStoreBare) -> Res + Sync + Send,
{
let tc = MetaSrvTestContext::new(555);
let sto = RaftStoreBare::open_create(&tc.config.raft_config, None, Some(()))
.await
.expect("fail to create store");
{
let mut tcs = self.test_contexts.lock().unwrap();
tcs.push(tc);
}
t(sto).await
}
}
#[test]
fn test_impl_raft_storage() -> anyhow::Result<()> {
let (_log_guards, ut_span) = init_meta_ut!();
let _ent = ut_span.enter();
common_meta_sled_store::openraft::testing::Suite::test_all(MetaStoreBuilder {
test_contexts: Arc::new(Mutex::new(vec![])),
})?;
Ok(())
}
#[async_entry::test(worker_threads = 3, init = "init_meta_ut!()", tracing_span = "debug")]
async fn test_meta_store_restart() -> anyhow::Result<()> {
// - Create a meta store
// - Update meta store
// - Close and reopen it
// - Test state is restored: hard state, log, state machine
let id = 3;
let tc = MetaSrvTestContext::new(id);
info!("--- new meta store");
{
let mut sto = RaftStoreBare::open_create(&tc.config.raft_config, None, Some(())).await?;
assert_eq!(id, sto.id);
assert!(!sto.is_opened());
assert_eq!(None, sto.read_vote().await?);
info!("--- update metasrv");
sto.save_vote(&Vote::new(10, 5)).await?;
sto.append_to_log(&[&Entry {
log_id: LogId::new(CommittedLeaderId::new(1, 2), 1),
payload: EntryPayload::Blank,
}])
.await?;
sto.apply_to_state_machine(&[&Entry {
log_id: LogId::new(CommittedLeaderId::new(1, 2), 2),
payload: EntryPayload::Blank,
}])
.await?;
}
info!("--- reopen meta store");
{
let mut sto = RaftStoreBare::open_create(&tc.config.raft_config, Some(()), None).await?;
assert_eq!(id, sto.id);
assert!(sto.is_opened());
assert_eq!(Some(Vote::new(10, 5)), sto.read_vote().await?);
assert_eq!(
LogId::new(CommittedLeaderId::new(1, 2), 1),
StorageHelper::new(&mut sto).get_log_id(1).await?
);
assert_eq!(
Some(LogId::new(CommittedLeaderId::new(1, 2), 2)),
sto.last_applied_state().await?.0
);
}
Ok(())
}
#[async_entry::test(worker_threads = 3, init = "init_meta_ut!()", tracing_span = "debug")]
async fn test_meta_store_build_snapshot() -> anyhow::Result<()> {
// - Create a metasrv
// - Apply logs
// - Create a snapshot check snapshot state
let id = 3;
let tc = MetaSrvTestContext::new(id);
let mut sto = RaftStoreBare::open_create(&tc.config.raft_config, None, Some(())).await?;
info!("--- feed logs and state machine");
let (logs, want) = snapshot_logs();
sto.log.append(&logs).await?;
for l in logs.iter() {
sto.state_machine.write().await.apply(l).await?;
}
let curr_snap = sto.build_snapshot().await?;
assert_eq!(Some(new_log_id(1, 0, 9)), curr_snap.meta.last_log_id);
info!("--- check snapshot");
{
let data = curr_snap.snapshot.into_inner();
let ser_snap: SerializableSnapshot = serde_json::from_slice(&data)?;
let res = pretty_snapshot(&ser_snap.kvs);
debug!("res: {:?}", res);
assert_eq!(want, res);
}
Ok(())
}
#[async_entry::test(worker_threads = 3, init = "init_meta_ut!()", tracing_span = "debug")]
async fn test_meta_store_current_snapshot() -> anyhow::Result<()> {
// - Create a metasrv
// - Apply logs
// - Create a snapshot check snapshot state
let id = 3;
let tc = MetaSrvTestContext::new(id);
let mut sto = RaftStoreBare::open_create(&tc.config.raft_config, None, Some(())).await?;
info!("--- feed logs and state machine");
let (logs, want) = snapshot_logs();
sto.log.append(&logs).await?;
for l in logs.iter() {
sto.state_machine.write().await.apply(l).await?;
}
sto.build_snapshot().await?;
info!("--- check get_current_snapshot");
let curr_snap = sto.get_current_snapshot().await?.unwrap();
assert_eq!(Some(new_log_id(1, 0, 9)), curr_snap.meta.last_log_id);
info!("--- check snapshot");
{
let data = curr_snap.snapshot.into_inner();
let ser_snap: SerializableSnapshot = serde_json::from_slice(&data)?;
let res = pretty_snapshot(&ser_snap.kvs);
debug!("res: {:?}", res);
assert_eq!(want, res);
}
Ok(())
}
#[async_entry::test(worker_threads = 3, init = "init_meta_ut!()", tracing_span = "debug")]
async fn test_meta_store_install_snapshot() -> anyhow::Result<()> {
// - Create a metasrv
// - Feed logs
// - Create a snapshot
// - Create a new metasrv and restore it by install the snapshot
let (logs, want) = snapshot_logs();
let id = 3;
let snap;
{
let tc = MetaSrvTestContext::new(id);
let mut sto = RaftStoreBare::open_create(&tc.config.raft_config, None, Some(())).await?;
info!("--- feed logs and state machine");
sto.log.append(&logs).await?;
for l in logs.iter() {
sto.state_machine.write().await.apply(l).await?;
}
snap = sto.build_snapshot().await?;
}
let data = snap.snapshot.into_inner();
info!("--- reopen a new metasrv to install snapshot");
{
let tc = MetaSrvTestContext::new(id);
let mut sto = RaftStoreBare::open_create(&tc.config.raft_config, None, Some(())).await?;
info!("--- rejected because old sm is not cleaned");
{
sto.raft_state.write_state_machine_id(&(1, 2)).await?;
let res = sto.do_install_snapshot(&data).await;
assert!(res.is_err(), "different ids disallow installing snapshot");
assert!(
res.unwrap_err()
.to_string()
.starts_with("another snapshot install is not finished yet: 1 2")
);
}
info!("--- install snapshot");
{
sto.raft_state.write_state_machine_id(&(0, 0)).await?;
sto.do_install_snapshot(&data).await?;
}
info!("--- check installed meta");
{
assert_eq!((1, 1), sto.raft_state.read_state_machine_id()?);
let mem = sto.state_machine.write().await.get_membership()?;
assert_eq!(
Some(StoredMembership::new(
Some(LogId::new(CommittedLeaderId::new(1, 0), 5)),
Membership::new(vec![btreeset! {4,5,6}], ())
)),
mem
);
let last_applied = sto.state_machine.write().await.get_last_applied()?;
assert_eq!(
Some(LogId::new(CommittedLeaderId::new(1, 0), 9)),
last_applied
);
}
info!("--- check snapshot");
{
let curr_snap = sto.build_snapshot().await?;
let data = curr_snap.snapshot.into_inner();
let ser_snap: SerializableSnapshot = serde_json::from_slice(&data)?;
let res = pretty_snapshot(&ser_snap.kvs);
debug!("res: {:?}", res);
assert_eq!(want, res);
}
}
Ok(())
}
|
use actix::prelude::*;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use starcoin_accumulator::AccumulatorNode;
use starcoin_crypto::HashValue;
use starcoin_state_tree::StateNode;
use starcoin_types::peer_info::PeerId;
use starcoin_types::{
block::{Block, BlockHeader, BlockInfo},
transaction::SignedUserTransaction,
};
use std::cmp::Ordering;
#[derive(Message, Clone, Debug)]
#[rtype(result = "()")]
pub struct StartSyncTxnEvent;
#[derive(Message, Clone, Debug)]
#[rtype(result = "()")]
pub struct PeerNewBlock {
peer_id: PeerId,
new_block: Block,
}
impl PeerNewBlock {
pub fn new(peer_id: PeerId, new_block: Block) -> Self {
PeerNewBlock { peer_id, new_block }
}
pub fn get_peer_id(&self) -> PeerId {
self.peer_id.clone()
}
pub fn get_block(&self) -> Block {
self.new_block.clone()
}
}
#[derive(Message, Clone, Serialize, Deserialize, Debug)]
#[rtype(result = "Result<()>")]
pub enum SyncRpcRequest {
GetHashByNumberMsg(GetHashByNumberMsg),
GetDataByHashMsg(GetDataByHashMsg),
GetStateNodeByNodeHash(HashValue),
GetAccumulatorNodeByNodeHash(HashValue),
GetTxns(GetTxns),
}
#[derive(Message, Clone, Serialize, Deserialize)]
#[rtype(result = "Result<()>")]
pub enum SyncRpcResponse {
BatchHashByNumberMsg(BatchHashByNumberMsg),
BatchHeaderAndBodyMsg(BatchHeaderMsg, BatchBodyMsg, BatchBlockInfo),
GetStateNodeByNodeHash(StateNode),
GetAccumulatorNodeByNodeHash(AccumulatorNode),
GetTxns(TransactionsData),
}
#[derive(Debug, Message, Clone, Serialize, Deserialize)]
#[rtype(result = "()")]
pub enum SyncNotify {
ClosePeerMsg(PeerId),
NewHeadBlock(PeerId, Block),
NewPeerMsg(PeerId),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GetTxns;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TransactionsData {
pub txns: Vec<SignedUserTransaction>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GetHashByNumberMsg {
pub numbers: Vec<u64>,
}
#[derive(Eq, Serialize, Deserialize, PartialEq, PartialOrd, Clone, Debug)]
pub struct HashWithNumber {
pub hash: HashValue,
pub number: u64,
}
impl Ord for HashWithNumber {
fn cmp(&self, other: &HashWithNumber) -> Ordering {
match self.number.cmp(&other.number) {
Ordering::Equal => {
return self.hash.cmp(&other.hash);
}
ordering => return ordering,
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
pub struct BatchHashByNumberMsg {
pub hashs: Vec<HashWithNumber>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum DataType {
HEADER,
BODY,
INFO,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct GetDataByHashMsg {
pub hashs: Vec<HashValue>,
pub data_type: DataType,
}
#[derive(Clone, Eq, Serialize, Deserialize, PartialEq, Debug)]
pub struct BatchHeaderMsg {
pub headers: Vec<BlockHeader>,
}
#[derive(Eq, Serialize, Deserialize, PartialEq, Clone, Debug)]
pub struct BlockBody {
pub hash: HashValue,
pub transactions: Vec<SignedUserTransaction>,
}
impl PartialOrd for BlockBody {
fn partial_cmp(&self, other: &BlockBody) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for BlockBody {
fn cmp(&self, other: &BlockBody) -> Ordering {
return self.hash.cmp(&other.hash);
}
}
#[derive(Eq, Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct BatchBodyMsg {
pub bodies: Vec<BlockBody>,
}
#[derive(Eq, Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct BatchBlockInfo {
pub infos: Vec<BlockInfo>,
}
|
use libc::c_char;
use libc::c_int;
use std::ffi::CStr;
/// Execute a dice roll based on the given notation
#[no_mangle]
pub unsafe extern "C" fn roll_dice(notation: *const c_char) -> c_int
{
let notation = CStr::from_ptr(notation);
let result = dicenotation::roll_dice::<i32>(notation.to_str().unwrap());
let result = result.unwrap_or(-1);
result
} |
use super::*;
use std::convert::TryInto;
use proptest::prop_assert;
use proptest::strategy::Just;
use liblumen_alloc::erts::term::prelude::{Boxed, Map};
#[test]
fn with_same_key_in_map1_and_map2_uses_value_from_map2() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term(arc_process.clone()),
strategy::term(arc_process.clone()),
strategy::term(arc_process.clone()),
)
},
|(arc_process, key, value1, value2)| {
let map1 = arc_process.map_from_slice(&[(key, value1)]);
let map2 = arc_process.map_from_slice(&[(key, value2)]);
let result_map3 = result(&arc_process, map1, map2);
prop_assert!(result_map3.is_ok());
let map3 = result_map3.unwrap();
let map3_map: Boxed<Map> = map3.try_into().unwrap();
prop_assert_eq!(map3_map.get(key), Some(value2));
Ok(())
},
);
}
#[test]
fn with_different_keys_in_map2_and_map2_combines_keys() {
TestRunner::new(Config::with_source_file(file!()))
.run(
&strategy::process()
.prop_flat_map(|arc_process| {
(Just(arc_process.clone()), strategy::term(arc_process))
})
.prop_flat_map(|(arc_process, key1)| {
(
Just(arc_process.clone()),
Just(key1),
strategy::term(arc_process)
.prop_filter("Key1 and Key2 must be different", move |key2| {
*key2 != key1
}),
)
})
.prop_flat_map(|(arc_process, key1, key2)| {
(
Just(arc_process.clone()),
Just(key1),
strategy::term(arc_process.clone()),
Just(key2),
strategy::term(arc_process),
)
}),
|(arc_process, key1, value1, key2, value2)| {
let map1 = arc_process.map_from_slice(&[(key1, value1)]);
let map2 = arc_process.map_from_slice(&[(key2, value2)]);
let result_map3 = result(&arc_process, map1, map2);
prop_assert!(result_map3.is_ok());
let map3 = result_map3.unwrap();
let map3_map: Boxed<Map> = map3.try_into().unwrap();
prop_assert_eq!(map3_map.get(key1), Some(value1));
prop_assert_eq!(map3_map.get(key2), Some(value2));
Ok(())
},
)
.unwrap();
}
|
//! Handling of different call formats.
use std::convert::TryInto;
use anyhow::anyhow;
use byteorder::{BigEndian, WriteBytesExt};
use crate::{
context::Context,
core::common::crypto::mrae::deoxysii,
crypto::signature::context::get_chain_context_for,
keymanager, module,
modules::core::Error,
types::{
self,
transaction::{Call, CallFormat, CallResult},
},
};
/// Additional metadata required by the result encoding function.
pub enum Metadata {
Empty,
EncryptedX25519DeoxysII {
/// Caller's ephemeral public key used for X25519.
pk: [u8; 32],
/// Secret key.
sk: keymanager::PrivateKey,
/// Transaction index within the batch.
index: usize,
},
}
/// Derive the key pair ID for the call data encryption key pair.
pub fn get_key_pair_id<C: Context>(ctx: &C) -> keymanager::KeyPairId {
keymanager::get_key_pair_id(&[
&get_chain_context_for(types::callformat::CALL_DATA_KEY_PAIR_ID_CONTEXT_BASE),
&ctx.epoch().to_be_bytes(),
])
}
/// Decode call arguments.
///
/// Returns `Some((Call, Metadata))` when processing should proceed and `None` in case further
/// execution needs to be deferred (e.g., because key manager access is required).
pub fn decode_call<C: Context>(
ctx: &C,
call: Call,
index: usize,
) -> Result<Option<(Call, Metadata)>, Error> {
match call.format {
// In case of the plain-text data format, we simply pass on the call unchanged.
CallFormat::Plain => Ok(Some((call, Metadata::Empty))),
// Encrypted data format using X25519 key exchange and Deoxys-II symmetric encryption.
CallFormat::EncryptedX25519DeoxysII => {
// Method must be empty.
if !call.method.is_empty() {
return Err(Error::InvalidCallFormat(anyhow!("non-empty method")));
}
// Body needs to follow the specified envelope.
let envelope: types::callformat::CallEnvelopeX25519DeoxysII =
cbor::from_value(call.body)
.map_err(|_| Error::InvalidCallFormat(anyhow!("bad envelope")))?;
// Make sure a key manager is available in this runtime.
let key_manager = ctx.key_manager().ok_or_else(|| {
Error::InvalidCallFormat(anyhow!("confidential transactions not available"))
})?;
// If we are only doing checks, this is the most that we can do as in this case we may
// be unable to access the key manager.
if ctx.is_check_only() || ctx.is_simulation() {
return Ok(None);
}
// Get transaction key pair from the key manager. Note that only the `input_keypair`
// portion is used.
let keypair = key_manager
.get_or_create_keys(get_key_pair_id(ctx))
.map_err(|err| Error::Abort(err.into()))?;
let sk = keypair.input_keypair.sk;
// Derive shared secret via X25519 and open the sealed box.
let data =
deoxysii::box_open(&envelope.nonce, envelope.data, vec![], &envelope.pk, &sk.0)
.map_err(Error::InvalidCallFormat)?;
let call = cbor::from_slice(&data)
.map_err(|_| Error::InvalidCallFormat(anyhow!("malformed call")))?;
Ok(Some((
call,
Metadata::EncryptedX25519DeoxysII {
pk: envelope.pk,
sk,
index,
},
)))
}
}
}
/// Encode call results.
pub fn encode_result<C: Context>(
ctx: &C,
result: module::CallResult,
metadata: Metadata,
) -> CallResult {
match metadata {
// In case of the plain-text data format, we simply pass on the data unchanged.
Metadata::Empty => result.into(),
// Encrypted data format using X25519 key exchange and Deoxys-II symmetric encryption.
Metadata::EncryptedX25519DeoxysII { pk, sk, index } => {
// Generate nonce for the output as Round (8 bytes) || Index (4 bytes) || 00 00 00.
let mut nonce = Vec::with_capacity(deoxysii::NONCE_SIZE);
nonce
.write_u64::<BigEndian>(ctx.runtime_header().round)
.unwrap();
nonce
.write_u32::<BigEndian>(index.try_into().unwrap())
.unwrap();
nonce.extend(&[0, 0, 0]);
let nonce = nonce.try_into().unwrap();
// Serialize result.
let result: CallResult = result.into();
let result = cbor::to_vec(result);
// Seal the result.
let data = deoxysii::box_seal(&nonce, result, vec![], &pk, &sk.0).unwrap();
// Generate an envelope.
let envelope =
cbor::to_value(types::callformat::ResultEnvelopeX25519DeoxysII { nonce, data });
CallResult::Unknown(envelope)
}
}
}
|
use core::marker::PhantomData;
use embedded_graphics::{
draw_target::DrawTarget,
prelude::{PixelColor, Primitive},
primitives::PrimitiveStyle,
Drawable,
};
use embedded_gui::{
data::WidgetData,
widgets::slider::{Slider, SliderDirection, SliderFields, SliderProperties},
WidgetRenderer,
};
use crate::{themes::default::DefaultTheme, EgCanvas, ToRectangle};
pub mod binary_color;
pub mod rgb;
pub trait ScrollbarVisualState<C>
where
C: PixelColor,
{
const BACKGROUND_FILL_COLOR: Option<C>;
const BACKGROUND_BORDER_COLOR: Option<C>;
const BACKGROUND_BORDER_THICKNESS: u32 = 0;
const BORDER_COLOR: Option<C>;
const FILL_COLOR: Option<C>;
const BORDER_THICKNESS: u32 = 0;
fn styles() -> (PrimitiveStyle<C>, PrimitiveStyle<C>) {
let mut style = PrimitiveStyle::default();
let mut bg_style = PrimitiveStyle::default();
style.fill_color = Self::FILL_COLOR;
style.stroke_width = Self::BORDER_THICKNESS;
style.stroke_color = Self::BORDER_COLOR;
bg_style.fill_color = Self::BACKGROUND_FILL_COLOR;
bg_style.stroke_width = Self::BACKGROUND_BORDER_THICKNESS;
bg_style.stroke_color = Self::BACKGROUND_BORDER_COLOR;
(style, bg_style)
}
}
pub trait ScrollbarVisualStyle<C>: Default
where
C: PixelColor,
{
type Direction: SliderDirection;
const THICKNESS: u32;
type Idle: ScrollbarVisualState<C>;
type Hovered: ScrollbarVisualState<C>;
type Dragged: ScrollbarVisualState<C>;
type Inactive: ScrollbarVisualState<C>;
fn draw<DT: DrawTarget<Color = C>, D>(
&self,
canvas: &mut crate::EgCanvas<DT>,
slider: &SliderFields<ScrollbarProperties<C, Self>, D>,
) -> Result<(), DT::Error> {
let (slider_style, bg_style) = if slider.state.has_state(Slider::STATE_INACTIVE) {
Self::Inactive::styles()
} else if slider.state.has_state(Slider::STATE_DRAGGED) {
Self::Dragged::styles()
} else if slider.state.has_state(Slider::STATE_HOVERED) {
Self::Hovered::styles()
} else {
Self::Idle::styles()
};
// Background
slider
.bounds
.to_rectangle()
.into_styled(bg_style)
.draw(&mut canvas.target)?;
// Foreground
slider
.slider_bounds()
.to_rectangle()
.into_styled(slider_style)
.draw(&mut canvas.target)
}
}
pub struct ScrollbarProperties<C, VS>
where
C: PixelColor,
VS: ScrollbarVisualStyle<C>,
{
visual: VS,
window_length: u32,
_marker: PhantomData<C>,
}
impl<C, VS> ScrollbarProperties<C, VS>
where
C: PixelColor,
VS: ScrollbarVisualStyle<C>,
{
pub fn new() -> Self {
Self {
visual: VS::default(),
window_length: 0,
_marker: PhantomData,
}
}
}
impl<C, VS> SliderProperties for ScrollbarProperties<C, VS>
where
C: PixelColor,
VS: ScrollbarVisualStyle<C>,
{
type Direction = VS::Direction;
const THICKNESS: u32 = VS::THICKNESS;
fn length(&self) -> u32 {
self.window_length
}
fn set_length(&mut self, length: u32) {
self.window_length = length.max(3);
}
}
impl<VS, C, DT, D> WidgetRenderer<EgCanvas<DT>> for Slider<ScrollbarProperties<C, VS>, D>
where
C: PixelColor,
DT: DrawTarget<Color = C>,
D: WidgetData,
VS: ScrollbarVisualStyle<C>,
{
fn draw(&mut self, canvas: &mut EgCanvas<DT>) -> Result<(), DT::Error> {
self.fields.properties.visual.draw(canvas, &self.fields)
}
}
pub type StyledVerticalScrollbar<C> =
Slider<ScrollbarProperties<C, <C as DefaultTheme>::VerticalScrollbar>, ()>;
pub type StyledHorizontalScrollbar<C> =
Slider<ScrollbarProperties<C, <C as DefaultTheme>::HorizontalScrollbar>, ()>;
pub fn vertical_scrollbar<C: DefaultTheme>() -> StyledVerticalScrollbar<C> {
Slider::new(0..=0, ScrollbarProperties::new())
}
pub fn horizontal_scrollbar<C: DefaultTheme>() -> StyledHorizontalScrollbar<C> {
Slider::new(0..=0, ScrollbarProperties::new())
}
|
//! Used in the creation of a [`PartitionsSource`](crate::PartitionsSource) of PartitionIds
//! for the [`LocalScheduler`](crate::LocalScheduler).
//!
//! The filtering and fetching operations in these [`PartitionsSource`](crate::PartitionsSource) implementations
//! are limited to the PartitionId and metadata only, and not dependent upon any file IO.
pub(crate) mod catalog_all;
pub(crate) mod catalog_to_compact;
pub(crate) mod filter;
pub(crate) mod never_skipped;
|
// 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 clap::{App, AppSettings, SubCommand, ArgMatches};
use alloc::string::String;
use super::super::super::qlib::common::*;
use super::super::super::qlib::path::*;
use super::super::cmd::config::*;
use super::super::oci::*;
use super::super::container::container::*;
use super::command::*;
#[derive(Debug)]
pub struct CreateCmd {
pub id: String,
pub bundleDir: String,
pub consoleSocket: String,
pub pivot: bool,
pub pid: String,
}
impl CreateCmd {
pub fn Init(cmd_matches: &ArgMatches) -> Result<Self> {
return Ok(Self {
id: cmd_matches.value_of("id").unwrap().to_string(),
bundleDir: cmd_matches.value_of("bundle").unwrap().to_string(),
consoleSocket: cmd_matches.value_of("console-socket").unwrap().to_string(),
pivot: !cmd_matches.is_present("no-pivot"),
pid: cmd_matches.value_of("p").unwrap().to_string(),
})
}
pub fn SubCommand<'a, 'b>(common: &CommonArgs<'a, 'b>) -> App<'a, 'b> {
return SubCommand::with_name("create")
.setting(AppSettings::ColoredHelp)
.arg(&common.id_arg)
.arg(&common.bundle_arg)
.arg(&common.consoleSocket_arg)
.arg(&common.no_pivot_arg)
.arg(&common.pid_arg)
.arg(&common.init_arg)
.about("Create a container (to be started later)");
}
pub fn Run(&self, gCfg: &GlobalConfig) -> Result<()> {
let specfile = Join(&self.bundleDir, "config.json");
let spec = Spec::load(&specfile).unwrap();
Container::Create(
&self.id,
RunAction::Create,
spec,
gCfg,
&self.bundleDir,
&self.consoleSocket,
&self.pid,
"",
true,
self.pivot
)?;
//eprintln!("Application error: teststasdfasfd");
//::std::process::exit(1);
return Ok(())
}
} |
mod day1;
mod day2;
mod day3;
mod day4;
fn main() {
println!("Hello, world!");
let mut filename = "inputs/day1".to_string();
day1::solve_day1(&filename);
filename = "inputs/day2".to_string();
day2::solve_day2(&filename);
filename = "inputs/day3".to_string();
day3::solve_day3(&filename);
filename = "inputs/day4".to_string();
day4::solve_day4(&filename);
}
|
// Divide Two Integers
// https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/587/week-4-february-22nd-february-28th/3654/
pub struct Solution;
use std::convert::TryInto;
impl Solution {
pub fn divide(dividend: i32, divisor: i32) -> i32 {
let negative = dividend.is_negative() ^ divisor.is_negative();
let mut num = (dividend as i64).abs();
let den = (divisor as i64).abs();
let mut res = 0_i64;
for exp2 in (0..32).rev() {
res <<= 1;
let prod = den << exp2;
if num >= prod {
num -= prod;
res += 1;
}
}
(if negative { -res } else { res })
.try_into()
.unwrap_or(std::i32::MAX)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn check(dividend: i32, divisor: i32) {
let expected = dividend.checked_div(divisor).unwrap_or(std::i32::MAX);
assert_eq!(Solution::divide(dividend, divisor), expected);
}
#[test]
fn example1() {
check(10, 3);
}
#[test]
fn example2() {
check(7, -3);
}
#[test]
fn example3() {
check(0, 1);
}
#[test]
fn example4() {
check(1, 1);
}
#[test]
fn test_big() {
check(12345678, 123);
}
#[test]
fn test_overflow() {
check(-2147483648, -1);
}
#[test]
fn test_no_overflow1() {
check(-2147483648, 1);
}
#[test]
fn test_no_overflow2() {
check(-2147483648, -2147483648);
}
#[test]
fn test_no_overflow3() {
check(-2147483648, 2147483647);
}
}
|
//use proconio::{input, fastout};
use proconio::input;
use num::*;
const L: u64 = 1000000000000000000;
//#[fastout]
fn main() {
input! {
n: usize,
mut d: [u64; n],
}
let lim = bigint::BigUint::from_u64(L).unwrap();
let mut r = bigint::BigUint::from_u64(1).unwrap();
d.sort();
if d[0] == 0 {
println!("0");
return;
}
for a in d {
r *= a;
if r > lim {
println!("-1");
return;
}
}
println!("{}", r);
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Devices_Pwm_Provider")]
pub mod Provider;
#[repr(transparent)]
#[doc(hidden)]
pub struct IPwmController(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPwmController {
type Vtable = IPwmController_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc45f5c85_d2e8_42cf_9bd6_cf5ed029e6a7);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPwmController_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 i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, desiredfrequency: f64, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pinnumber: i32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPwmControllerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPwmControllerStatics {
type Vtable = IPwmControllerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4263bda1_8946_4404_bd48_81dd124af4d9);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPwmControllerStatics_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 = "Devices_Pwm_Provider", feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, provider: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Devices_Pwm_Provider", feature = "Foundation", feature = "Foundation_Collections")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPwmControllerStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPwmControllerStatics2 {
type Vtable = IPwmControllerStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x44fc5b1f_f119_4bdd_97ad_f76ef986736d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPwmControllerStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPwmControllerStatics3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPwmControllerStatics3 {
type Vtable = IPwmControllerStatics3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb2581871_0229_4344_ae3f_9b7cd0e66b94);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPwmControllerStatics3_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, friendlyname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPwmPin(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPwmPin {
type Vtable = IPwmPin_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x22972dc8_c6cf_4821_b7f9_c6454fb6af79);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPwmPin_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dutycyclepercentage: f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut PwmPulsePolarity) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: PwmPulsePolarity) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PwmController(pub ::windows::core::IInspectable);
impl PwmController {
pub fn PinCount(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn ActualFrequency(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn SetDesiredFrequency(&self, desiredfrequency: f64) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), desiredfrequency, &mut result__).from_abi::<f64>(result__)
}
}
pub fn MinFrequency(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn MaxFrequency(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn OpenPin(&self, pinnumber: i32) -> ::windows::core::Result<PwmPin> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), pinnumber, &mut result__).from_abi::<PwmPin>(result__)
}
}
#[cfg(all(feature = "Devices_Pwm_Provider", feature = "Foundation", feature = "Foundation_Collections"))]
pub fn GetControllersAsync<'a, Param0: ::windows::core::IntoParam<'a, Provider::IPwmProvider>>(provider: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PwmController>>> {
Self::IPwmControllerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), provider.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<PwmController>>>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn GetDefaultAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PwmController>> {
Self::IPwmControllerStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PwmController>>(result__)
})
}
pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IPwmControllerStatics3(|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 GetDeviceSelectorFromFriendlyName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(friendlyname: Param0) -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IPwmControllerStatics3(|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), friendlyname.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<PwmController>> {
Self::IPwmControllerStatics3(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<PwmController>>(result__)
})
}
pub fn IPwmControllerStatics<R, F: FnOnce(&IPwmControllerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PwmController, IPwmControllerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IPwmControllerStatics2<R, F: FnOnce(&IPwmControllerStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PwmController, IPwmControllerStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IPwmControllerStatics3<R, F: FnOnce(&IPwmControllerStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PwmController, IPwmControllerStatics3> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for PwmController {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Pwm.PwmController;{c45f5c85-d2e8-42cf-9bd6-cf5ed029e6a7})");
}
unsafe impl ::windows::core::Interface for PwmController {
type Vtable = IPwmController_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc45f5c85_d2e8_42cf_9bd6_cf5ed029e6a7);
}
impl ::windows::core::RuntimeName for PwmController {
const NAME: &'static str = "Windows.Devices.Pwm.PwmController";
}
impl ::core::convert::From<PwmController> for ::windows::core::IUnknown {
fn from(value: PwmController) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PwmController> for ::windows::core::IUnknown {
fn from(value: &PwmController) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PwmController {
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 PwmController {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PwmController> for ::windows::core::IInspectable {
fn from(value: PwmController) -> Self {
value.0
}
}
impl ::core::convert::From<&PwmController> for ::windows::core::IInspectable {
fn from(value: &PwmController) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PwmController {
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 PwmController {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for PwmController {}
unsafe impl ::core::marker::Sync for PwmController {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PwmPin(pub ::windows::core::IInspectable);
impl PwmPin {
pub fn Controller(&self) -> ::windows::core::Result<PwmController> {
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::<PwmController>(result__)
}
}
pub fn GetActiveDutyCyclePercentage(&self) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn SetActiveDutyCyclePercentage(&self, dutycyclepercentage: f64) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), dutycyclepercentage).ok() }
}
pub fn Polarity(&self) -> ::windows::core::Result<PwmPulsePolarity> {
let this = self;
unsafe {
let mut result__: PwmPulsePolarity = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<PwmPulsePolarity>(result__)
}
}
pub fn SetPolarity(&self, value: PwmPulsePolarity) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Start(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() }
}
pub fn Stop(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
pub fn IsStarted(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Close(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for PwmPin {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Pwm.PwmPin;{22972dc8-c6cf-4821-b7f9-c6454fb6af79})");
}
unsafe impl ::windows::core::Interface for PwmPin {
type Vtable = IPwmPin_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x22972dc8_c6cf_4821_b7f9_c6454fb6af79);
}
impl ::windows::core::RuntimeName for PwmPin {
const NAME: &'static str = "Windows.Devices.Pwm.PwmPin";
}
impl ::core::convert::From<PwmPin> for ::windows::core::IUnknown {
fn from(value: PwmPin) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PwmPin> for ::windows::core::IUnknown {
fn from(value: &PwmPin) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PwmPin {
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 PwmPin {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PwmPin> for ::windows::core::IInspectable {
fn from(value: PwmPin) -> Self {
value.0
}
}
impl ::core::convert::From<&PwmPin> for ::windows::core::IInspectable {
fn from(value: &PwmPin) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PwmPin {
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 PwmPin {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<PwmPin> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: PwmPin) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation")]
impl ::core::convert::TryFrom<&PwmPin> for super::super::Foundation::IClosable {
type Error = ::windows::core::Error;
fn try_from(value: &PwmPin) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for PwmPin {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &PwmPin {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> {
::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PwmPin {}
unsafe impl ::core::marker::Sync for PwmPin {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PwmPulsePolarity(pub i32);
impl PwmPulsePolarity {
pub const ActiveHigh: PwmPulsePolarity = PwmPulsePolarity(0i32);
pub const ActiveLow: PwmPulsePolarity = PwmPulsePolarity(1i32);
}
impl ::core::convert::From<i32> for PwmPulsePolarity {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PwmPulsePolarity {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for PwmPulsePolarity {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Pwm.PwmPulsePolarity;i4)");
}
impl ::windows::core::DefaultType for PwmPulsePolarity {
type DefaultType = Self;
}
|
use serde::{Serialize, Serializer};
pub use ser::MCProtoSerializer;
mod ser;
pub(crate) mod write;
pub fn serialize<T, S>(data: &T, serializer: S) -> Result<S::Ok, S::Error>
where
T: ?Sized + Serialize,
S: Serializer,
{
Serialize::serialize(data, serializer)
}
|
use chrono::Local;
use color;
use irc::proto::message::Tag;
use std::{collections::HashMap, iter::FromIterator};
#[inline(always)]
#[allow(dead_code)]
pub fn opt_string(s: Option<String>, default: String) -> String {
if let Some(x) = s {
x
} else {
default
}
}
#[inline(always)]
#[allow(dead_code)]
pub fn opt_string_apply<T>(s: Option<String>, default: String, on_ok: T) -> String
where
T: FnOnce(String) -> String,
{
if let Some(x) = s {
on_ok(x)
} else {
default
}
}
#[inline(always)]
#[allow(dead_code)]
pub fn bool_string(s: bool, yes: String, no: String) -> String {
if s {
yes
} else {
no
}
}
#[allow(dead_code)]
pub fn f_dump_s(fx: &str, s: &str) -> ::std::io::Result<()> {
use std::{fs::File, io::Write};
let mut f = File::create(fx)?;
write!(f, "{}", s)?;
Ok(())
}
#[inline]
#[allow(dead_code)]
pub fn find_twitch_name_prefx(s: Option<String>) -> String {
if let Some(prefx) = s {
let s = prefx.split('@').collect::<Vec<_>>();
if s.len() == 2 {
let sx = s[0].split('!').collect::<Vec<_>>();
if sx.len() == 2 {
String::from(sx[0])
} else {
String::from(s[0])
}
} else {
String::from("[SOMEBODY]")
}
} else {
String::from("[UNKNOWN]")
}
}
/// Abbreviation function for `String::from(o)`
#[inline(always)]
#[allow(dead_code)]
pub fn s(o: &str) -> String { String::from(o) }
/// Abbreviation function for `model::color::ColoredString::to_string()`
#[inline(always)]
#[allow(dead_code)]
pub fn sc(o: &color::ColoredString) -> String { o.to_string() }
pub fn stringy_bool(s: &str) -> bool {
match s {
"y" | "yes" | "1" | "true" => true,
_ => false,
}
}
// This is *NOT* alloc free
pub fn tags_into_hashmap(tags: &[Tag]) -> HashMap<String, String> {
HashMap::from_iter(
tags.into_iter()
.filter(|i| i.1 != None && i.1 != Some("".to_owned()))
.map(|Tag(l, r)| (l.clone(), r.clone().unwrap())),
)
}
pub fn localtime() -> String {
let local = Local::now();
format!("{}", local.format("%T"))
}
|
#[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 = "DAC channel1 DMA Underrun Interrupt enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMAUDRIE1_A {
#[doc = "0: DAC channel X DMA Underrun Interrupt disabled"]
DISABLED = 0,
#[doc = "1: DAC channel X DMA Underrun Interrupt enabled"]
ENABLED = 1,
}
impl From<DMAUDRIE1_A> for bool {
#[inline(always)]
fn from(variant: DMAUDRIE1_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DMAUDRIE1`"]
pub type DMAUDRIE1_R = crate::R<bool, DMAUDRIE1_A>;
impl DMAUDRIE1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DMAUDRIE1_A {
match self.bits {
false => DMAUDRIE1_A::DISABLED,
true => DMAUDRIE1_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DMAUDRIE1_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DMAUDRIE1_A::ENABLED
}
}
#[doc = "Write proxy for field `DMAUDRIE1`"]
pub struct DMAUDRIE1_W<'a> {
w: &'a mut W,
}
impl<'a> DMAUDRIE1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DMAUDRIE1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "DAC channel X DMA Underrun Interrupt disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(DMAUDRIE1_A::DISABLED)
}
#[doc = "DAC channel X DMA Underrun Interrupt enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(DMAUDRIE1_A::ENABLED)
}
#[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 = "DAC channel1 DMA enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMAEN1_A {
#[doc = "0: DAC channel X DMA mode disabled"]
DISABLED = 0,
#[doc = "1: DAC channel X DMA mode enabled"]
ENABLED = 1,
}
impl From<DMAEN1_A> for bool {
#[inline(always)]
fn from(variant: DMAEN1_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DMAEN1`"]
pub type DMAEN1_R = crate::R<bool, DMAEN1_A>;
impl DMAEN1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DMAEN1_A {
match self.bits {
false => DMAEN1_A::DISABLED,
true => DMAEN1_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == DMAEN1_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == DMAEN1_A::ENABLED
}
}
#[doc = "Write proxy for field `DMAEN1`"]
pub struct DMAEN1_W<'a> {
w: &'a mut W,
}
impl<'a> DMAEN1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DMAEN1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "DAC channel X DMA mode disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(DMAEN1_A::DISABLED)
}
#[doc = "DAC channel X DMA mode enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(DMAEN1_A::ENABLED)
}
#[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 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `MAMP13`"]
pub type MAMP13_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MAMP13`"]
pub struct MAMP13_W<'a> {
w: &'a mut W,
}
impl<'a> MAMP13_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `MAMP12`"]
pub type MAMP12_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MAMP12`"]
pub struct MAMP12_W<'a> {
w: &'a mut W,
}
impl<'a> MAMP12_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `MAMP11`"]
pub type MAMP11_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MAMP11`"]
pub struct MAMP11_W<'a> {
w: &'a mut W,
}
impl<'a> MAMP11_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `MAMP10`"]
pub type MAMP10_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MAMP10`"]
pub struct MAMP10_W<'a> {
w: &'a mut W,
}
impl<'a> MAMP10_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `WAVE1`"]
pub type WAVE1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WAVE1`"]
pub struct WAVE1_W<'a> {
w: &'a mut W,
}
impl<'a> WAVE1_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 `WAVE2`"]
pub type WAVE2_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WAVE2`"]
pub struct WAVE2_W<'a> {
w: &'a mut W,
}
impl<'a> WAVE2_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 = "DAC channel1 trigger selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum TSEL1_A {
#[doc = "0: Timer 6 TRGO event"]
TIM6_TRGO = 0,
#[doc = "1: Timer 3 TRGO event"]
TIM3_TRGO = 1,
#[doc = "2: Timer 7 TRGO event"]
TIM7_TRGO = 2,
#[doc = "3: Timer 15 TRGO event"]
TIM15_TRGO = 3,
#[doc = "4: Timer 2 TRGO event"]
TIM2_TRGO = 4,
#[doc = "6: EXTI line9"]
EXTI9 = 6,
#[doc = "7: Software trigger"]
SOFTWARE = 7,
}
impl From<TSEL1_A> for u8 {
#[inline(always)]
fn from(variant: TSEL1_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `TSEL1`"]
pub type TSEL1_R = crate::R<u8, TSEL1_A>;
impl TSEL1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, TSEL1_A> {
use crate::Variant::*;
match self.bits {
0 => Val(TSEL1_A::TIM6_TRGO),
1 => Val(TSEL1_A::TIM3_TRGO),
2 => Val(TSEL1_A::TIM7_TRGO),
3 => Val(TSEL1_A::TIM15_TRGO),
4 => Val(TSEL1_A::TIM2_TRGO),
6 => Val(TSEL1_A::EXTI9),
7 => Val(TSEL1_A::SOFTWARE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `TIM6_TRGO`"]
#[inline(always)]
pub fn is_tim6_trgo(&self) -> bool {
*self == TSEL1_A::TIM6_TRGO
}
#[doc = "Checks if the value of the field is `TIM3_TRGO`"]
#[inline(always)]
pub fn is_tim3_trgo(&self) -> bool {
*self == TSEL1_A::TIM3_TRGO
}
#[doc = "Checks if the value of the field is `TIM7_TRGO`"]
#[inline(always)]
pub fn is_tim7_trgo(&self) -> bool {
*self == TSEL1_A::TIM7_TRGO
}
#[doc = "Checks if the value of the field is `TIM15_TRGO`"]
#[inline(always)]
pub fn is_tim15_trgo(&self) -> bool {
*self == TSEL1_A::TIM15_TRGO
}
#[doc = "Checks if the value of the field is `TIM2_TRGO`"]
#[inline(always)]
pub fn is_tim2_trgo(&self) -> bool {
*self == TSEL1_A::TIM2_TRGO
}
#[doc = "Checks if the value of the field is `EXTI9`"]
#[inline(always)]
pub fn is_exti9(&self) -> bool {
*self == TSEL1_A::EXTI9
}
#[doc = "Checks if the value of the field is `SOFTWARE`"]
#[inline(always)]
pub fn is_software(&self) -> bool {
*self == TSEL1_A::SOFTWARE
}
}
#[doc = "Write proxy for field `TSEL1`"]
pub struct TSEL1_W<'a> {
w: &'a mut W,
}
impl<'a> TSEL1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TSEL1_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Timer 6 TRGO event"]
#[inline(always)]
pub fn tim6_trgo(self) -> &'a mut W {
self.variant(TSEL1_A::TIM6_TRGO)
}
#[doc = "Timer 3 TRGO event"]
#[inline(always)]
pub fn tim3_trgo(self) -> &'a mut W {
self.variant(TSEL1_A::TIM3_TRGO)
}
#[doc = "Timer 7 TRGO event"]
#[inline(always)]
pub fn tim7_trgo(self) -> &'a mut W {
self.variant(TSEL1_A::TIM7_TRGO)
}
#[doc = "Timer 15 TRGO event"]
#[inline(always)]
pub fn tim15_trgo(self) -> &'a mut W {
self.variant(TSEL1_A::TIM15_TRGO)
}
#[doc = "Timer 2 TRGO event"]
#[inline(always)]
pub fn tim2_trgo(self) -> &'a mut W {
self.variant(TSEL1_A::TIM2_TRGO)
}
#[doc = "EXTI line9"]
#[inline(always)]
pub fn exti9(self) -> &'a mut W {
self.variant(TSEL1_A::EXTI9)
}
#[doc = "Software trigger"]
#[inline(always)]
pub fn software(self) -> &'a mut W {
self.variant(TSEL1_A::SOFTWARE)
}
#[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 << 3)) | (((value as u32) & 0x07) << 3);
self.w
}
}
#[doc = "DAC channel1 trigger enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TEN1_A {
#[doc = "0: DAC channel X trigger disabled"]
DISABLED = 0,
#[doc = "1: DAC channel X trigger enabled"]
ENABLED = 1,
}
impl From<TEN1_A> for bool {
#[inline(always)]
fn from(variant: TEN1_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `TEN1`"]
pub type TEN1_R = crate::R<bool, TEN1_A>;
impl TEN1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> TEN1_A {
match self.bits {
false => TEN1_A::DISABLED,
true => TEN1_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == TEN1_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == TEN1_A::ENABLED
}
}
#[doc = "Write proxy for field `TEN1`"]
pub struct TEN1_W<'a> {
w: &'a mut W,
}
impl<'a> TEN1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TEN1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "DAC channel X trigger disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(TEN1_A::DISABLED)
}
#[doc = "DAC channel X trigger enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(TEN1_A::ENABLED)
}
#[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 = "DAC channel1 output buffer disable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BOFF1_A {
#[doc = "0: DAC channel X output buffer enabled"]
ENABLED = 0,
#[doc = "1: DAC channel X output buffer disabled"]
DISABLED = 1,
}
impl From<BOFF1_A> for bool {
#[inline(always)]
fn from(variant: BOFF1_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `BOFF1`"]
pub type BOFF1_R = crate::R<bool, BOFF1_A>;
impl BOFF1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> BOFF1_A {
match self.bits {
false => BOFF1_A::ENABLED,
true => BOFF1_A::DISABLED,
}
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == BOFF1_A::ENABLED
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == BOFF1_A::DISABLED
}
}
#[doc = "Write proxy for field `BOFF1`"]
pub struct BOFF1_W<'a> {
w: &'a mut W,
}
impl<'a> BOFF1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: BOFF1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "DAC channel X output buffer enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(BOFF1_A::ENABLED)
}
#[doc = "DAC channel X output buffer disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(BOFF1_A::DISABLED)
}
#[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 = "DAC channel1 enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EN1_A {
#[doc = "0: DAC channel X disabled"]
DISABLED = 0,
#[doc = "1: DAC channel X enabled"]
ENABLED = 1,
}
impl From<EN1_A> for bool {
#[inline(always)]
fn from(variant: EN1_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EN1`"]
pub type EN1_R = crate::R<bool, EN1_A>;
impl EN1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EN1_A {
match self.bits {
false => EN1_A::DISABLED,
true => EN1_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EN1_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EN1_A::ENABLED
}
}
#[doc = "Write proxy for field `EN1`"]
pub struct EN1_W<'a> {
w: &'a mut W,
}
impl<'a> EN1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EN1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "DAC channel X disabled"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EN1_A::DISABLED)
}
#[doc = "DAC channel X enabled"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EN1_A::ENABLED)
}
#[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
}
}
impl R {
#[doc = "Bit 13 - DAC channel1 DMA Underrun Interrupt enable"]
#[inline(always)]
pub fn dmaudrie1(&self) -> DMAUDRIE1_R {
DMAUDRIE1_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 12 - DAC channel1 DMA enable"]
#[inline(always)]
pub fn dmaen1(&self) -> DMAEN1_R {
DMAEN1_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 11 - DAC channel1 mask/amplitude selector"]
#[inline(always)]
pub fn mamp13(&self) -> MAMP13_R {
MAMP13_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 10 - MAMP12"]
#[inline(always)]
pub fn mamp12(&self) -> MAMP12_R {
MAMP12_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 9 - MAMP11"]
#[inline(always)]
pub fn mamp11(&self) -> MAMP11_R {
MAMP11_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - MAMP10"]
#[inline(always)]
pub fn mamp10(&self) -> MAMP10_R {
MAMP10_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 7 - DAC channel1 noise/triangle wave generation enable"]
#[inline(always)]
pub fn wave1(&self) -> WAVE1_R {
WAVE1_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 6 - WAVE2"]
#[inline(always)]
pub fn wave2(&self) -> WAVE2_R {
WAVE2_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bits 3:5 - DAC channel1 trigger selection"]
#[inline(always)]
pub fn tsel1(&self) -> TSEL1_R {
TSEL1_R::new(((self.bits >> 3) & 0x07) as u8)
}
#[doc = "Bit 2 - DAC channel1 trigger enable"]
#[inline(always)]
pub fn ten1(&self) -> TEN1_R {
TEN1_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - DAC channel1 output buffer disable"]
#[inline(always)]
pub fn boff1(&self) -> BOFF1_R {
BOFF1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - DAC channel1 enable"]
#[inline(always)]
pub fn en1(&self) -> EN1_R {
EN1_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 13 - DAC channel1 DMA Underrun Interrupt enable"]
#[inline(always)]
pub fn dmaudrie1(&mut self) -> DMAUDRIE1_W {
DMAUDRIE1_W { w: self }
}
#[doc = "Bit 12 - DAC channel1 DMA enable"]
#[inline(always)]
pub fn dmaen1(&mut self) -> DMAEN1_W {
DMAEN1_W { w: self }
}
#[doc = "Bit 11 - DAC channel1 mask/amplitude selector"]
#[inline(always)]
pub fn mamp13(&mut self) -> MAMP13_W {
MAMP13_W { w: self }
}
#[doc = "Bit 10 - MAMP12"]
#[inline(always)]
pub fn mamp12(&mut self) -> MAMP12_W {
MAMP12_W { w: self }
}
#[doc = "Bit 9 - MAMP11"]
#[inline(always)]
pub fn mamp11(&mut self) -> MAMP11_W {
MAMP11_W { w: self }
}
#[doc = "Bit 8 - MAMP10"]
#[inline(always)]
pub fn mamp10(&mut self) -> MAMP10_W {
MAMP10_W { w: self }
}
#[doc = "Bit 7 - DAC channel1 noise/triangle wave generation enable"]
#[inline(always)]
pub fn wave1(&mut self) -> WAVE1_W {
WAVE1_W { w: self }
}
#[doc = "Bit 6 - WAVE2"]
#[inline(always)]
pub fn wave2(&mut self) -> WAVE2_W {
WAVE2_W { w: self }
}
#[doc = "Bits 3:5 - DAC channel1 trigger selection"]
#[inline(always)]
pub fn tsel1(&mut self) -> TSEL1_W {
TSEL1_W { w: self }
}
#[doc = "Bit 2 - DAC channel1 trigger enable"]
#[inline(always)]
pub fn ten1(&mut self) -> TEN1_W {
TEN1_W { w: self }
}
#[doc = "Bit 1 - DAC channel1 output buffer disable"]
#[inline(always)]
pub fn boff1(&mut self) -> BOFF1_W {
BOFF1_W { w: self }
}
#[doc = "Bit 0 - DAC channel1 enable"]
#[inline(always)]
pub fn en1(&mut self) -> EN1_W {
EN1_W { w: self }
}
}
|
fn main() {
println!("{}", inc(10));
greeting(String::from("Agus"), 35);
}
fn inc(x: i32) -> i32 {
return x+1;
}
fn greeting(name: String, age: i32) {
println!("Halo bapak {}, umur Anda {}", name, age);
} |
use std;
#[derive(Debug,PartialEq)]
pub enum RleComponent {
Run(usize, u8),
Literal(Vec<u8>)
}
struct Encoder {
working_component: Option<RleComponent>,
components: Vec<RleComponent>,
}
impl Encoder {
fn new() -> Encoder {
Encoder {
working_component: None,
components: vec![],
}
}
fn commit(&mut self) {
let wc = std::mem::replace(&mut self.working_component, None);
if let Some(component) = wc {
self.components.push(component);
}
}
fn append(&mut self, component: RleComponent) {
match component {
RleComponent::Run(_, _) => {
self.commit();
self.working_component = Some(component);
},
RleComponent::Literal(new_val) => {
match self.working_component {
Some(RleComponent::Run(_, _)) => {
self.commit();
self.working_component = Some(RleComponent::Literal(new_val));
}
Some(RleComponent::Literal(ref mut vals)) => {
vals.extend(new_val);
}
None => {
self.working_component = Some(RleComponent::Literal(new_val));
}
}
}
}
}
fn finish(mut self) -> Vec<RleComponent> {
self.commit();
self.components
}
}
pub fn encode(input: &str) -> Vec<RleComponent> {
let mut encoder = Encoder::new();
let mut input_iter = input.bytes().peekable();
let mut last: u8 = input_iter.nth(0).unwrap();
let mut counter: usize = 1;
for bv in input_iter {
if bv == last {
counter += 1;
} else {
if counter == 1 {
encoder.append(RleComponent::Literal(vec![last]));
} else {
encoder.append(RleComponent::Run(counter, last));
}
counter = 1;
last = bv;
}
}
// TODO: This repeated code isn't ideal.
if counter == 1 {
encoder.append(RleComponent::Literal(vec![last]));
} else {
encoder.append(RleComponent::Run(counter, last));
}
encoder.finish()
}
pub fn decode(input: Vec<RleComponent>) -> String {
let mut decoded = vec!();
for component in input {
let next_sequence = match component {
RleComponent::Run(length, byte) => vec![byte;length],
RleComponent::Literal(bytes) => bytes,
};
decoded.extend(next_sequence);
}
String::from_utf8(decoded).unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_encode() {
assert_eq!(
encode("hello"),
[
RleComponent::Literal(vec![104, 101]),
RleComponent::Run(2, 108),
RleComponent::Literal(vec![111])
]
);
}
#[test]
#[ignore]
fn empty_encode() {
assert_eq!(
encode(""),
[]
);
}
#[test]
fn with_trailing_run() {
assert_eq!(
encode("helloo"),
[
RleComponent::Literal(vec![104, 101]),
RleComponent::Run(2, 108),
RleComponent::Run(2, 111),
]
);
}
#[test]
fn moretests() {
assert_eq!(
encode("aaaaaab"),
[
RleComponent::Run(6, 97),
RleComponent::Literal(vec![98]),
]
);
}
#[test]
fn basic_decode() {
assert_eq!(
decode(encode("aabb")),
"aabb"
);
}
#[test]
fn basic_decode_only_literal() {
assert_eq!(
decode(encode("ab")),
"ab"
);
}
}
|
use crate::*;
use std::ffi::CString;
#[test]
fn write_rgba1() {
let mut file = std::ptr::null_mut();
let filename = CString::new("out.exr").unwrap();
unsafe {
Imf_RgbaOutputFile_with_dimensions(
&mut file,
filename.as_ptr(),
256,
128,
Imf_RgbaChannels_WRITE_RGBA,
1.0,
Imath_V2f_t { x: 1.0, y: 1.0 },
1.0,
Imf_LineOrder_INCREASING_Y,
Imf_Compression_ZIP_COMPRESSION,
1,
);
}
}
|
use url::{ParseError, Url};
use crate::signing::util::percent_encode_path;
/// An S3 bucket
///
/// ## Path style url
///
/// ```rust
/// # use rusty_s3::Bucket;
/// let endpoint = "https://eu-west-1.s3.amazonaws.com".parse().expect("endpoint is a valid Url");
/// let path_style = true;
/// let name = String::from("rusty-s3");
/// let region = String::from("eu-west-1");
///
/// let bucket = Bucket::new(endpoint, path_style, name, region).expect("Url has a valid scheme and host");
/// assert_eq!(bucket.base_url().as_str(), "https://eu-west-1.s3.amazonaws.com/rusty-s3/");
/// assert_eq!(bucket.name(), "rusty-s3");
/// assert_eq!(bucket.region(), "eu-west-1");
/// assert_eq!(bucket.object_url("duck.jpg").expect("url is valid").as_str(), "https://eu-west-1.s3.amazonaws.com/rusty-s3/duck.jpg");
/// ```
///
/// ## Domain style url
///
/// ```rust
/// # use rusty_s3::Bucket;
/// let endpoint = "https://eu-west-1.s3.amazonaws.com".parse().expect("endpoint is a valid Url");
/// let path_style = false;
/// let name = String::from("rusty-s3");
/// let region = String::from("eu-west-1");
///
/// let bucket = Bucket::new(endpoint, path_style, name, region).expect("Url has a valid scheme and host");
/// assert_eq!(bucket.base_url().as_str(), "https://rusty-s3.eu-west-1.s3.amazonaws.com/");
/// assert_eq!(bucket.name(), "rusty-s3");
/// assert_eq!(bucket.region(), "eu-west-1");
/// assert_eq!(bucket.object_url("duck.jpg").expect("url is valid").as_str(), "https://rusty-s3.eu-west-1.s3.amazonaws.com/duck.jpg");
/// ```
#[derive(Debug, Clone)]
pub struct Bucket {
base_url: Url,
name: String,
region: String,
}
impl Bucket {
/// Construct a new S3 bucket
pub fn new(endpoint: Url, path_style: bool, name: String, region: String) -> Option<Self> {
let _ = endpoint.host_str()?;
match endpoint.scheme() {
"http" | "https" => {}
_ => return None,
};
let base_url = base_url(endpoint, &name, path_style);
Some(Self {
base_url,
name,
region,
})
}
/// Get the base url of this s3 `Bucket`
pub fn base_url(&self) -> &Url {
&self.base_url
}
/// Get the name of this `Bucket`
pub fn name(&self) -> &str {
&self.name
}
/// Get the region of this `Bucket`
pub fn region(&self) -> &str {
&self.region
}
/// Generate an url to an object of this `Bucket`
///
/// This is not a signed url, it's just the starting point for
/// generating an url to an S3 object.
pub fn object_url(&self, object: &str) -> Result<Url, ParseError> {
let object = percent_encode_path(object);
self.base_url.join(&object)
}
}
fn base_url(mut endpoint: Url, name: &str, path_style: bool) -> Url {
if path_style {
let path = format!("{}/", name);
endpoint.join(&path).unwrap()
} else {
let host = format!("{}.{}", name, endpoint.host_str().unwrap());
endpoint.set_host(Some(&host)).unwrap();
endpoint
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn new_pathstyle() {
let endpoint: Url = "https://s3.eu-west-1.amazonaws.com".parse().unwrap();
let base_url: Url = "https://s3.eu-west-1.amazonaws.com/rusty-s3/"
.parse()
.unwrap();
let name = "rusty-s3";
let region = "eu-west-1";
let bucket = Bucket::new(endpoint, true, name.into(), region.into()).unwrap();
assert_eq!(bucket.base_url(), &base_url);
assert_eq!(bucket.name(), name);
assert_eq!(bucket.region(), region);
}
#[test]
fn new_domainstyle() {
let endpoint: Url = "https://s3.eu-west-1.amazonaws.com".parse().unwrap();
let base_url: Url = "https://rusty-s3.s3.eu-west-1.amazonaws.com"
.parse()
.unwrap();
let name = "rusty-s3";
let region = "eu-west-1";
let bucket = Bucket::new(endpoint, false, name.into(), region.into()).unwrap();
assert_eq!(bucket.base_url(), &base_url);
assert_eq!(bucket.name(), name);
assert_eq!(bucket.region(), region);
}
#[test]
fn new_bad_scheme() {
let endpoint = "file:///home/something".parse().unwrap();
let name = "rusty-s3";
let region = "eu-west-1";
assert!(Bucket::new(endpoint, true, name.into(), region.into()).is_none());
}
#[test]
fn object_url_pathstyle() {
let endpoint: Url = "https://s3.eu-west-1.amazonaws.com".parse().unwrap();
let name = "rusty-s3";
let region = "eu-west-1";
let bucket = Bucket::new(endpoint, true, name.into(), region.into()).unwrap();
let path_style = bucket.object_url("something/cat.jpg").unwrap();
assert_eq!(
"https://s3.eu-west-1.amazonaws.com/rusty-s3/something/cat.jpg",
path_style.as_str()
);
}
#[test]
fn object_url_domainstyle() {
let endpoint: Url = "https://s3.eu-west-1.amazonaws.com".parse().unwrap();
let name = "rusty-s3";
let region = "eu-west-1";
let bucket = Bucket::new(endpoint, false, name.into(), region.into()).unwrap();
let domain_style = bucket.object_url("something/cat.jpg").unwrap();
assert_eq!(
"https://rusty-s3.s3.eu-west-1.amazonaws.com/something/cat.jpg",
domain_style.as_str()
);
}
}
|
use clap::{App, Arg};
use std::io;
use csvsc::columns::ColSpec;
use csvsc::input::ReaderSource;
use csvsc::AddColumns;
use csvsc::InputStream;
use encoding::label::encoding_from_whatwg_label;
fn main() {
let matches = App::new("csvsc")
.version("1.0")
.author("Abraham Toriz <categulario@gmail.com>")
.about("Converts M csv files in N files using aggregates and other rules")
.arg(
Arg::with_name("input")
.value_name("INPUT")
.help("Input files")
.multiple(true)
.required(true),
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.value_name("OUTPUT")
.help("Output filename")
.required(true),
)
.arg(
Arg::with_name("encoding")
.short("e")
.long("input-encoding")
.value_name("ENCODING")
.default_value("utf-8")
.help("The encoding to use while reading the files")
.takes_value(true),
)
.arg(
Arg::with_name("add_columns")
.short("a")
.long("add-columns")
.value_name("COLUMN_SPEC")
.help("Columns to add to the input")
.multiple(true)
.takes_value(true),
)
.arg(
Arg::with_name("reduce")
.short("r")
.long("reduce")
.value_name("REDUCE_SPEC")
.help("Reduce using the specified rules")
.multiple(true)
.takes_value(true),
)
.arg(
Arg::with_name("group")
.short("g")
.long("group-by")
.value_name("GROUP_SPEC")
.help("How to group for aggregates")
.multiple(true)
.takes_value(true),
)
.arg(
Arg::with_name("filter")
.short("f")
.long("filter")
.value_name("FILTER_SPEC")
.help("Exclude some rows from the output")
.takes_value(true),
)
.get_matches();
// Step 1. Get the source
let filenames: Vec<_> = matches.values_of("input").unwrap().collect();
let encoding = encoding_from_whatwg_label(matches.value_of("encoding").unwrap())
.expect("Invalid encoding, check whatwg list");
let input_stream: InputStream = filenames
.iter()
.filter_map(|f| match csv::Reader::from_path(f) {
Ok(reader) => Some(ReaderSource {
reader,
path: f.to_string(),
encoding: encoding,
}),
Err(e) => {
match e.kind() {
csv::ErrorKind::Io(error) => match error.kind() {
io::ErrorKind::PermissionDenied => eprintln!("Permission denied: {}", f),
io::ErrorKind::NotFound => eprintln!("Not found: {}", f),
_ => eprintln!("IO Error: {}", f),
},
_ => eprintln!("This shouldn't happen, please report to mantainer"),
}
None
}
})
.collect();
// Step 2. Map the info, add/remove, transform each row
let add_columns = AddColumns::new(
input_stream,
match matches.values_of("add_columns") {
Some(columns) => columns.map(|s| ColSpec::new(s)).collect(),
None => Vec::new(),
},
);
// mapper = Mapper(input_stream, add_columns=self.add_columns)
// Step 3. Stablish destination
// dist = Distributor(mapper, self.output)
// Step 4. Reduce, aggregate
// reducer = Reducer(dist, grouping=self.grouping, columns=self.reducer_columns)
// Step 5. Flush to destination
// Flusher(reducer).flush()
}
|
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
pub fn get<T, F>(v: T, key: &str, f: F) -> Option<T>
where
F: Fn(T, &str) -> Option<T>,
{
if key.is_empty() {
return None;
}
let vecs: Vec<&str> = key.splitn(2, '.').collect();
let v2 = f(v, vecs[0]);
if vecs.len() == 1 {
v2
} else {
v2.map_or_else(|| None, |v3| get(v3, vecs[1], f))
}
}
#[derive(Debug)]
pub enum Config {
JSON(serde_json::Value),
TOML(toml::value::Value),
}
impl Config {
pub fn get(&self, key: &str) -> Option<Config> {
match self {
Config::JSON(v) => get(v, key, |v2,s|v2.get(s)).map(|v3| Config::JSON(v3.clone())),
Config::TOML(v) => get(v, key, |v2,s|v2.get(s)).map(|v3| Config::TOML(v3.clone())),
}
}
pub fn keys(&self) -> Vec<String> {
match self {
Config::JSON(v) => v.as_object().map_or_else(|| vec![], |m| m.keys().cloned().collect()),
Config::TOML(v) => v.as_table().map_or_else(|| vec![], |m| m.keys().cloned().collect()),
}
}
pub fn str(&self, key: &str) -> Option<String> {
self.get(key).map_or_else(||None, |s| s._as_str())
}
pub fn str_must(&self, key: &str) -> String {
self.str(key).expect(&format!("failed to get config {} (str)", key))
}
pub fn str_default(&self, key: &str, def: &str) -> String {
self.str(key).unwrap_or(def.to_owned())
}
pub fn bool(&self, key: &str) -> Option<bool> {
self.get(key).map_or_else(|| None, |s| s._as_bool())
}
pub fn bool_must(&self, key: &str) -> bool {
self.bool(key).expect(&format!("failed to get config {} (bool)", key))
}
pub fn bool_default(&self, key: &str, def: bool) -> bool {
self.bool(key).unwrap_or(def)
}
pub fn i64(&self, key: &str) -> Option<i64> {
self.get(key).map_or_else(|| None, |s| s._as_i64())
}
pub fn i64_must(&self, key: &str) -> i64 {
self.i64(key).expect(&format!("failed to get config {} (i64)", key))
}
pub fn i64_default(&self, key: &str, def: i64) -> i64 {
self.i64(key).unwrap_or(def)
}
pub fn f64(&self, key: &str) -> Option<f64> {
self.get(key).map_or_else(|| None, |s| s._as_f64())
}
pub fn f64_must(&self, key: &str) -> f64 {
self.f64(key).expect(&format!("failed to get config {} (f64)", key))
}
pub fn f64_default(&self, key: &str, def: f64) -> f64 {
self.f64(key).unwrap_or(def)
}
fn _as_str(&self) -> Option<String> {
match self {
Config::JSON(v) => match v {
serde_json::Value::String(s) => Some(s.to_owned()),
serde_json::Value::Number(s) => Some(format!("{}", s)),
serde_json::Value::Bool(s) => Some(format!("{}", s)),
_ => None,
},
Config::TOML(v) => match v {
toml::value::Value::String(s) => Some(s.to_owned()),
toml::value::Value::Integer(s) => Some(format!("{}", s)),
toml::value::Value::Float(s) => Some(format!("{}", s)),
toml::value::Value::Boolean(s) => Some(format!("{}", s)),
toml::value::Value::Datetime(s) => Some(format!("{}", &s)),
_ => None,
},
}.map_or_else(|| None, |v| if v.is_empty() {None} else {Some(v)})
}
fn _as_bool(&self) -> Option<bool> {
match self {
Config::JSON(v) => match v {
serde_json::Value::String(s) => match s.to_lowercase().as_str() {
"true" | "yes" | "t" | "y" => Some(true),
"false" | "no" | "f" | "n" => Some(false),
_ => None,
},
serde_json::Value::Bool(s) => Some(*s),
_ => None,
},
Config::TOML(v) => match v {
toml::value::Value::String(s) => match s.to_lowercase().as_str() {
"true" | "yes" | "t" | "y" => Some(true),
"false" | "no" | "f" | "n" => Some(false),
_ => None,
},
toml::value::Value::Boolean(s) => Some(*s),
_ => None,
},
}
}
fn _as_i64(&self) -> Option<i64> {
match self {
Config::JSON(v) => match v {
serde_json::Value::String(s) => s.parse::<i64>().ok(),
serde_json::Value::Number(s) => s.as_i64(),
_ => None,
},
Config::TOML(v) => match v {
toml::value::Value::String(s) => s.parse::<i64>().ok(),
toml::value::Value::Integer(s) => Some(*s),
toml::value::Value::Float(s) => Some(*s as i64),
_ => None,
},
}
}
fn _as_f64(&self) -> Option<f64> {
match self {
Config::JSON(v) => match v {
serde_json::Value::String(s) => s.parse::<f64>().ok(),
serde_json::Value::Number(s) => s.as_f64(),
_ => None,
},
Config::TOML(v) => match v {
toml::value::Value::String(s) => s.parse::<f64>().ok(),
toml::value::Value::Integer(s) => Some(*s as f64),
toml::value::Value::Float(s) => Some(*s),
_ => None,
},
}
}
}
pub fn load(var: &str, def: &str) -> Config {
let f = match env::var(var) {
Ok(s) => s,
Err(_) => String::from(def),
};
let p = if !f.starts_with("/") {
match env::current_exe() {
Ok(p) => p.parent().unwrap().join(&f).to_owned(),
Err(_) => PathBuf::from(&f),
}
} else {
PathBuf::from(&f)
};
let mut s = String::new();
File::open(&p).expect(&format!("failed to open {:?}", &p)).read_to_string(&mut s).unwrap();
let s = shellexpand::env_with_context_no_errors(&s, _subst).to_owned().to_string();
let ext = p.extension().unwrap().to_str();
match ext {
Some("toml") => Config::TOML(toml::from_str::<toml::value::Value>(&s).unwrap()),
Some("json") => Config::JSON(serde_json::from_str::<serde_json::Value>(&s).unwrap()),
Some(_) => panic!("unsupported config {:?}", p),
None => panic!("unsupported config {:?}", p),
}
}
fn _subst(s: &str) -> Option<String> {
match env::var(s).ok() {
Some(v) => Some(v),
None => Some("".to_string()),
// None => {
// match s {
// "ABC" => Some("123".to_string()),
// _ => Some("".to_string()),
// }
// }
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IQuickLink(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IQuickLink {
type Vtable = IQuickLink_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x603e4308_f0be_4adc_acc9_8b27ab9cf556);
}
#[repr(C)]
#[doc(hidden)]
pub struct IQuickLink_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 = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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 IShareOperation(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IShareOperation {
type Vtable = IShareOperation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2246bab8_d0f8_41c1_a82a_4137db6504fb);
}
#[repr(C)]
#[doc(hidden)]
pub struct IShareOperation_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quicklink: ::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, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IShareOperation2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IShareOperation2 {
type Vtable = IShareOperation2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0ffb97c1_9778_4a09_8e5b_cb5e482d0555);
}
#[repr(C)]
#[doc(hidden)]
pub struct IShareOperation2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IShareOperation3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IShareOperation3 {
type Vtable = IShareOperation3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5ef6b382_b7a7_4571_a2a6_994a034988b2);
}
#[repr(C)]
#[doc(hidden)]
pub struct IShareOperation3_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 = "ApplicationModel_Contacts", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "ApplicationModel_Contacts", feature = "Foundation_Collections")))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct QuickLink(pub ::windows::core::IInspectable);
impl QuickLink {
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<QuickLink, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn Title(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetTitle<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Storage_Streams")]
pub fn Thumbnail(&self) -> ::windows::core::Result<super::super::super::Storage::Streams::RandomAccessStreamReference> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Storage::Streams::RandomAccessStreamReference>(result__)
}
}
#[cfg(feature = "Storage_Streams")]
pub fn SetThumbnail<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::RandomAccessStreamReference>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn SupportedDataFormats(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn SupportedFileTypes(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for QuickLink {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.DataTransfer.ShareTarget.QuickLink;{603e4308-f0be-4adc-acc9-8b27ab9cf556})");
}
unsafe impl ::windows::core::Interface for QuickLink {
type Vtable = IQuickLink_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x603e4308_f0be_4adc_acc9_8b27ab9cf556);
}
impl ::windows::core::RuntimeName for QuickLink {
const NAME: &'static str = "Windows.ApplicationModel.DataTransfer.ShareTarget.QuickLink";
}
impl ::core::convert::From<QuickLink> for ::windows::core::IUnknown {
fn from(value: QuickLink) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&QuickLink> for ::windows::core::IUnknown {
fn from(value: &QuickLink) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for QuickLink {
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 QuickLink {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<QuickLink> for ::windows::core::IInspectable {
fn from(value: QuickLink) -> Self {
value.0
}
}
impl ::core::convert::From<&QuickLink> for ::windows::core::IInspectable {
fn from(value: &QuickLink) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for QuickLink {
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 QuickLink {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ShareOperation(pub ::windows::core::IInspectable);
impl ShareOperation {
pub fn Data(&self) -> ::windows::core::Result<super::DataPackageView> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::DataPackageView>(result__)
}
}
pub fn QuickLinkId(&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 RemoveThisQuickLink(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() }
}
pub fn ReportStarted(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() }
}
pub fn ReportDataRetrieved(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() }
}
pub fn ReportSubmittedBackgroundTask(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() }
}
pub fn ReportCompletedWithQuickLink<'a, Param0: ::windows::core::IntoParam<'a, QuickLink>>(&self, quicklink: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), quicklink.into_param().abi()).ok() }
}
pub fn ReportCompleted(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this)).ok() }
}
pub fn ReportError<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn DismissUI(&self) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IShareOperation2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(all(feature = "ApplicationModel_Contacts", feature = "Foundation_Collections"))]
pub fn Contacts(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<super::super::Contacts::Contact>> {
let this = &::windows::core::Interface::cast::<IShareOperation3>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<super::super::Contacts::Contact>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ShareOperation {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation;{2246bab8-d0f8-41c1-a82a-4137db6504fb})");
}
unsafe impl ::windows::core::Interface for ShareOperation {
type Vtable = IShareOperation_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2246bab8_d0f8_41c1_a82a_4137db6504fb);
}
impl ::windows::core::RuntimeName for ShareOperation {
const NAME: &'static str = "Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation";
}
impl ::core::convert::From<ShareOperation> for ::windows::core::IUnknown {
fn from(value: ShareOperation) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ShareOperation> for ::windows::core::IUnknown {
fn from(value: &ShareOperation) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ShareOperation {
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 ShareOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ShareOperation> for ::windows::core::IInspectable {
fn from(value: ShareOperation) -> Self {
value.0
}
}
impl ::core::convert::From<&ShareOperation> for ::windows::core::IInspectable {
fn from(value: &ShareOperation) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ShareOperation {
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 ShareOperation {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
|
mod day_four;
use day_four::solve;
fn main() {
println!("{}", solve())
} |
// Copyright 2016 `multipart` Crate Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//! Sized/buffered wrapper around `HttpRequest`.
use client::{HttpRequest, HttpStream};
use std::io;
use std::io::prelude::*;
/// A wrapper around a request object that measures the request body and sets the `Content-Length`
/// header to its size in bytes.
///
/// Sized requests are more human-readable and use less bandwidth
/// (as chunking adds [visual noise and overhead][chunked-example]),
/// but they must be able to load their entirety, including the contents of all files
/// and streams, into memory so the request body can be measured.
///
/// You should really only use sized requests if you intend to inspect the data manually on the
/// server side, as it will produce a more human-readable request body. Also, of course, if the
/// server doesn't support chunked requests or otherwise rejects them.
///
/// [chunked-example]: http://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example
pub struct SizedRequest<R> {
inner: R,
buffer: Vec<u8>,
boundary: String,
}
impl<R: HttpRequest> SizedRequest<R> {
#[doc(hidden)]
pub fn from_request(req: R) -> SizedRequest<R> {
SizedRequest {
inner: req,
buffer: Vec::new(),
boundary: String::new(),
}
}
}
impl<R> Write for SizedRequest<R> {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
self.buffer.write(data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl<R: HttpRequest> HttpRequest for SizedRequest<R>
where <R::Stream as HttpStream>::Error: From<R::Error> {
type Stream = Self;
type Error = R::Error;
/// `SizedRequest` ignores `_content_len` because it sets its own later.
fn apply_headers(&mut self, boundary: &str, _content_len: Option<u64>) -> bool {
self.boundary.clear();
self.boundary.push_str(boundary);
true
}
fn open_stream(mut self) -> Result<Self, Self::Error> {
self.buffer.clear();
Ok(self)
}
}
impl<R: HttpRequest> HttpStream for SizedRequest<R>
where <R::Stream as HttpStream>::Error: From<R::Error> {
type Request = Self;
type Response = <<R as HttpRequest>::Stream as HttpStream>::Response;
type Error = <<R as HttpRequest>::Stream as HttpStream>::Error;
fn finish(mut self) -> Result<Self::Response, Self::Error> {
let content_len = self.buffer.len() as u64;
if !self.inner.apply_headers(&self.boundary, Some(content_len)) {
return Err(io::Error::new(
io::ErrorKind::Other,
"SizedRequest failed to apply headers to wrapped request."
).into());
}
let mut req = self.inner.open_stream()?;
io::copy(&mut &self.buffer[..], &mut req)?;
req.finish()
}
}
|
extern crate pcap;
use pcap::{Device,Capture};
#[test]
fn it_works() {
assert!(true);
}
fn main() {
let device = Device::lookup().unwrap();
let mut cap = Capture::from_device(device).unwrap();
cap = cap.timeout(60000);
cap = cap.promisc(true);
cap = cap.snaplen(5000);
let mut active_cap = cap.open().unwrap();
active_cap.filter("arp").unwrap();
while let Ok(packet) = active_cap.next() {
println!("Received packet! {:?}", packet);
}
}
|
extern crate proc_macro;
use proc_macro::{TokenStream, TokenTree};
fn get_type_name(input: TokenStream) -> String {
let mut iter = input.into_iter();
loop {
match iter.next() {
Some(TokenTree::Ident(ident)) => {
let name = ident.to_string();
if name == "struct" || name == "enum" || name == "union" {
return iter.next().unwrap().to_string()
}
},
None => break,
_ => (),
}
}
panic!("no type name found");
}
#[proc_macro_derive(Event)]
pub fn derive_event(input: TokenStream) -> TokenStream {
let type_name = get_type_name(input);
format!("
mod {0}_Event_impls {{
use crate::event::{{Event, NetworkEvent}};
use crate::event::conversion::AsNetworkEvent;
impl Event for super::{0} {{ }}
impl AsNetworkEvent for super::{0} {{
fn is_network_event(&self) -> bool {{
false
}}
fn as_network_event(self: Box<Self>) -> Option<Box<dyn NetworkEvent>> {{
None
}}
}}
}}", type_name).parse().unwrap()
}
#[proc_macro_derive(NetworkEvent)]
pub fn derive_network_event(input: TokenStream) -> TokenStream {
let type_name = get_type_name(input);
format!("
mod {0}_NetworkEvent_impls {{
use crate::event::{{Event, NetworkEvent}};
use crate::event::conversion::AsNetworkEvent;
#[typetag::serde]
impl NetworkEvent for super::{0} {{ }}
impl AsNetworkEvent for super::{0} {{
fn is_network_event(&self) -> bool {{
true
}}
fn as_network_event(self: Box<Self>) -> Option<Box<dyn NetworkEvent>> {{
Some(self)
}}
}}
}}", type_name).parse().unwrap()
} |
// List of useful cargo commands:
// run, test, check, clippy, fmt, build --release
fn main() {
println!("Hello, world!");
let _test: u32 = 0;
}
|
use cosmwasm_std::{Response, Uint128};
use cw0::Event;
pub struct SubscribeEvent<'a> {
pub plan_id: Uint128,
pub subscriber: &'a str,
}
impl<'a> Event for SubscribeEvent<'a> {
fn add_attributes(&self, rsp: &mut Response) {
rsp.add_attribute("action", "subscribe");
rsp.add_attribute("plan_id", self.plan_id);
rsp.add_attribute("subscriber", self.subscriber);
}
}
pub struct UnsubscribeEvent<'a> {
pub plan_id: Uint128,
pub subscriber: &'a str,
}
impl<'a> Event for UnsubscribeEvent<'a> {
fn add_attributes(&self, rsp: &mut Response) {
rsp.add_attribute("action", "unsubscribe");
rsp.add_attribute("plan_id", self.plan_id);
rsp.add_attribute("subscriber", self.subscriber);
}
}
pub struct UpdateSubscriptionEvent<'a> {
pub plan_id: Uint128,
pub subscriber: &'a str,
}
impl<'a> Event for UpdateSubscriptionEvent<'a> {
fn add_attributes(&self, rsp: &mut Response) {
rsp.add_attribute("action", "update-subscription");
rsp.add_attribute("plan_id", self.plan_id);
rsp.add_attribute("subscriber", self.subscriber);
}
}
pub struct CreatePlanEvent {
pub plan_id: Uint128,
}
impl Event for CreatePlanEvent {
fn add_attributes(&self, rsp: &mut Response) {
rsp.add_attribute("action", "create-plan");
rsp.add_attribute("plan_id", self.plan_id);
}
}
pub struct StopPlanEvent {
pub plan_id: Uint128,
}
impl Event for StopPlanEvent {
fn add_attributes(&self, rsp: &mut Response) {
rsp.add_attribute("action", "stop-plan");
rsp.add_attribute("plan_id", self.plan_id);
}
}
|
#[macro_use]
extern crate serde_derive;
pub mod block_device;
pub mod vsock_device;
#[cfg(test)]
mod tests {
#[test]
fn test() {
}
} |
use symbol;
pub type Symbol = symbol::SymbolId;
pub type Position = usize;
#[derive(Debug,Clone,PartialEq)]
pub enum Var {
SimpleVar(Symbol, Position),
FieldVar(Box<Var>, Symbol, Position),
SubscriptVar(Box<Var>, Box<Exp>, Position),
}
#[derive(Debug,Clone,PartialEq)]
pub enum Exp {
VarExp(Box<Var>),
NilExp,
IntExp(i32),
StringExp(String, Position),
CallExp {
func: Symbol,
args: Vec<Box<Exp>>,
pos: Position,
},
// NewExp(Symbol, Position),
OpExp {
left: Box<Exp>,
op: Oper,
right: Box<Exp>,
pos: Position,
},
RecordExp {
fields: Vec<(Symbol, Box<Exp>, Position)>,
typ: Symbol,
pos: Position,
},
SeqExp(Vec<Box<Exp>>),
AssignExp {
var: Box<Var>,
exp: Box<Exp>,
pos: Position,
},
IfExp {
test: Box<Exp>,
then_: Box<Exp>,
else_: Option<Box<Exp>>,
pos: Position,
},
WhileExp {
test: Box<Exp>,
body: Box<Exp>,
pos: Position,
},
ForExp {
var: Symbol,
escape: bool,
lo: Box<Exp>,
hi: Box<Exp>,
body: Box<Exp>,
pos: Position
},
BreakExp(Position),
LetExp {
decs: Vec<Box<Dec>>,
body: Box<Exp>,
pos: Position,
},
ArrayExp {
typ: Symbol,
size: Box<Exp>,
init: Box<Exp>,
pos: Position,
},
}
#[derive(Debug,Clone,PartialEq)]
pub enum Dec {
FunDec {
name: Symbol,
params: Vec<Box<Field>>,
result: Option<(Symbol,Position)>,
body: Box<Exp>,
pos: Position,
},
VarDec {
name: Symbol,
escape: bool,
typ: Option<(Symbol, Position)>,
init: Box<Exp>,
pos: Position,
},
TypeDec {
name: Symbol,
ty: Box<Ty>,
pos: Position,
}
}
#[derive(Debug,Clone,PartialEq)]
pub struct Field {
pub name: Symbol,
pub escape: bool,
pub typ: Symbol,
pub pos: Position,
}
#[derive(Debug,Clone,PartialEq)]
pub enum Ty {
NameTy(Symbol, Position),
RecordTy(Vec<Box<Field>>),
ArrayTy(Symbol, Position),
}
#[derive(Debug,Clone,Copy,PartialEq)]
pub enum Oper {
PlusOp,
MinusOp,
TimesOp,
DivideOp,
EqOp,
NeqOp,
LtOp,
LeOp,
GtOp,
GeOp
} |
use elf;
use lz4;
use std;
use std::fmt;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use sha2::{Sha256, Digest};
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use serde::ser::SerializeTuple;
use serde::de::{Visitor, Unexpected};
pub fn align(size: usize, padding: usize) -> usize {
((size as usize) + padding) & !padding
}
pub fn add_padding(vec: &mut Vec<u8>, padding: usize) {
let real_size = vec.len();
vec.resize(align(real_size, padding), 0);
}
pub fn check_string_or_truncate(string: &mut String, name: &str, size: usize) {
if string.len() >= size {
println!("Warning: Truncating {} to 0x{:x}", name, size - 1);
string.truncate(size);
}
}
pub fn get_segment_data(
file: &mut File,
header: &elf::types::ProgramHeader,
) -> std::io::Result<Vec<u8>> {
let mut data = vec![0; header.filesz as usize];
file.seek(SeekFrom::Start(header.offset))?;
file.read_exact(&mut data)?;
Ok(data)
}
pub fn compress_lz4(uncompressed_data: &mut Vec<u8>) -> std::io::Result<Vec<u8>> {
lz4::block::compress(&uncompressed_data[..], None, false)
}
pub fn compress_blz(uncompressed_data: &mut Vec<u8>) -> blz_nx::BlzResult<Vec<u8>> {
let mut compressed_data =
vec![0; blz_nx::get_worst_compression_buffer_size(uncompressed_data.len())];
let res = blz_nx::compress_raw(&mut uncompressed_data[..], &mut compressed_data[..])?;
compressed_data.resize(res, 0);
Ok(compressed_data)
}
pub fn calculate_sha256(data: &[u8]) -> std::io::Result<Vec<u8>> {
let mut hasher = Sha256::default();
hasher.input(data);
Ok(Vec::from(hasher.result().as_slice()))
}
#[derive(Default)]
pub struct HexOrNum(pub u64);
impl fmt::Debug for HexOrNum {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_fmt(format_args!("{:#010x}", self.0))
}
}
impl<'de> Deserialize<'de> for HexOrNum {
fn deserialize<D>(deserializer: D) -> Result<HexOrNum, D::Error>
where
D: Deserializer<'de>,
{
struct HexOrNumVisitor;
impl<'a> Visitor<'a> for HexOrNumVisitor {
type Value = u64;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "an integer or a hex-formatted string")
}
fn visit_u64<E>(self, v: u64) -> Result<u64, E>
where
E: serde::de::Error,
{
Ok(v)
}
fn visit_str<E>(self, v: &str) -> Result<u64, E>
where
E: serde::de::Error,
{
if v.starts_with("0x") {
u64::from_str_radix(&v[2..], 16)
.map_err(|_| E::invalid_value(Unexpected::Str(v), &"a hex-encoded string"))
} else {
Err(E::invalid_value(
Unexpected::Str(v),
&"a hex-encoded string",
))
}
}
}
let num = Deserializer::deserialize_any(deserializer, HexOrNumVisitor)?;
Ok(HexOrNum(num))
}
}
impl Serialize for HexOrNum {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.collect_str(&format_args!("{:#010x}", self.0))
}
}
macro_rules! array_impls {
($($ty:ident: $len:literal),+) => {
$(
#[derive(Clone, Copy)]
pub struct $ty(pub [u8; $len]);
impl Default for $ty {
fn default() -> Self {
$ty([0; $len])
}
}
impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_fmt(format_args!("{:02x?}", &self.0[..]))
}
}
impl Serialize for $ty {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_tuple($len)?;
for e in &self.0[..] {
seq.serialize_element(e)?;
}
seq.end()
}
}
)+
}
}
array_impls!(SigOrPubKey: 0x100, Reserved64: 0x30); |
use crate::{
Coordinate, CoordinateType, Line, LineString, MultiLineString, MultiPoint, MultiPolygon,
Polygon, Rect, Triangle,
};
use geo_types::private_utils::{get_bounding_rect, line_string_bounding_rect};
/// Calculation of the bounding rectangle of a geometry.
pub trait BoundingRect<T: CoordinateType> {
type Output;
/// Return the bounding rectangle of a geometry
///
/// # Examples
///
/// ```
/// use geo::algorithm::bounding_rect::BoundingRect;
/// use geo::{LineString, Point};
///
/// let mut vec = Vec::new();
/// vec.push(Point::new(40.02f64, 116.34));
/// vec.push(Point::new(42.02f64, 116.34));
/// vec.push(Point::new(42.02f64, 118.34));
/// let linestring = LineString::from(vec);
/// let bounding_rect = linestring.bounding_rect().unwrap();
///
/// assert_eq!(40.02f64, bounding_rect.min().x);
/// assert_eq!(42.02f64, bounding_rect.max().x);
/// assert_eq!(116.34, bounding_rect.min().y);
/// assert_eq!(118.34, bounding_rect.max().y);
/// ```
fn bounding_rect(&self) -> Self::Output;
}
impl<T> BoundingRect<T> for MultiPoint<T>
where
T: CoordinateType,
{
type Output = Option<Rect<T>>;
///
/// Return the BoundingRect for a MultiPoint
fn bounding_rect(&self) -> Self::Output {
get_bounding_rect(self.0.iter().map(|p| p.0))
}
}
impl<T> BoundingRect<T> for Line<T>
where
T: CoordinateType,
{
type Output = Rect<T>;
fn bounding_rect(&self) -> Self::Output {
let a = self.start;
let b = self.end;
let (xmin, xmax) = if a.x <= b.x { (a.x, b.x) } else { (b.x, a.x) };
let (ymin, ymax) = if a.y <= b.y { (a.y, b.y) } else { (b.y, a.y) };
Rect::new(
Coordinate { x: xmin, y: ymin },
Coordinate { x: xmax, y: ymax },
)
}
}
impl<T> BoundingRect<T> for LineString<T>
where
T: CoordinateType,
{
type Output = Option<Rect<T>>;
///
/// Return the BoundingRect for a LineString
fn bounding_rect(&self) -> Self::Output {
line_string_bounding_rect(self)
}
}
impl<T> BoundingRect<T> for MultiLineString<T>
where
T: CoordinateType,
{
type Output = Option<Rect<T>>;
///
/// Return the BoundingRect for a MultiLineString
fn bounding_rect(&self) -> Self::Output {
get_bounding_rect(self.0.iter().flat_map(|line| line.0.iter().cloned()))
}
}
impl<T> BoundingRect<T> for Polygon<T>
where
T: CoordinateType,
{
type Output = Option<Rect<T>>;
///
/// Return the BoundingRect for a Polygon
fn bounding_rect(&self) -> Self::Output {
let line = self.exterior();
get_bounding_rect(line.0.iter().cloned())
}
}
impl<T> BoundingRect<T> for MultiPolygon<T>
where
T: CoordinateType,
{
type Output = Option<Rect<T>>;
///
/// Return the BoundingRect for a MultiPolygon
fn bounding_rect(&self) -> Self::Output {
get_bounding_rect(
self.0
.iter()
.flat_map(|poly| poly.exterior().0.iter().cloned()),
)
}
}
impl<T> BoundingRect<T> for Triangle<T>
where
T: CoordinateType,
{
type Output = Rect<T>;
fn bounding_rect(&self) -> Self::Output {
get_bounding_rect(self.to_array().iter().cloned()).unwrap()
}
}
impl<T> BoundingRect<T> for Rect<T>
where
T: CoordinateType,
{
type Output = Rect<T>;
fn bounding_rect(&self) -> Self::Output {
*self
}
}
#[cfg(test)]
mod test {
use crate::algorithm::bounding_rect::BoundingRect;
use crate::line_string;
use crate::{
polygon, Coordinate, Line, LineString, MultiLineString, MultiPoint, MultiPolygon, Polygon,
Rect,
};
#[test]
fn empty_linestring_test() {
let linestring: LineString<f32> = line_string![];
let bounding_rect = linestring.bounding_rect();
assert!(bounding_rect.is_none());
}
#[test]
fn linestring_one_point_test() {
let linestring = line_string![(x: 40.02f64, y: 116.34)];
let bounding_rect = Rect::new(
Coordinate {
x: 40.02f64,
y: 116.34,
},
Coordinate {
x: 40.02,
y: 116.34,
},
);
assert_eq!(bounding_rect, linestring.bounding_rect().unwrap());
}
#[test]
fn linestring_test() {
let linestring = line_string![
(x: 1., y: 1.),
(x: 2., y: -2.),
(x: -3., y: -3.),
(x: -4., y: 4.)
];
let bounding_rect = Rect::new(Coordinate { x: -4., y: -3. }, Coordinate { x: 2., y: 4. });
assert_eq!(bounding_rect, linestring.bounding_rect().unwrap());
}
#[test]
fn multilinestring_test() {
let multiline = MultiLineString(vec![
line_string![(x: 1., y: 1.), (x: -40., y: 1.)],
line_string![(x: 1., y: 1.), (x: 50., y: 1.)],
line_string![(x: 1., y: 1.), (x: 1., y: -60.)],
line_string![(x: 1., y: 1.), (x: 1., y: 70.)],
]);
let bounding_rect = Rect::new(
Coordinate { x: -40., y: -60. },
Coordinate { x: 50., y: 70. },
);
assert_eq!(bounding_rect, multiline.bounding_rect().unwrap());
}
#[test]
fn multipoint_test() {
let multipoint = MultiPoint::from(vec![(1., 1.), (2., -2.), (-3., -3.), (-4., 4.)]);
let bounding_rect = Rect::new(Coordinate { x: -4., y: -3. }, Coordinate { x: 2., y: 4. });
assert_eq!(bounding_rect, multipoint.bounding_rect().unwrap());
}
#[test]
fn polygon_test() {
let linestring = line_string![
(x: 0., y: 0.),
(x: 5., y: 0.),
(x: 5., y: 6.),
(x: 0., y: 6.),
(x: 0., y: 0.),
];
let line_bounding_rect = linestring.bounding_rect().unwrap();
let poly = Polygon::new(linestring, Vec::new());
assert_eq!(line_bounding_rect, poly.bounding_rect().unwrap());
}
#[test]
fn multipolygon_test() {
let mpoly = MultiPolygon(vec![
polygon![(x: 0., y: 0.), (x: 50., y: 0.), (x: 0., y: -70.), (x: 0., y: 0.)],
polygon![(x: 0., y: 0.), (x: 5., y: 0.), (x: 0., y: 80.), (x: 0., y: 0.)],
polygon![(x: 0., y: 0.), (x: -60., y: 0.), (x: 0., y: 6.), (x: 0., y: 0.)],
]);
let bounding_rect = Rect::new(
Coordinate { x: -60., y: -70. },
Coordinate { x: 50., y: 80. },
);
assert_eq!(bounding_rect, mpoly.bounding_rect().unwrap());
}
#[test]
fn line_test() {
let line1 = Line::new(Coordinate { x: 0., y: 1. }, Coordinate { x: 2., y: 3. });
let line2 = Line::new(Coordinate { x: 2., y: 3. }, Coordinate { x: 0., y: 1. });
assert_eq!(
line1.bounding_rect(),
Rect::new(Coordinate { x: 0., y: 1. }, Coordinate { x: 2., y: 3. },)
);
assert_eq!(
line2.bounding_rect(),
Rect::new(Coordinate { x: 0., y: 1. }, Coordinate { x: 2., y: 3. },)
);
}
}
|
//! Framegraph implementation for Rendy engine.
#![forbid(overflowing_literals)]
#![deny(missing_copy_implementations)]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![deny(intra_doc_link_resolution_failure)]
#![deny(path_statements)]
#![deny(trivial_bounds)]
#![deny(type_alias_bounds)]
#![deny(unconditional_recursion)]
#![deny(unions_with_drop_fields)]
#![deny(while_true)]
// #![deny(unused)]
#![deny(bad_style)]
#![deny(future_incompatible)]
#![warn(rust_2018_compatibility)]
#![warn(rust_2018_idioms)]
extern crate rendy_chain as chain;
extern crate rendy_command as command;
extern crate rendy_resource as resource;
extern crate smallvec;
mod node;
mod graph;
pub use node::{Node, NodeDesc, NodeBuilder};
pub use graph::Graph;
|
mod clip;
mod neighborhoods;
mod osm_reader;
mod split_ways;
use abstutil::{prettyprint_usize, Timer};
use geom::{Distance, FindClosest, Line, PolyLine, Pt2D};
use kml::ExtraShapes;
use map_model::{osm, raw_data, LaneID, OffstreetParking, Position, LANE_THICKNESS};
use std::collections::BTreeMap;
pub struct Flags {
pub osm: String,
pub parking_shapes: Option<String>,
pub street_signs: Option<String>,
pub offstreet_parking: Option<String>,
pub gtfs: Option<String>,
pub neighborhoods: Option<String>,
pub clip: Option<String>,
pub output: String,
}
pub fn convert(flags: &Flags, timer: &mut abstutil::Timer) -> raw_data::Map {
let mut map = split_ways::split_up_roads(
osm_reader::extract_osm(&flags.osm, &flags.clip, timer),
timer,
);
clip::clip_map(&mut map, timer);
// Need to do a first pass of removing cul-de-sacs here, or we wind up with loop PolyLines when doing the parking hint matching.
abstutil::retain_btreemap(&mut map.roads, |_, r| r.i1 != r.i2);
check_orig_ids(&map);
if let Some(ref path) = flags.parking_shapes {
use_parking_hints(&mut map, path, timer);
}
if let Some(ref path) = flags.street_signs {
use_street_signs(&mut map, path, timer);
}
if let Some(ref path) = flags.offstreet_parking {
use_offstreet_parking(&mut map, path, timer);
}
if let Some(ref path) = flags.gtfs {
timer.start("load GTFS");
map.bus_routes = gtfs::load(path).unwrap();
timer.stop("load GTFS");
}
if let Some(ref path) = flags.neighborhoods {
timer.start("convert neighborhood polygons");
neighborhoods::convert(path, map.name.clone(), &map.gps_bounds);
timer.stop("convert neighborhood polygons");
}
map
}
fn check_orig_ids(map: &raw_data::Map) {
{
let mut ids = BTreeMap::new();
for (id, r) in &map.roads {
if let Some(id2) = ids.get(&r.orig_id) {
panic!(
"Both {} and {} have the same orig_id: {:?}",
id, id2, r.orig_id
);
} else {
ids.insert(r.orig_id, *id);
}
}
}
{
let mut ids = BTreeMap::new();
for (id, i) in &map.intersections {
if let Some(id2) = ids.get(&i.orig_id) {
panic!(
"Both {} and {} have the same orig_id: {:?}",
id, id2, i.orig_id
);
} else {
ids.insert(i.orig_id, *id);
}
}
}
}
fn use_parking_hints(map: &mut raw_data::Map, path: &str, timer: &mut Timer) {
timer.start("apply parking hints");
let shapes: ExtraShapes = abstutil::read_binary(path, timer).expect("loading blockface failed");
// Match shapes with the nearest road + direction (true for forwards)
let mut closest: FindClosest<(raw_data::StableRoadID, bool)> =
FindClosest::new(&map.gps_bounds.to_bounds());
for (id, r) in &map.roads {
let center = PolyLine::new(r.center_points.clone());
closest.add(
(*id, true),
center.shift_right(LANE_THICKNESS).get(timer).points(),
);
closest.add(
(*id, false),
center.shift_left(LANE_THICKNESS).get(timer).points(),
);
}
for s in shapes.shapes.into_iter() {
let pts = if let Some(pts) = map.gps_bounds.try_convert(&s.points) {
pts
} else {
continue;
};
if pts.len() > 1 {
// The blockface line endpoints will be close to other roads, so match based on the
// middle of the blockface.
// TODO Long blockfaces sometimes cover two roads. Should maybe find ALL matches within
// the threshold distance?
let middle = PolyLine::new(pts).middle();
if let Some(((r, fwds), _)) = closest.closest_pt(middle, LANE_THICKNESS * 5.0) {
let category = s.attributes.get("PARKING_CATEGORY");
let has_parking = category != Some(&"None".to_string())
&& category != Some(&"No Parking Allowed".to_string());
// Blindly override prior values.
if has_parking {
map.roads.get_mut(&r).unwrap().osm_tags.insert(
if fwds {
osm::PARKING_LANE_FWD.to_string()
} else {
osm::PARKING_LANE_BACK.to_string()
},
"true".to_string(),
);
} else {
map.roads.get_mut(&r).unwrap().osm_tags.remove(if fwds {
osm::PARKING_LANE_FWD
} else {
osm::PARKING_LANE_BACK
});
}
}
}
}
timer.stop("apply parking hints");
}
fn use_street_signs(map: &mut raw_data::Map, path: &str, timer: &mut Timer) {
timer.start("apply street signs to override parking hints");
let shapes: ExtraShapes =
abstutil::read_binary(path, timer).expect("loading street_signs failed");
// Match shapes with the nearest road + direction (true for forwards)
let mut closest: FindClosest<(raw_data::StableRoadID, bool)> =
FindClosest::new(&map.gps_bounds.to_bounds());
for (id, r) in &map.roads {
let center = PolyLine::new(r.center_points.clone());
closest.add(
(*id, true),
center.shift_right(LANE_THICKNESS).get(timer).points(),
);
closest.add(
(*id, false),
center.shift_left(LANE_THICKNESS).get(timer).points(),
);
}
let mut applied = 0;
for s in shapes.shapes.into_iter() {
let pts = if let Some(pts) = map.gps_bounds.try_convert(&s.points) {
pts
} else {
continue;
};
if pts.len() == 1 {
if let Some(((r, fwds), _)) = closest.closest_pt(pts[0], LANE_THICKNESS * 5.0) {
// TODO Model RPZ, paid on-street spots, limited times, etc.
let no_parking =
s.attributes.get("TEXT") == Some(&"NO PARKING ANYTIME".to_string());
if no_parking {
applied += 1;
map.roads.get_mut(&r).unwrap().osm_tags.remove(if fwds {
osm::PARKING_LANE_FWD
} else {
osm::PARKING_LANE_BACK
});
}
}
}
}
timer.note(format!(
"Applied {} street signs",
prettyprint_usize(applied)
));
timer.stop("apply street signs to override parking hints");
}
fn use_offstreet_parking(map: &mut raw_data::Map, path: &str, timer: &mut Timer) {
timer.start("match offstreet parking points");
let shapes = kml::load(path, &map.gps_bounds, timer).expect("loading offstreet_parking failed");
let mut closest: FindClosest<raw_data::StableBuildingID> =
FindClosest::new(&map.gps_bounds.to_bounds());
for (id, b) in &map.buildings {
closest.add(*id, b.polygon.points());
}
// TODO Another function just to use ?. Try blocks would rock.
let mut handle_shape: Box<dyn FnMut(kml::ExtraShape) -> Option<()>> = Box::new(|s| {
assert_eq!(s.points.len(), 1);
let pt = Pt2D::from_gps(s.points[0], &map.gps_bounds)?;
let (id, _) = closest.closest_pt(pt, Distance::meters(50.0))?;
// TODO Handle parking lots.
if !map.buildings[&id].polygon.contains_pt(pt) {
return None;
}
let name = s.attributes.get("DEA_FACILITY_NAME")?.to_string();
let num_stalls = s.attributes.get("DEA_STALLS")?.parse::<usize>().ok()?;
// TODO Update the existing one instead
if let Some(ref existing) = map.buildings[&id].parking {
// TODO Can't use timer inside this closure
println!(
"Two offstreet parking hints apply to {}: {} @ {}, and {} @ {}",
id, existing.num_stalls, existing.name, num_stalls, name
);
}
map.buildings.get_mut(&id).unwrap().parking = Some(OffstreetParking {
name,
num_stalls,
// Temporary values, populate later
driveway_line: Line::new(Pt2D::new(0.0, 0.0), Pt2D::new(1.0, 1.0)),
driving_pos: Position::new(LaneID(0), Distance::ZERO),
});
None
});
for s in shapes.shapes.into_iter() {
handle_shape(s);
}
timer.stop("match offstreet parking points");
}
|
extern crate errno;
extern crate telamon_gen;
use telamon_gen::ir::{CmpOp, CounterKind, CounterVisibility, SetDefKey};
use telamon_gen::lexer::*;
use errno::Errno;
#[test]
#[allow(clippy::cyclomatic_complexity)]
fn lexer_initial() {
// Invalid's Token
assert_eq!(
Lexer::new(b"!".to_vec()).collect::<Vec<_>>(),
vec![Err(LexicalError {
cause: Spanned {
beg: Position::default(),
end: Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
data: ErrorKind::InvalidToken {
token: String::from("!"),
},
},
})]
);
// ChoiceIdent's Token
assert_eq!(
Lexer::new(b"az_09".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::ChoiceIdent(String::from("az_09")),
Position {
position: LexerPosition {
column: 5,
..Default::default()
},
..Default::default()
},
))]
);
// SetIdent's Token
assert_eq!(
Lexer::new(b"Az_09".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetIdent(String::from("Az_09")),
Position {
position: LexerPosition {
column: 5,
..Default::default()
},
..Default::default()
},
))]
);
// ValueIdent's Token
assert_eq!(
Lexer::new(b"AZ_09".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::ValueIdent(String::from("AZ_09")),
Position {
position: LexerPosition {
column: 5,
..Default::default()
},
..Default::default()
},
))]
);
// Var's Token
assert_eq!(
Lexer::new(b"$vV".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Var(String::from("vV")),
Position {
position: LexerPosition {
column: 3,
..Default::default()
},
..Default::default()
},
))]
);
// Alias's Token
assert_eq!(
Lexer::new(b"alias".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Alias,
Position {
position: LexerPosition {
column: 5,
..Default::default()
},
..Default::default()
},
))]
);
// Counter's Token
assert_eq!(
Lexer::new(b"counter".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Counter,
Position {
position: LexerPosition {
column: 7,
..Default::default()
},
..Default::default()
},
))]
);
// Define's Token
assert_eq!(
Lexer::new(b"define".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Define,
Position {
position: LexerPosition {
column: 6,
..Default::default()
},
..Default::default()
},
))]
);
// Enum's Token
assert_eq!(
Lexer::new(b"enum".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Enum,
Position {
position: LexerPosition {
column: 4,
..Default::default()
},
..Default::default()
},
))]
);
// Forall's Token
assert_eq!(
Lexer::new(b"forall".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Forall,
Position {
position: LexerPosition {
column: 6,
..Default::default()
},
..Default::default()
},
))]
);
// In's Token
assert_eq!(
Lexer::new(b"in".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::In,
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Is's Token
assert_eq!(
Lexer::new(b"is".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Is,
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Not's Token
assert_eq!(
Lexer::new(b"not".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Not,
Position {
position: LexerPosition {
column: 3,
..Default::default()
},
..Default::default()
},
))]
);
// Require's Token
assert_eq!(
Lexer::new(b"require".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Require,
Position {
position: LexerPosition {
column: 7,
..Default::default()
},
..Default::default()
},
))]
);
// Mul's CounterKind Token
assert_eq!(
Lexer::new(b"mul".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CounterKind(CounterKind::Mul),
Position {
position: LexerPosition {
column: 3,
..Default::default()
},
..Default::default()
},
))]
);
// Sum's CounterKind Token
assert_eq!(
Lexer::new(b"sum".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CounterKind(CounterKind::Add),
Position {
position: LexerPosition {
column: 3,
..Default::default()
},
..Default::default()
},
))]
);
// Value's Token
assert_eq!(
Lexer::new(b"value".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Value,
Position {
position: LexerPosition {
column: 5,
..Default::default()
},
..Default::default()
},
))]
);
// When's Token
assert_eq!(
Lexer::new(b"when".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::When,
Position {
position: LexerPosition {
column: 4,
..Default::default()
},
..Default::default()
},
))]
);
// Trigger's Token
assert_eq!(
Lexer::new(b"trigger".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Trigger,
Position {
position: LexerPosition {
column: 7,
..Default::default()
},
..Default::default()
},
))]
);
// NoMax's CounterVisibility Token
assert_eq!(
Lexer::new(b"half".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CounterVisibility(CounterVisibility::NoMax),
Position {
position: LexerPosition {
column: 4,
..Default::default()
},
..Default::default()
},
))]
);
// HiddenMax's CounterVisibility Token
assert_eq!(
Lexer::new(b"internal".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CounterVisibility(CounterVisibility::HiddenMax),
Position {
position: LexerPosition {
column: 8,
..Default::default()
},
..Default::default()
},
))]
);
// Base's Token
assert_eq!(
Lexer::new(b"base".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Base,
Position {
position: LexerPosition {
column: 4,
..Default::default()
},
..Default::default()
},
))]
);
// item_type's SetDefKey Token
assert_eq!(
Lexer::new(b"item_type".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::ItemType),
Position {
position: LexerPosition {
column: 9,
..Default::default()
},
..Default::default()
},
))]
);
// NewObjs's SetDefKey Token
assert_eq!(
Lexer::new(b"new_objs".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::NewObjs),
Position {
position: LexerPosition {
column: 8,
..Default::default()
},
..Default::default()
},
))]
);
// IdType's SetDefKey Token
assert_eq!(
Lexer::new(b"id_type".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::IdType),
Position {
position: LexerPosition {
column: 7,
..Default::default()
},
..Default::default()
},
))]
);
// ItemGetter's SetDefKey Token
assert_eq!(
Lexer::new(b"item_getter".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::ItemGetter),
Position {
position: LexerPosition {
column: 11,
..Default::default()
},
..Default::default()
},
))]
);
// IdGetter's SetDefKey Token
assert_eq!(
Lexer::new(b"id_getter".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::IdGetter),
Position {
position: LexerPosition {
column: 9,
..Default::default()
},
..Default::default()
},
))]
);
// Iter's SetDefKey Token
assert_eq!(
Lexer::new(b"iterator".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::Iter),
Position {
position: LexerPosition {
column: 8,
..Default::default()
},
..Default::default()
},
))]
);
// Prefix's SetDefKey Token
assert_eq!(
Lexer::new(b"var_prefix".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::Prefix),
Position {
position: LexerPosition {
column: 10,
..Default::default()
},
..Default::default()
},
))]
);
// Reverse's SetDefKey Token
assert_eq!(
Lexer::new(b"reverse".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::Reverse),
Position {
position: LexerPosition {
column: 7,
..Default::default()
},
..Default::default()
},
))]
);
// AddToSet's SetDefKey Token
assert_eq!(
Lexer::new(b"add_to_set".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::AddToSet),
Position {
position: LexerPosition {
column: 10,
..Default::default()
},
..Default::default()
},
))]
);
// FromSuperset's SetDefKey Token
assert_eq!(
Lexer::new(b"from_superset".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SetDefKey(SetDefKey::FromSuperset),
Position {
position: LexerPosition {
column: 13,
..Default::default()
},
..Default::default()
},
))]
);
// Set's Token
assert_eq!(
Lexer::new(b"set".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Set,
Position {
position: LexerPosition {
column: 3,
..Default::default()
},
..Default::default()
},
))]
);
// SubsetOf's Token
assert_eq!(
Lexer::new(b"subsetof".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::SubsetOf,
Position {
position: LexerPosition {
column: 8,
..Default::default()
},
..Default::default()
},
))]
);
// Disjoint's Token
assert_eq!(
Lexer::new(b"disjoint".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Disjoint,
Position {
position: LexerPosition {
column: 8,
..Default::default()
},
..Default::default()
},
))]
);
// Quotient's Token
assert_eq!(
Lexer::new(b"quotient".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Quotient,
Position {
position: LexerPosition {
column: 8,
..Default::default()
},
..Default::default()
},
))]
);
// Of's Token
assert_eq!(
Lexer::new(b"of".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Of,
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// False's Bool Token
assert_eq!(
Lexer::new(b"false".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Bool(false),
Position {
position: LexerPosition {
column: 5,
..Default::default()
},
..Default::default()
},
))]
);
// True's Bool Token
assert_eq!(
Lexer::new(b"true".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Bool(true),
Position {
position: LexerPosition {
column: 4,
..Default::default()
},
..Default::default()
},
))]
);
// Colon's Token
assert_eq!(
Lexer::new(b":".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Colon,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// Comma's Token
assert_eq!(
Lexer::new(b",".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Comma,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// LParen's Token
assert_eq!(
Lexer::new(b"(".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::LParen,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// RParen's Token
assert_eq!(
Lexer::new(b")".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::RParen,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// Bitor's Token
assert_eq!(
Lexer::new(b"|".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::BitOr,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// Or's Token
assert_eq!(
Lexer::new(b"||".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Or,
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// And's Token
assert_eq!(
Lexer::new(b"&&".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::And,
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Gt's CmpOp Token
assert_eq!(
Lexer::new(b">".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CmpOp(CmpOp::Gt),
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// Lt's CmpOp Token
assert_eq!(
Lexer::new(b"<".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CmpOp(CmpOp::Lt),
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// Ge's CmpOp Token
assert_eq!(
Lexer::new(b">=".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CmpOp(CmpOp::Geq),
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Le's CmpOp Token
assert_eq!(
Lexer::new(b"<=".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CmpOp(CmpOp::Leq),
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Eq's CmpOp Token
assert_eq!(
Lexer::new(b"==".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CmpOp(CmpOp::Eq),
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Neq's CmpOp Token
assert_eq!(
Lexer::new(b"!=".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::CmpOp(CmpOp::Neq),
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Equal's Token
assert_eq!(
Lexer::new(b"=".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Equal,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// End's Token
assert_eq!(
Lexer::new(b"end".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::End,
Position {
position: LexerPosition {
column: 3,
..Default::default()
},
..Default::default()
},
))]
);
// Symmetric's Token
assert_eq!(
Lexer::new(b"symmetric".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Symmetric,
Position {
position: LexerPosition {
column: 9,
..Default::default()
},
..Default::default()
},
))]
);
// AntiSymmetric's Token
assert_eq!(
Lexer::new(b"antisymmetric".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::AntiSymmetric,
Position {
position: LexerPosition {
column: 13,
..Default::default()
},
..Default::default()
},
))]
);
// Arrow's Token
assert_eq!(
Lexer::new(b"->".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Arrow,
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
// Divide's Token
assert_eq!(
Lexer::new(b"/".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Divide,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
))]
);
// Integer's Token
assert_eq!(
Lexer::new(b"integer".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position::default(),
Token::Integer,
Position {
position: LexerPosition {
column: 7,
..Default::default()
},
..Default::default()
},
))]
);
}
#[test]
fn lexer_comment_mode() {
// C_COMMENT's Token
assert_eq!(
Lexer::new(b"/* com */ ".to_vec()).collect::<Vec<_>>(),
vec![]
);
assert_eq!(
Lexer::new(b"/* com \n com */ ".to_vec()).collect::<Vec<_>>(),
vec![]
);
assert_eq!(
Lexer::new(b"| /* comment */ |".to_vec()).collect::<Vec<_>>(),
vec![
Ok((
Position::default(),
Token::BitOr,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
)),
Ok((
Position {
position: LexerPosition {
column: 16,
..Default::default()
},
..Default::default()
},
Token::BitOr,
Position {
position: LexerPosition {
column: 17,
..Default::default()
},
..Default::default()
},
)),
]
);
assert_eq!(
Lexer::new(b"| /* comment \n comment */ |".to_vec()).collect::<Vec<_>>(),
vec![
Ok((
Position::default(),
Token::BitOr,
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
)),
Ok((
Position {
position: LexerPosition {
column: 26,
line: 1,
},
..Default::default()
},
Token::BitOr,
Position {
position: LexerPosition {
column: 27,
line: 1,
},
..Default::default()
},
)),
]
);
}
#[test]
fn lexer_doc_mode() {
// Outer Line Doc's Token
assert_eq!(
Lexer::new(b"/// comment ".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 0,
..Default::default()
},
..Default::default()
},
Token::Doc(String::from(" comment ")),
Position {
position: LexerPosition {
column: 12,
..Default::default()
},
..Default::default()
},
))]
);
assert_eq!(
Lexer::new(b" /// comment ".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
Token::Doc(String::from(" comment ")),
Position {
position: LexerPosition {
column: 13,
..Default::default()
},
..Default::default()
},
))]
);
// Outer Line MultiDoc's Token
assert_eq!(
Lexer::new(b"/// comment \n /// comment ".to_vec()).collect::<Vec<_>>(),
vec![
Ok((
Position {
position: LexerPosition {
column: 0,
..Default::default()
},
..Default::default()
},
Token::Doc(String::from(" comment ")),
Position {
position: LexerPosition {
column: 12,
..Default::default()
},
..Default::default()
},
)),
Ok((
Position {
position: LexerPosition { column: 1, line: 1 },
..Default::default()
},
Token::Doc(String::from(" comment ")),
Position {
position: LexerPosition {
column: 13,
line: 1,
},
..Default::default()
},
)),
]
);
// Line Comment Doc's Token
assert_eq!(
Lexer::new(b"// comment".to_vec()).collect::<Vec<_>>(),
vec![]
);
// Line Comment MultiDoc's Token
assert_eq!(
Lexer::new(b"// comment \n // comment".to_vec()).collect::<Vec<_>>(),
vec![]
);
}
#[test]
fn lexer_code_mode() {
// Simple Code's Token
assert_eq!(
Lexer::new(b"\"_\"".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
Token::Code(String::from("_")),
Position {
position: LexerPosition {
column: 2,
..Default::default()
},
..Default::default()
},
))]
);
assert_eq!(
Lexer::new(b"\"__\"".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
Token::Code(String::from("__")),
Position {
position: LexerPosition {
column: 3,
..Default::default()
},
..Default::default()
},
))]
);
// Multiline Code's Token
assert_eq!(
Lexer::new(b"\"_\\\n_\"".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
Token::Code(String::from("__")),
Position {
position: LexerPosition { column: 2, line: 1 },
..Default::default()
},
))]
);
assert_eq!(
Lexer::new(b"\"_\\\n _\"".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
Token::Code(String::from("__")),
Position {
position: LexerPosition { column: 2, line: 1 },
..Default::default()
},
))]
);
assert_eq!(
Lexer::new(b"\"_\\\n__\"".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
Token::Code(String::from("___")),
Position {
position: LexerPosition { column: 3, line: 1 },
..Default::default()
},
))]
);
// Repetition Code's Token
assert_eq!(
Lexer::new(b"\"_\" \"_\"".to_vec()).collect::<Vec<_>>(),
vec![Ok((
Position {
position: LexerPosition {
column: 1,
..Default::default()
},
..Default::default()
},
Token::Code(String::from("__")),
Position {
position: LexerPosition {
column: 6,
..Default::default()
},
..Default::default()
},
))]
);
}
#[test]
fn lexer_include() {
// Unexist include.
assert_eq!(
Lexer::new(b"include \"/dev/unexist\"".to_vec()).collect::<Vec<_>>(),
vec![Err(LexicalError {
cause: Spanned {
beg: Position::default(),
end: Position {
position: LexerPosition {
column: 22,
..Default::default()
},
..Default::default()
},
data: ErrorKind::InvalidInclude {
name: String::from("/dev/unexist"),
code: Errno(2),
},
},
})]
);
// Header include.
let filename: &str =
concat!(env!("CARGO_MANIFEST_DIR"), "/tests/extra/include_foo.exh");
let include = format!("include \"{}\"", filename);
assert_eq!(Lexer::new(include.as_bytes().to_vec()).count(), 9);
// Two same header include.
let filename: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/extra/enum_foo.exh");
let include = format!("include \"{}\"", filename);
assert_eq!(Lexer::new(include.as_bytes().to_vec()).count(), 7);
assert_eq!(Lexer::new(include.as_bytes().to_vec()).count(), 7);
// Sub header include.
let filename: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/extra/sub/include_foo.exh"
);
let include = format!("include \"{}\"", filename);
assert_eq!(Lexer::new(include.as_bytes().to_vec()).count(), 7);
}
#[test]
fn lexer_include_set() {
// Header include.
// ```
// include ab
// set a
// include c
// set c
// set b
// ```
let filename: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/extra/set/acb.exh");
let include = format!("include \"{}\"", filename);
assert_eq!(
Lexer::new(include.as_bytes().to_vec())
.map(|t| t.unwrap())
.map(|(_, t, _)| t)
.collect::<Vec<_>>(),
vec![
Token::Set,
Token::SetIdent(String::from("Aa")),
Token::Colon,
Token::SetDefKey(SetDefKey::ItemType),
Token::Equal,
Token::Code(String::from("ir::inst::Obj")),
Token::SetDefKey(SetDefKey::IdType),
Token::Equal,
Token::Code(String::from("ir::inst::Id")),
Token::SetDefKey(SetDefKey::ItemGetter),
Token::Equal,
Token::Code(String::from("ir::inst::get($fun, $id)")),
Token::SetDefKey(SetDefKey::IdGetter),
Token::Equal,
Token::Code(String::from("ir::inst::Obj::id($item)")),
Token::SetDefKey(SetDefKey::Iter),
Token::Equal,
Token::Code(String::from("ir::inst::iter($fun)")),
Token::SetDefKey(SetDefKey::Prefix),
Token::Equal,
Token::Code(String::from("inst")),
Token::SetDefKey(SetDefKey::NewObjs),
Token::Equal,
Token::Code(String::from("$objs.inst")),
Token::End,
Token::Set,
Token::SetIdent(String::from("Cc")),
Token::Colon,
Token::SetDefKey(SetDefKey::ItemType),
Token::Equal,
Token::Code(String::from("ir::inst::Obj")),
Token::SetDefKey(SetDefKey::IdType),
Token::Equal,
Token::Code(String::from("ir::inst::Id")),
Token::SetDefKey(SetDefKey::ItemGetter),
Token::Equal,
Token::Code(String::from("ir::inst::get($fun, $id)")),
Token::SetDefKey(SetDefKey::IdGetter),
Token::Equal,
Token::Code(String::from("ir::inst::Obj::id($item)")),
Token::SetDefKey(SetDefKey::Iter),
Token::Equal,
Token::Code(String::from("ir::inst::iter($fun)")),
Token::SetDefKey(SetDefKey::Prefix),
Token::Equal,
Token::Code(String::from("inst")),
Token::SetDefKey(SetDefKey::NewObjs),
Token::Equal,
Token::Code(String::from("$objs.inst")),
Token::End,
Token::Set,
Token::SetIdent(String::from("Bb")),
Token::Colon,
Token::SetDefKey(SetDefKey::ItemType),
Token::Equal,
Token::Code(String::from("ir::inst::Obj")),
Token::SetDefKey(SetDefKey::IdType),
Token::Equal,
Token::Code(String::from("ir::inst::Id")),
Token::SetDefKey(SetDefKey::ItemGetter),
Token::Equal,
Token::Code(String::from("ir::inst::get($fun, $id)")),
Token::SetDefKey(SetDefKey::IdGetter),
Token::Equal,
Token::Code(String::from("ir::inst::Obj::id($item)")),
Token::SetDefKey(SetDefKey::Iter),
Token::Equal,
Token::Code(String::from("ir::inst::iter($fun)")),
Token::SetDefKey(SetDefKey::Prefix),
Token::Equal,
Token::Code(String::from("inst")),
Token::SetDefKey(SetDefKey::NewObjs),
Token::Equal,
Token::Code(String::from("$objs.inst")),
Token::End,
]
);
}
#[test]
fn lexer_include_enum() {
// Header include.
// ```
// include enum_foo
// enum foo
// enum Bar
// ```
let filename: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/extra/foo_bar.exh");
let include = format!("include \"{}\"", filename);
assert_eq!(
Lexer::new(include.as_bytes().to_vec())
.map(|t| t.unwrap())
.map(|(_, t, _)| t)
.collect::<Vec<_>>(),
vec![
Token::Define,
Token::Enum,
Token::ChoiceIdent(String::from("foo")),
Token::LParen,
Token::RParen,
Token::Colon,
Token::End,
Token::Define,
Token::Enum,
Token::ChoiceIdent(String::from("bar")),
Token::LParen,
Token::RParen,
Token::Colon,
Token::Value,
Token::ValueIdent(String::from("A")),
Token::Colon,
Token::Value,
Token::ValueIdent(String::from("B")),
Token::Colon,
Token::End,
]
);
}
#[test]
#[ignore]
fn lexer_include_guard() {
// double header include.
let filename: &str =
concat!(env!("CARGO_MANIFEST_DIR"), "/tests/extra/include_a.exh");
let include = format!("include \"{}\"", filename);
let _ = Lexer::new(include.as_bytes().to_vec()).collect::<Vec<_>>();
}
|
use crate::file_util::read_non_blank_lines;
use std::str::FromStr;
use std::collections::HashMap;
use itertools::Itertools;
#[derive(Debug)]
struct Instructions {
mask: String,
assignments: Vec<(usize, usize)>
}
#[allow(dead_code)]
pub fn run_day_fourteen() {
let mut lines = read_non_blank_lines("assets/day_fourteen");
let parsed = parse_lines(&mut lines);
let sum_part_one: usize = execute_task_one(&parsed)
.values().sum();
let sum_part_two: usize = execute_task_two(&parsed)
.values().sum();
println!("Part 1 {}", sum_part_one);
println!("Part 2 {}", sum_part_two);
}
fn execute_task_two(instructions: &[Instructions]) -> HashMap<usize, usize> {
let mut address_space = HashMap::new();
for instruction in instructions.iter() {
let ones_mask = get_ones_mask(&instruction.mask);
let x_masks: Vec<(usize,usize)> = instruction.mask.chars()
.rev()
.enumerate()
.filter(|c| c.1 == 'X')
.map(|c| 1 << c.0)
.fold(vec!((0_usize, 0_usize)), |mut buff, elem| {
let mut to_append = Vec::new();
for mask in buff.iter_mut() {
let mut split = *mask;
mask.0 += elem;
split.1 += elem;
to_append.push(split);
}
buff.append(&mut to_append);
buff
});
if let Some(ones_mask_val) = ones_mask {
for assignment in instruction.assignments.iter() {
let address = assignment.0 | ones_mask_val;
for x_mask in x_masks.iter() {
address_space.insert((address | x_mask.0) & !x_mask.1, assignment.1);
}
}
}
}
address_space
}
fn get_ones_mask(mask: &str) -> Option<usize> {
usize::from_str_radix(
mask.chars()
.map(|x| if x == '1' { '1' } else { '0' })
.join("")
.as_str(),
2
).ok()
}
fn execute_task_one(instructions: &[Instructions]) -> HashMap<usize, usize> {
let mut address_space = HashMap::new();
for instruction in instructions.iter() {
for assignment in instruction.assignments.iter() {
let ones_mask = get_ones_mask(&instruction.mask);
let zeros_mask = usize::from_str_radix(
instruction.mask.chars()
.map(|x| if x == '0' { '0' } else { '1' })
.join("")
.as_str(),
2
);
if let Some((ones, zeros)) = ones_mask.zip(zeros_mask.ok()) {
address_space.insert(
assignment.0,
(assignment.1 | ones) & zeros
);
}
}
}
address_space
}
fn parse_lines(lines: &mut impl Iterator<Item = String>) -> Vec<Instructions> {
let next_mask = lines.next();
let mut result = Vec::new();
if let Some(mut mask) = next_mask {
let mut assignments = Vec::new();
for assignment in lines {
let mut split_assignment = assignment.splitn(2, " = ");
if let Some(split) = split_assignment.next().zip(split_assignment.next()) {
if split.0 == "mask" {
let current_assignments = assignments;
assignments = Vec::new();
result.push(
Instructions {
mask: String::from(&mask[7..]), assignments: current_assignments
}
);
mask = assignment;
} else {
let address = usize::from_str(&split.0[4..split.0.len()-1]);
let value = usize::from_str(split.1);
if let Some(assignment) = address.ok().zip(value.ok()) {
assignments.push(assignment);
}
}
}
}
result.push(Instructions { mask, assignments })
}
result
}
#[cfg(test)]
mod tests {
use crate::day_fourteen::*;
#[test]
fn should_resolve_part_2() {
let result = execute_task_two(
&vec!(
Instructions {
mask: String::from("000000000000000000000000000000X1001X"),
assignments: vec!((42, 100))
},
Instructions {
mask: String::from("00000000000000000000000000000000X0XX"),
assignments: vec!((26, 1))
}
)
);
assert_eq!(
result.values().sum::<usize>(),
208
)
}
}
|
#[doc = "Reader of register C1ISR"]
pub type R = crate::R<u32, super::C1ISR>;
#[doc = "Reader of field `TEIF1`"]
pub type TEIF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `CTCIF1`"]
pub type CTCIF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `BRTIF1`"]
pub type BRTIF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `BTIF1`"]
pub type BTIF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `TCIF1`"]
pub type TCIF1_R = crate::R<bool, bool>;
#[doc = "Reader of field `CRQA1`"]
pub type CRQA1_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Channel x transfer error interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn teif1(&self) -> TEIF1_R {
TEIF1_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Channel x Channel Transfer Complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register. CTC is set when the last block was transferred and the channel has been automatically disabled. CTC is also set when the channel is suspended, as a result of writing EN bit to 0."]
#[inline(always)]
pub fn ctcif1(&self) -> CTCIF1_R {
CTCIF1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Channel x block repeat transfer complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn brtif1(&self) -> BRTIF1_R {
BRTIF1_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Channel x block transfer complete interrupt flag This bit is set by hardware. It is cleared by software writing 1 to the corresponding bit in the DMA_IFCRy register."]
#[inline(always)]
pub fn btif1(&self) -> BTIF1_R {
BTIF1_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - channel x buffer transfer complete"]
#[inline(always)]
pub fn tcif1(&self) -> TCIF1_R {
TCIF1_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 16 - channel x request active flag"]
#[inline(always)]
pub fn crqa1(&self) -> CRQA1_R {
CRQA1_R::new(((self.bits >> 16) & 0x01) != 0)
}
}
|
fn main() {
proconio::input!{k:usize,s:String};
if s.len()<=k{
println!("{}",s)
}else{
println!("{}...",&s[0..k])
}
} |
use std::fmt::Display;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
pub use input::{QueryAsMacroInput, QueryMacroInput};
pub use query::expand_query;
use crate::database::DatabaseExt;
use sqlx::connection::Connection;
use sqlx::database::Database;
mod args;
mod input;
mod output;
mod query;
pub async fn expand_query_file<C: Connection>(
input: QueryMacroInput,
conn: C,
checked: bool,
) -> crate::Result<TokenStream>
where
C::Database: DatabaseExt + Sized,
<C::Database as Database>::TypeInfo: Display,
{
expand_query(input.expand_file_src().await?, conn, checked).await
}
pub async fn expand_query_as<C: Connection>(
input: QueryAsMacroInput,
mut conn: C,
checked: bool,
) -> crate::Result<TokenStream>
where
C::Database: DatabaseExt + Sized,
<C::Database as Database>::TypeInfo: Display,
{
let describe = input.query_input.describe_validate(&mut conn).await?;
if describe.result_columns.is_empty() {
return Err(syn::Error::new(
input.query_input.source_span,
"query must output at least one column",
)
.into());
}
let args_tokens = args::quote_args(&input.query_input, &describe, checked)?;
let query_args = format_ident!("query_args");
let columns = output::columns_to_rust(&describe)?;
let output = output::quote_query_as::<C::Database>(
&input.query_input.source,
&input.as_ty.path,
&query_args,
&columns,
checked,
);
let arg_names = &input.query_input.arg_names;
Ok(quote! {
macro_rules! macro_result {
(#($#arg_names:expr),*) => {{
use sqlx::arguments::Arguments as _;
#args_tokens
#output
}}
}
})
}
pub async fn expand_query_file_as<C: Connection>(
input: QueryAsMacroInput,
conn: C,
checked: bool,
) -> crate::Result<TokenStream>
where
C::Database: DatabaseExt + Sized,
<C::Database as Database>::TypeInfo: Display,
{
expand_query_as(input.expand_file_src().await?, conn, checked).await
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::sync::Arc;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::types::DataType;
use common_expression::Scalar;
use once_cell::sync::Lazy;
use super::AggregateFunctionCombinatorNull;
use super::AggregateFunctionOrNullAdaptor;
use crate::aggregates::AggregateFunctionRef;
use crate::aggregates::Aggregators;
pub type AggregateFunctionCreator =
Box<dyn Fn(&str, Vec<Scalar>, Vec<DataType>) -> Result<AggregateFunctionRef> + Sync + Send>;
pub type AggregateFunctionCombinatorCreator = Box<
dyn Fn(
&str,
Vec<Scalar>,
Vec<DataType>,
&AggregateFunctionCreator,
) -> Result<AggregateFunctionRef>
+ Sync
+ Send,
>;
static FACTORY: Lazy<Arc<AggregateFunctionFactory>> = Lazy::new(|| {
let mut factory = AggregateFunctionFactory::create();
Aggregators::register(&mut factory);
Aggregators::register_combinator(&mut factory);
Arc::new(factory)
});
pub struct AggregateFunctionDescription {
pub(crate) aggregate_function_creator: AggregateFunctionCreator,
pub(crate) features: AggregateFunctionFeatures,
}
#[derive(Debug, Clone, Default)]
pub struct AggregateFunctionFeatures {
/// When the function is wrapped with Null combinator,
/// should we return Nullable type with NULL when no values were aggregated
/// or we should return non-Nullable type with default value (example: count, count_distinct, approx_count_distinct)
pub(crate) returns_default_when_only_null: bool,
// Function Category
pub category: &'static str,
// Introduce the function in brief.
pub description: &'static str,
// The definition of the function.
pub definition: &'static str,
// Example SQL of the function that can be run directly in query.
pub example: &'static str,
}
impl AggregateFunctionDescription {
pub fn creator(creator: AggregateFunctionCreator) -> AggregateFunctionDescription {
AggregateFunctionDescription {
aggregate_function_creator: creator,
features: AggregateFunctionFeatures {
returns_default_when_only_null: false,
..Default::default()
},
}
}
pub fn creator_with_features(
creator: AggregateFunctionCreator,
features: AggregateFunctionFeatures,
) -> AggregateFunctionDescription {
AggregateFunctionDescription {
aggregate_function_creator: creator,
features,
}
}
}
pub struct CombinatorDescription {
creator: AggregateFunctionCombinatorCreator,
// TODO(Winter): function document, this is very interesting.
// TODO(Winter): We can support the SHOW FUNCTION DOCUMENT `function_name` or MAN FUNCTION `function_name` query syntax.
}
impl CombinatorDescription {
pub fn creator(creator: AggregateFunctionCombinatorCreator) -> CombinatorDescription {
CombinatorDescription { creator }
}
}
pub struct AggregateFunctionFactory {
case_insensitive_desc: HashMap<String, AggregateFunctionDescription>,
case_insensitive_combinator_desc: Vec<(String, CombinatorDescription)>,
}
impl AggregateFunctionFactory {
pub(in crate::aggregates::aggregate_function_factory) fn create() -> AggregateFunctionFactory {
AggregateFunctionFactory {
case_insensitive_desc: Default::default(),
case_insensitive_combinator_desc: Default::default(),
}
}
pub fn instance() -> &'static AggregateFunctionFactory {
FACTORY.as_ref()
}
pub fn register(&mut self, name: &str, desc: AggregateFunctionDescription) {
let case_insensitive_desc = &mut self.case_insensitive_desc;
case_insensitive_desc.insert(name.to_lowercase(), desc);
}
pub fn register_combinator(&mut self, suffix: &str, desc: CombinatorDescription) {
for (exists_suffix, _) in &self.case_insensitive_combinator_desc {
if exists_suffix.eq_ignore_ascii_case(suffix) {
panic!(
"Logical error: {} combinator suffix already exists.",
suffix
);
}
}
let case_insensitive_combinator_desc = &mut self.case_insensitive_combinator_desc;
case_insensitive_combinator_desc.push((suffix.to_lowercase(), desc));
}
pub fn get(
&self,
name: impl AsRef<str>,
params: Vec<Scalar>,
arguments: Vec<DataType>,
) -> Result<AggregateFunctionRef> {
self.get_or_null(name, params, arguments, true)
}
pub fn get_or_null(
&self,
name: impl AsRef<str>,
params: Vec<Scalar>,
arguments: Vec<DataType>,
or_null: bool,
) -> Result<AggregateFunctionRef> {
let name = name.as_ref();
let mut features = AggregateFunctionFeatures::default();
// The NULL value in the list function needs to be added to the returned array column,
// so handled separately.
if name == "list" {
let agg = self.get_impl(name, params, arguments, &mut features)?;
return Ok(agg);
}
if !arguments.is_empty() && arguments.iter().any(|f| f.is_nullable_or_null()) {
let new_params = AggregateFunctionCombinatorNull::transform_params(¶ms)?;
let new_arguments = AggregateFunctionCombinatorNull::transform_arguments(&arguments)?;
let nested = self.get_impl(name, new_params, new_arguments, &mut features)?;
let agg = AggregateFunctionCombinatorNull::try_create(
name,
params,
arguments,
nested,
features.clone(),
)?;
if or_null {
return AggregateFunctionOrNullAdaptor::create(agg, features);
} else {
return Ok(agg);
}
}
let agg = self.get_impl(name, params, arguments, &mut features)?;
if or_null {
AggregateFunctionOrNullAdaptor::create(agg, features)
} else {
Ok(agg)
}
}
fn get_impl(
&self,
name: &str,
params: Vec<Scalar>,
arguments: Vec<DataType>,
features: &mut AggregateFunctionFeatures,
) -> Result<AggregateFunctionRef> {
let lowercase_name = name.to_lowercase();
let aggregate_functions_map = &self.case_insensitive_desc;
if let Some(desc) = aggregate_functions_map.get(&lowercase_name) {
*features = desc.features.clone();
return (desc.aggregate_function_creator)(name, params, arguments);
}
// find suffix
for (suffix, desc) in &self.case_insensitive_combinator_desc {
if let Some(nested_name) = lowercase_name.strip_suffix(suffix) {
let aggregate_functions_map = &self.case_insensitive_desc;
match aggregate_functions_map.get(nested_name) {
None => {
break;
}
Some(nested_desc) => {
*features = nested_desc.features.clone();
return (desc.creator)(
nested_name,
params,
arguments,
&nested_desc.aggregate_function_creator,
);
}
}
}
}
Err(ErrorCode::UnknownAggregateFunction(format!(
"Unsupported AggregateFunction: {}",
name
)))
}
pub fn contains(&self, func_name: impl AsRef<str>) -> bool {
let origin = func_name.as_ref();
let lowercase_name = origin.to_lowercase();
if self.case_insensitive_desc.contains_key(&lowercase_name) {
return true;
}
// find suffix
for (suffix, _) in &self.case_insensitive_combinator_desc {
if let Some(nested_name) = lowercase_name.strip_suffix(suffix) {
if self.case_insensitive_desc.contains_key(nested_name) {
return true;
}
}
}
false
}
pub fn registered_names(&self) -> Vec<String> {
self.case_insensitive_desc.keys().cloned().collect()
}
pub fn registered_features(&self) -> Vec<AggregateFunctionFeatures> {
self.case_insensitive_desc
.values()
.map(|v| &v.features)
.cloned()
.collect::<Vec<_>>()
}
}
|
use std;
use na::*;
use math::*;
use renderer::*;
use alga::general::SupersetOf;
use std::iter::FlatMap;
#[derive(Clone, Copy, Debug)]
pub struct MaterialPoint<T : Real + Copy>{
pub density : T,
pub material : u32,
}
pub type DenMatFn3<T> = Box<Fn(Vector3<T>) -> MaterialPoint<T>>;
pub fn intersection3_mat_a<T : Real>(a : DenMatFn3<T>, b : DenMatFn3<T>) -> DenMatFn3<T>{
Box::new(move |x|{
let a_of_x = a(x);
let maximum = Real::max(a_of_x.density, b(x).density);
MaterialPoint{density : maximum, material : if maximum <= T::zero() {a_of_x.material} else {0}}
})
}
pub fn union3_mat<T : Real>(a : DenMatFn3<T>, b : DenMatFn3<T>) -> DenMatFn3<T>{
Box::new(move |x|{
let a_of_x = a(x);
let b_of_x = b(x);
let minimum = Real::min(a_of_x.density, b_of_x.density);
if(a_of_x.density == minimum){
MaterialPoint{density : minimum, material : if minimum <= T::zero() {a_of_x.material} else {0}}
}else{
MaterialPoint{density : minimum, material : if minimum <= T::zero() {b_of_x.material} else {0}}
}
})
}
pub fn difference3_mat_a<T : Real>(a : DenMatFn3<T>, b : DenMatFn3<T>) -> DenMatFn3<T>{
Box::new(move |x|{
let a_of_x = a(x);
let minimum = Real::max(a_of_x.density, -b(x).density);
MaterialPoint{density : minimum, material : if minimum <= T::zero() {a_of_x.material} else {0}}
})
}
pub fn mk_sphere_mat<T : Real + Copy>(sphere : Sphere<T>, mat : u32) -> DenMatFn3<T>{
Box::new(move |x|{
let dist = x - sphere.center;
MaterialPoint{density : dist.dot(&dist) - sphere.rad * sphere.rad, material : mat}
})
}
pub struct VoxelMaterialGrid3<T : Real + Copy>{
pub a : T,
pub size_x : usize,
pub size_y : usize,
pub size_z : usize,
pub grid : Vec<MaterialPoint<T>>,
}
impl<T : Real + SupersetOf<f32>> VoxelMaterialGrid3<T>{ //TODO get,set by `t` (precalculated array offset)
pub fn vertices_x(&self) -> usize {self.size_x + 1}
pub fn vertices_y(&self) -> usize {self.size_y + 1}
pub fn vertices_z(&self) -> usize {self.size_z + 1}
pub fn new(a : T, size_x : usize, size_y : usize, size_z : usize) -> VoxelMaterialGrid3<T>{
let grid = vec![MaterialPoint{density : convert(0.0), material : 0};(size_x + 1) * (size_y + 1) * (size_z + 1)];
VoxelMaterialGrid3{a,size_x, size_y, size_z, grid}
}
pub fn get(&self, x : usize, y : usize, z : usize) -> T{
self.grid[z * self.vertices_y() * self.vertices_x() + y * self.vertices_x() + x].density
}
pub fn get_material(&self, x : usize, y : usize, z : usize) -> u32{
self.grid[z * self.vertices_y() * self.vertices_x() + y * self.vertices_x() + x].material
}
pub fn set(&mut self, x : usize, y : usize, z : usize, value : MaterialPoint<T>){
let vx = self.vertices_x();
let vy = self.vertices_y();
self.grid[z * vy * vx + y * vx + x] = value;
}
pub fn get_point(&self, x : usize, y : usize, z : usize) -> Vector3<T>{
Vector3::new(self.a * convert::<f32, T>(x as f32), self.a * convert::<f32, T>(y as f32), self.a * convert::<f32, T>(z as f32))
}
//bounding box of the cube
pub fn square3(&self, x : usize, y : usize, z : usize) -> Square3<T>{
Square3{center : Vector3::new(convert::<f32,T>(x as f32 + 0.5) * self.a, convert::<f32,T>(y as f32 + 0.5) * self.a, convert::<f32,T>(z as f32 + 0.5) * self.a), extent: self.a / convert(2.0)}
}
}
fn calc_qef(point : &Vector3<f32>, planes : &Vec<Plane<f32>>) -> f32{
let mut qef : f32 = 0.0;
for plane in planes{
let dist_signed = plane.normal.dot(&(point - plane.point));
qef += dist_signed * dist_signed;
}
qef
}
fn const_sign(a : u32, b : u32) -> bool {
if a == 0 {b == 0} else {b != 0}
}
fn sample_qef_brute(square : Square3<f32>, n : usize, planes : &Vec<Plane<f32>>) -> Vector3<f32> {
let ext = Vector3::new(square.extent, square.extent, square.extent);
let min = square.center - ext;
let mut best_qef = std::f32::MAX;
let mut best_point = min;
for i in 0..n{
for j in 0..n{
for k in 0..n{
let point = min + Vector3::new(ext.x * (2.0 * (i as f32) + 1.0) / (n as f32),
ext.y * (2.0 * (j as f32) + 1.0) / (n as f32),
ext.z * (2.0 * (k as f32) + 1.0) / (n as f32));
let qef = calc_qef(&point, &planes);
if qef < best_qef{
best_qef = qef;
best_point = point;
}
}
}
}
best_point
}
//in the feature density functions will not be present at all times (as the world can be saved to disk, generator-density function is not saved)
//so the algorithm should use some interpolation methods assuming the surface is smooth(does not change too much within one cube of the grid)
//interpolation can operate on 8 corner vertices of the cube
//TODO or maybe save generator to disk ??, in case of random(presudo-random) generator - its seed can be saved
fn sample_intersection_brute(line : Line3<f32>, n : usize, f : &DenMatFn3<f32>) -> Vector3<f32>{
let ext = line.end - line.start;
let norm = ext.norm();
let dir = ext / norm;
let mut best = std::f32::MAX;
let mut best_point : Option<Vector3<f32>> = None;
for i in 0..n {
let point = line.start + ext * ( i as f32 + 0.5) / n as f32;
let den = f(point).density.abs();
if den < best{
best = den;
best_point = Some(point);
}
}
best_point.unwrap()
}
//why haven't I come up with this one at the start ? :)
pub fn sample_normal(point : &Vector3<f32>, eps : f32, f : &DenMatFn3<f32>) -> Vector3<f32>{
Vector3::new( f(Vector3::new(point.x + eps, point.y, point.z)).density - f(Vector3::new(point.x - eps, point.y, point.z)).density,
f(Vector3::new(point.x, point.y + eps, point.z)).density - f(Vector3::new(point.x, point.y - eps, point.z)).density,
f(Vector3::new(point.x, point.y, point.z + eps)).density - f(Vector3::new(point.x, point.y, point.z - eps)).density ).normalize()
}
//voxel grid is an array like structure (in the feature it should be upgraded to an octree) that contains density information at each vertex of each cube of the grid
//feature is a vertex that may or may not be calculated for each cube of the grid. It is calculated for each cube that exhibits a sign change(this means that the cube
// intersects the surface) and not calculated otherwise
fn calc_feature(vg : &VoxelMaterialGrid3<f32>, x : usize, y : usize, z : usize,
f : &DenMatFn3<f32>, accuracy : usize, contour_data : &mut ContourData, debug_render : &mut RendererVertFragDef) -> Option<Vector3<f32>>{
//let epsilon = vg.a / accuracy as f32;
// let p00 = vg.get(x, y, z);
// let p01 = vg.get(x + 1, y, z);
// let p02 = vg.get(x, y + 1, z);
// let p03 = vg.get(x + 1, y + 1, z);
// let p10 = vg.get(x, y, z + 1);
// let p11 = vg.get(x + 1, y, z + 1);
// let p12 = vg.get(x, y + 1, z + 1);
// let p13 = vg.get(x + 1, y + 1, z + 1);
let m00 = vg.get_material(x, y, z);
let m01 = vg.get_material(x + 1, y, z);
let m02 = vg.get_material(x, y + 1, z);
let m03 = vg.get_material(x + 1, y + 1, z);
let m10 = vg.get_material(x, y, z + 1);
let m11 = vg.get_material(x + 1, y, z + 1);
let m12 = vg.get_material(x, y + 1, z + 1);
let m13 = vg.get_material(x + 1, y + 1, z + 1);
let v00 = vg.get_point(x, y, z);
let v01 = vg.get_point(x + 1, y, z);
let v02 = vg.get_point(x, y + 1, z);
let v03 = vg.get_point(x + 1, y + 1, z);
let v10 = vg.get_point(x,y, z + 1);
let v11 = vg.get_point(x + 1, y, z + 1);
let v12 = vg.get_point(x, y + 1, z + 1);
let v13 = vg.get_point(x + 1, y + 1, z + 1);
let mut edge_info = 0;
if !const_sign(m00, m01){edge_info |= 1;}
if !const_sign(m01, m03){edge_info |= 2;}
if !const_sign(m03, m02){edge_info |= 4;} //z
if !const_sign(m02, m00){edge_info |= 8;}
if !const_sign(m10, m11){edge_info |= 16;}
if !const_sign(m11, m13){edge_info |= 32;} //z + 1
if !const_sign(m13, m12){edge_info |= 64;}
if !const_sign(m12, m10){edge_info |= 128;}
if !const_sign(m00, m10){edge_info |= 256;}
if !const_sign(m01, m11){edge_info |= 512;}
if !const_sign(m02, m12){edge_info |= 1024;} //edges in between of 2 z-levels
if !const_sign(m03, m13){edge_info |= 2048;}
let rad_for_normal = vg.a / 100.0; //TODO will not work if vg.a is too small (f32 precision)
if edge_info > 0{
//let mut normals = Vec::<f32>::new();
//let mut intersections = Vec::<f32>::new();
let mut planes = Vec::new();
{
let mut worker = |edge_id : usize, v_a : Vector3<f32>, v_b : Vector3<f32>|{//goes through each edge of the cube
if (edge_info & edge_id) > 0{
let ip = sample_intersection_brute(Line3{start : v_a, end : v_b}, accuracy, f);//intersecion point
//let full = if p_a <= 0.0 {v_a} else {v_b};
//let normal = sample_normal(&Sphere{center : ip, rad : rad_for_normal}, accuracy, f);
let normal = sample_normal(&ip, rad_for_normal, f);
//intersections.push(ip.x);
//intersections.push(ip.y);
//intersections.push(ip.z);
//normals.push(normal.x);
//normals.push(normal.y);
//normals.push(normal.z);
planes.push(Plane{point : ip, normal});
//calculate feature vertices of 3 other cubes containing this edge then create a quad from maximum of 4 those feature vertices.
//this is done in make_contour
}
};
worker(1, v00, v01);
worker(2, v01, v03);
worker(4, v03, v02);
worker(8, v02, v00);
worker(16, v10, v11);
worker(32, v11, v13);
worker(64, v13, v12);
worker(128, v12, v10);
worker(256, v00, v10);
worker(512, v01, v11);
worker(1024, v02, v12);
worker(2048, v03, v13);
}
let normals : Vec<f32> = planes.iter().flat_map(|x| x.normal.as_slice().to_owned()).collect();
let mut Abs = Vec::with_capacity(normals.len() * 4 / 3);
//let intersections : Vec<f32> = planes.iter().flat_map(|x| x.point.as_slice().to_owned()).collect();
let product : Vec<f32> = planes.iter().map(|x| x.normal.dot(&x.point)).collect();
for i in 0..product.len(){
Abs.push(normals[3 * i]);
Abs.push(normals[3 * i + 1]);
Abs.push(normals[3 * i + 2]);
Abs.push(product[i]);
}
// let mut product = Vec::with_capacity(normals.len());
// for i in 0..normals.len()/3{
// product.push(normals[3 * i] * intersections[3 * i] + normals[3 * i + 1] * intersections[3 * i + 1] + normals[3 * i + 2] * intersections[3 * i + 2]);
// }
//let feature_vertex = Vector3::new(0.0,0.0,0.0);//sample_qef_brute(vg.square3(x,y,z), accuracy, &normals.zip);//TODO
let A = DMatrix::from_row_slice(normals.len() / 3, 3, normals.as_slice());
let ATA = (&A).transpose() * &A;
let b = DMatrix::from_row_slice(product.len(), 1, product.as_slice());
let ATb = (&A).transpose() * &b;
let Ab = DMatrix::from_row_slice(planes.len(), 4, Abs.as_slice());
let bTb = (&b).transpose() * (&b);
let mag = bTb.norm();
// let qr1 = Ab.qr();
// let R = qr1.r(); //transpose ?
// let mut A1 = R.slice((0,0), (3,3));
// let mut b1 = R.slice((0,3), (3,1));
// let mut r = unsafe{R.get_unchecked(3,3)};
// let svd = A1.svd(true,true);
// let sol = svd.solve(&b1,0.00001);
let qr = ATA.qr();
let solved = qr.solve(&ATb);
//println!("{:?} {}", normals.as_slice(), A);
let mut feature_vertex = match solved{
Some(sol) => Vector3::new(sol[0], sol[1], sol[2]),
None => sample_qef_brute(vg.square3(x, y, z), accuracy, &planes),
};
if !point3_inside_square3_inclusive(&feature_vertex, &vg.square3(x, y, z)){
// println!("bad val {} {} {}", x,y,z);
// add_square3_bounds_color(debug_render, vg.square3(x, y, z), Vector3::new(1.0,1.0,1.0)); //cube
// add_square3_bounds_color(debug_render, Square3{center : feature_vertex, extent : 0.006}, Vector3::new(0.0,1.0,1.0)); //feature
// add_line3_color(debug_render, Line3{start : vg.square3(x, y, z).center, end : feature_vertex}, Vector3::new(0.0,0.0,0.0)); //to feature
// for plane in &planes{
// add_square3_bounds_color(debug_render, Square3{center : plane.point, extent : 0.004}, Vector3::new(0.0,1.0,0.0));
// add_line3_color(debug_render, Line3{start : plane.point, end : plane.point + plane.normal * 0.05}, Vector3::new(1.0,1.0,0.0));
// }
feature_vertex = sample_qef_brute(vg.square3(x, y, z), accuracy, &planes);
}
let t = z * vg.size_y * vg.size_x + y * vg.size_x + x;
contour_data.features[t] = Some(feature_vertex);
//contour_data.normals[t] = Some(sample_normal(&Sphere{center : feature_vertex, rad : rad_for_normal}, accuracy, f));
contour_data.normals[t] = Some(sample_normal(&feature_vertex, vg.a / 100.0, f));//TODO it should not sample density function anymore
//see https://github.com/Lin20/isosurface/blob/57b5c5e16e9de321e3f4a919d2f14c85811a28e7/Isosurface/Isosurface/UniformDualContouring/DC3D.cs#L143
contour_data.materials[t] = f(feature_vertex).material;
Some(feature_vertex)
}else{
None
}
}
//TODO debug_renderer is for debug only
pub fn make_contour(vg : &VoxelMaterialGrid3<f32>, f : &DenMatFn3<f32>, accuracy : usize, debug_renderer : &mut RendererVertFragDef) -> ContourData{
//TODO inefficient Vec::new() creation vvv
let mut contour_data = ContourData{lines : Vec::new(),
triangles : Vec::new(),
triangle_normals : Vec::new(),
triangle_colors : Vec::new(),
features : vec![None;vg.size_x * vg.size_y * vg.size_z],
normals : vec![None;vg.size_x * vg.size_y * vg.size_z],
materials : vec![0;vg.size_x * vg.size_y * vg.size_z]};
let mut cache_already_calculated = vec![false;vg.size_x * vg.size_y * vg.size_z]; //this cache is used to mark cubes that have already been calculated for feature vertex
{
//&mut contour_data, cache_already_calculated
let mut cached_make = |x: usize, y: usize, z : usize, contour_data : &mut ContourData| -> Option<Vector3<f32>>{
let t = z * vg.size_y * vg.size_x + y * vg.size_x + x;
if cache_already_calculated[t] {
contour_data.features[t]
}else{
cache_already_calculated[t] = true;
calc_feature(&vg, x, y, z, f, accuracy, contour_data, debug_renderer)
}
};
for z in 0..vg.size_z{
for y in 0..vg.size_y {
for x in 0..vg.size_x {
//let p00 = vg.get(x, y, z);
//let p01 = vg.get(x + 1, y, z);
//let p02 = vg.get(x, y + 1, z);
//let p03 = vg.get(x + 1, y + 1, z);
let m03 = vg.get_material(x + 1, y + 1, z);
//let p10 = vg.get(x, y, z + 1);
//let p11 = vg.get(x + 1, y, z + 1);
//let p12 = vg.get(x, y + 1, z + 1);
//let p13 = vg.get(x + 1, y + 1, z + 1);
let m11 = vg.get_material(x + 1, y, z + 1);
let m12 = vg.get_material(x, y + 1, z + 1);
let m13 = vg.get_material(x + 1, y + 1, z + 1);
/*let v00 = vg.get_point(x, y, z);
let v01 = vg.get_point(x + 1, y, z);
let v02 = vg.get_point(x, y + 1, z);
let v03 = vg.get_point(x + 1, y + 1, z);
let v10 = vg.get_point(x,y, z + 1);
let v11 = vg.get_point(x + 1, y, z + 1);
let v12 = vg.get_point(x, y + 1, z + 1);
let v13 = vg.get_point(x + 1, y + 1, z + 1);*/
fn color_map(edge0 : u32, edge1 : u32) -> Vector3<f32>{
match edge0{
1 => Vector3::new(1.0, 0.0, 0.0),
2 => Vector3::new(0.0, 1.0, 0.0),
_ => {
match edge1{
1 => Vector3::new(1.0, 0.0, 0.0),
2 => Vector3::new(0.0, 1.0, 0.0),
_ => Vector3::new(0.0,0.0,0.0),
}
},
}
}
let possible_feature_vertex = cached_make(x, y, z, &mut contour_data);
match possible_feature_vertex{
None => (),
Some(f0) => {
let t = z * vg.size_y * vg.size_x + y * vg.size_x + x;
let normal = contour_data.normals[t].unwrap();
//TODO incorrect normals in some places
if !const_sign(m03, m13){
let f1 = cached_make(x + 1, y, z, &mut contour_data).unwrap();
let f2 = cached_make(x + 1, y + 1, z, &mut contour_data).unwrap();
let f3 = cached_make(x, y + 1, z, &mut contour_data).unwrap();
//f1 && f2 && f3 all should be non-empty, as they all exhibit a sign change at least on their common edge
//this is needed to calculate the direction of the resulting quad correctly
let dir = (f2 - f0).cross(&(f3 - f0)).normalize();
contour_data.triangle_colors.push(color_map(m03, m13));
if dir.dot(&normal) > 0.0{ //should not be zero at any time
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f3});
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f1, p3 : f2});
//add_line3_color(debug_renderer, Line3{start : f0, end : f0 + dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
//TODO debug
/* if (dir.dot(&debug_real_normal) <= 0.0) {
println!("bad normal at {} {} {} {}", 1, x, y, z);
} */
contour_data.triangle_normals.push(dir); //TODO inefficient
}else{
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f3, p3 : f2});
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f1});
//add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
/* if (-dir.dot(&debug_real_normal) <= 0.0) {
add_square3_bounds_color(debug_renderer, vg.square3(x, y, z), Vector3::new(1.0, 0.0, 0.0));
add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
add_line3_color(debug_renderer, Line3{start : f0, end : f0 - normal.normalize()}, Vector3::new(0.0, 0.0, 0.0));
println!("bad normal at {} {}", 2, -dir.dot(&debug_real_normal));
} */
contour_data.triangle_normals.push(-dir);
}
}
if !const_sign(m12, m13){
let f1 = cached_make(x, y, z + 1, &mut contour_data).unwrap();
let f2 = cached_make(x, y + 1, z + 1, &mut contour_data).unwrap();
let f3 = cached_make(x, y + 1, z, &mut contour_data).unwrap();
//f1 && f2 && f3 all should be non-empty, as they all exhibit a sign change at least on their common edge
contour_data.triangle_colors.push(color_map(m12, m13));
//this is needed to calculate the direction of the resulting quad correctly
let dir = (f2 - f0).cross(&(f3 - f0)).normalize();
if dir.dot(&normal) > 0.0{ //should not be zero at any time
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f3});
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f1, p3 : f2});
//add_line3_color(debug_renderer, Line3{start : f0, end : f0 + dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
/* if (dir.dot(&debug_real_normal) <= 0.0) {
println!("bad normal at {} {} {} {}", 3, x, y, z);
} */
contour_data.triangle_normals.push(dir);
}else{
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f3, p3 : f2});
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f1});
//add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
/* if (-dir.dot(&debug_real_normal) <= 0.0) {
add_square3_bounds_color(debug_renderer, vg.square3(x, y, z), Vector3::new(1.0, 0.0, 0.0));
add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
add_line3_color(debug_renderer, Line3{start : f0, end : f0 - normal.normalize()}, Vector3::new(0.0, 0.0, 0.0));
println!("bad normal at {} {}", 4, -dir.dot(&debug_real_normal));
} */
contour_data.triangle_normals.push(-dir);
}
}
if !const_sign(m11, m13){
let f1 = cached_make(x + 1, y, z, &mut contour_data).unwrap();
let f2 = cached_make(x + 1, y, z + 1, &mut contour_data).unwrap();
let f3 = cached_make(x, y, z + 1, &mut contour_data).unwrap();
//f1 && f2 && f3 all should be non-empty, as they all exhibit a sign change at least on their common edge
contour_data.triangle_colors.push(color_map(m11, m13));
//this is needed to calculate the direction of the resulting quad correctly
let dir = (f2 - f0).cross(&(f3 - f0)).normalize();
if dir.dot(&normal) > 0.0{ //should not be zero at any time
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f3});
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f1, p3 : f2});
//add_line3_color(debug_renderer, Line3{start : f0, end : f0 + dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
/* if (dir.dot(&debug_real_normal) <= 0.0) {
println!("bad normal at {} {} {} {}", 5, x, y, z);
} */
contour_data.triangle_normals.push(dir);
} else{
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f3, p3 : f2});
contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f1});
//add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
/* if (-dir.dot(&debug_real_normal) <= 0.0) {
add_square3_bounds_color(debug_renderer, vg.square3(x, y, z), Vector3::new(1.0, 0.0, 0.0));
add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0));
println!("bad normal at {} {} {} {}", 6, x, y, z);
} */
contour_data.triangle_normals.push(-dir);
}
}
},
}
}
}
}
}
contour_data
}
pub fn fill_in_grid(vg : &mut VoxelMaterialGrid3<f32>, f : &DenMatFn3<f32>, offset : Vector3<f32>){
for z in 0..vg.size_z + 1 {
for y in 0..vg.size_y + 1{
for x in 0..vg.size_x + 1 {
let vx = vg.vertices_x();
let vy = vg.vertices_y();
vg.grid[z * vy * vx + y * vx + x] = f(offset + Vector3::new(vg.a * (x as f32), vg.a * (y as f32), vg.a * (z as f32)));
}
}
}
}
pub struct ContourData{ // + hermite data ? (exact points of intersection of the surface with each edge that exhibits a sign change + normals for each of those points)
pub lines : Vec<Line3<f32>>,
pub triangles : Vec<Triangle3<f32>>,
pub triangle_normals : Vec<Vector3<f32>>,
pub triangle_colors : Vec<Vector3<f32>>,
pub features : Vec<Option<Vector3<f32>>>,
pub normals : Vec<Option<Vector3<f32>>>, //normal to the surface calculated at feature vertex
pub materials : Vec<u32>,
} |
use crate::app::Args;
use anyhow::{Context, Result};
use clap::Parser;
use maple_core::paths::AbsPathBuf;
use maple_core::tools::ctags::{buffer_tags_lines, current_context_tag};
/// Prints the tags for a specific file.
#[derive(Parser, Debug, Clone)]
pub struct BufferTags {
/// Show the nearest function/method to a specific line.
#[clap(long)]
current_context: Option<usize>,
/// Use the raw output format even json output is supported, for testing purpose.
#[clap(long)]
force_raw: bool,
#[clap(long)]
file: AbsPathBuf,
}
impl BufferTags {
pub fn run(&self, _args: Args) -> Result<()> {
if let Some(at) = self.current_context {
let context_tag = current_context_tag(self.file.as_path(), at)
.context("Error at finding the context tag info")?;
println!("Context: {context_tag:?}");
return Ok(());
}
let lines = buffer_tags_lines(self.file.as_ref(), self.force_raw)?;
for line in lines {
println!("{line}");
}
Ok(())
}
}
|
use libsodium_sys::{
crypto_box_SEEDBYTES, crypto_hash_sha256_BYTES, crypto_pwhash_SALTBYTES,
crypto_secretstream_xchacha20poly1305_ABYTES,
};
pub use crate::object::cached_source::CachedObjectSource;
pub use crate::object::decrypt_reader::DecryptReader;
pub use crate::object::encrypt_writer::EncrypterWriter;
pub use crate::object::finish::Finish;
pub use crate::object::fs_source::FsObjectSource;
pub use crate::object::google_storage_source::GoogleStorageObjectSource;
pub use crate::object::quoco_reader::QuocoReader;
pub use crate::object::quoco_writer::QuocoWriter;
pub use crate::object::remote_source::{RemoteSource, RemoteSourceConfig};
pub use crate::object::source::BoxedObjectSource;
pub use crate::object::source::ObjectSource;
mod cached_source;
mod decrypt_reader;
mod encrypt_writer;
mod finish;
mod fs_source;
mod google_storage_source;
mod quoco_reader;
mod quoco_writer;
mod remote_source;
mod source;
pub const CHUNK_LENGTH: usize = 4096;
const ENCRYPTED_CHUNK_LENGTH: usize =
CHUNK_LENGTH + crypto_secretstream_xchacha20poly1305_ABYTES as usize;
pub const KEY_LENGTH: usize = crypto_box_SEEDBYTES as usize;
// Currently data is compressed and encrypted in memory, so we set an arbitrary max file size of 4 GiB.
// TODO(vinhowe): Figure out how to use less memory securely
pub const MAX_DATA_LENGTH: usize = 1024 * 1024 * 1024 * 4;
pub const MAX_NAME_LENGTH: usize = 512;
pub const SALT_LENGTH: usize = crypto_pwhash_SALTBYTES as usize;
pub const HASH_LENGTH: usize = crypto_hash_sha256_BYTES as usize;
pub const UUID_LENGTH: usize = 16;
pub type ObjectId = [u8; UUID_LENGTH];
pub type ObjectHash = [u8; HASH_LENGTH];
pub type Key = [u8; KEY_LENGTH];
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[cfg(feature = "Win32_System_WinRT_Graphics_Capture")]
pub mod Capture;
#[cfg(feature = "Win32_System_WinRT_Graphics_Direct2D")]
pub mod Direct2D;
#[cfg(feature = "Win32_System_WinRT_Graphics_Imaging")]
pub mod Imaging;
|
use std::{env, path::Path};
fn main() {
let mut opts = built::Options::default();
opts
.set_cfg(false)
.set_compiler(false)
.set_dependencies(false)
.set_features(false)
.set_ci(true)
.set_env(true)
.set_git(true)
.set_time(true);
let src = env::var("CARGO_MANIFEST_DIR").unwrap();
let dst = Path::new(&env::var("OUT_DIR").unwrap()).join("built.rs");
built::write_built_file_with_opts(&opts, src.as_ref(), &dst)
.expect("Failed to acquire build-time information");
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type IWindowsMediaLibrarySharingDevice = *mut ::core::ffi::c_void;
pub type IWindowsMediaLibrarySharingDeviceProperties = *mut ::core::ffi::c_void;
pub type IWindowsMediaLibrarySharingDeviceProperty = *mut ::core::ffi::c_void;
pub type IWindowsMediaLibrarySharingDevices = *mut ::core::ffi::c_void;
pub type IWindowsMediaLibrarySharingServices = *mut ::core::ffi::c_void;
pub type WindowsMediaLibrarySharingDeviceAuthorizationStatus = i32;
pub const DEVICE_AUTHORIZATION_UNKNOWN: WindowsMediaLibrarySharingDeviceAuthorizationStatus = 0i32;
pub const DEVICE_AUTHORIZATION_ALLOWED: WindowsMediaLibrarySharingDeviceAuthorizationStatus = 1i32;
pub const DEVICE_AUTHORIZATION_DENIED: WindowsMediaLibrarySharingDeviceAuthorizationStatus = 2i32;
pub const WindowsMediaLibrarySharingServices: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2908232448,
data2: 31588,
data3: 20057,
data4: [163, 141, 210, 197, 191, 81, 221, 179],
};
|
use libwebm::mkvmuxer::writer::MkvWriter;
use std::fs::File;
use std::io;
use std::io::{Error, ErrorKind, Read};
use libwebm::mkvmuxer::util;
// constants for muxer and parser tests
const kAppString: &'static str = "mkvmuxer_unit_tests";
const kOpusCodecId: &'static str = "A_OPUS";
const kVorbisCodecId: &'static str = "A_VORBIS";
const kAudioTrackNumber: i32 = 2;
const kBitDepth: i32 = 2;
const kChannels: i32 = 2;
const kDuration: f64 = 2.345;
const kFrameLength: i32 = 10;
const kHeight: i32 = 180;
const kInvalidTrackNumber: i32 = 100;
const kOpusCodecDelay: u64 = 6500000;
const kOpusPrivateDataSizeMinimum: usize = 19;
const kOpusSeekPreroll: u64 = 80000000;
const kMetadataCodecId: &'static str = "D_WEBVTT/METADATA";
const kMetadataTrackNumber: i32 = 3;
const kMetadataTrackType: i32 = 0x21;
const kSampleRate: i32 = 30;
const kTimeCodeScale: i32 = 1000;
const kTrackName: &'static str = "unit_test";
const kVP8CodecId: &'static str = "V_VP8";
const kVP9CodecId: &'static str = "V_VP9";
const kVideoFrameRate: f64 = 0.5;
const kVideoTrackNumber: i32 = 1;
const kWidth: i32 = 320;
fn GetTempFileName() -> String {
let temp_dir = std::env::temp_dir().to_str().unwrap().to_string();
temp_dir + "/libwebm_temp." + &util::MakeUID().to_string()
}
fn GetTestDataDir() -> String {
let test_data_path = std::env::var("LIBWEBM_TEST_DATA_PATH");
match test_data_path {
Ok(path) => path,
Err(err) => ".".to_string(),
}
}
fn GetTestFilePath(name: &str) -> String {
let libwebm_testdata_dir = GetTestDataDir();
libwebm_testdata_dir + "/" + name
}
fn CompareFiles(file1: &str, file2: &str) -> io::Result<()> {
let mut f1 = File::open(file1)?;
let mut f2 = File::open(file2)?;
let block_size = 4096;
let mut buf1 = vec![0u8; block_size];
let mut buf2 = vec![0u8; block_size];
loop {
match (f1.read(&mut buf1), f2.read(&mut buf2)) {
(Ok(n1), Ok(n2)) => {
if n1 != n2 {
return Err(Error::new(ErrorKind::Other, "f1 and f2 not same size"));
} else if buf1 != buf2 {
return Err(Error::new(ErrorKind::Other, "f1 and f2 not same content"));
} else if n1 < block_size {
return Ok(());
}
}
_ => {
return Err(Error::new(
ErrorKind::Other,
"f1 or f2 eof but another not eof",
));
}
}
}
}
struct MuxerTest {
writer_: MkvWriter,
filename_: String,
//segment_: Segment,
dummy_data_: Vec<u8>,//[u8; ],
}
impl MuxerTest{
fn new() -> MuxerTest {
let temp_file = GetTempFileName();
let file = File::open(temp_file.clone()).unwrap();
MuxerTest{
writer_: MkvWriter::new(file),
filename_: temp_file,
dummy_data_: vec![0; kFrameLength as usize],
}
}
fn get_filename(&self) ->&str {
&self.filename_
}
} |
use std::ops::{self, RangeBounds};
use anyhow::{Context as _, Result};
use cfg_if::cfg_if;
use js_sys::{Uint16Array, Uint32Array};
use web_sys::{WebGlBuffer, WebGlRenderingContext};
use crate::{resolve_range, Buffer, BufferDataUsage, Context, Program, RenderPrimitiveType};
/// Stores the indices of a buffer.
pub struct Indices {
buffer: WebGlBuffer,
len: usize,
ty: u32,
}
impl Indices {
/// Allocates a buffer to store indices for a buffer of up to 65536 vertices.
pub fn new(context: &Context, indices: &[u16], usage: BufferDataUsage) -> Result<Self> {
let gl = &context.native;
let buffer = gl
.create_buffer()
.context("Failed to allocate WebGL buffer")?;
gl.bind_buffer(WebGlRenderingContext::ELEMENT_ARRAY_BUFFER, Some(&buffer));
let array = Uint16Array::from(indices);
gl.buffer_data_with_array_buffer_view(
WebGlRenderingContext::ELEMENT_ARRAY_BUFFER,
&array,
usage.to_const(),
);
Ok(Self {
buffer,
len: indices.len(),
ty: WebGlRenderingContext::UNSIGNED_SHORT,
})
}
/// Allocates a buffer to store indices that can exceed 65536 vertices.
///
/// This always fails on browsers that do not support the
/// [`OES_element_index_uint`](https://developer.mozilla.org/en-US/docs/Web/API/OES_element_index_uint) extension.
pub fn new_with_usize(
context: &Context,
indices: &[usize],
usage: BufferDataUsage,
) -> Result<Self> {
let gl = &context.native;
gl.get_extension("OES_element_index_uint")
.ok()
.flatten()
.context("Failed to enable extension for u32 element index")?;
let array;
cfg_if! {
if #[cfg(target_pointer_width = "32")] {
// In wasm32-unknown-unknown, usize == u32.
// Let's try to optimize this majority use case.
let indices = unsafe {
std::slice::from_raw_parts(indices.as_ptr() as *const u32, indices.len())
};
array = Uint32Array::from(indices);
} else {
use std::convert::TryFrom;
let indices: Vec<u32> = indices.iter().map(|&v| u32::try_from(v).expect("Index is unreasonably large")).collect();
array = Uint32Array::from(&indices[..]);
}
};
let buffer = gl
.create_buffer()
.context("Failed ot allocate WebGL buffer")?;
gl.bind_buffer(WebGlRenderingContext::ELEMENT_ARRAY_BUFFER, Some(&buffer));
gl.buffer_data_with_array_buffer_view(
WebGlRenderingContext::ELEMENT_ARRAY_BUFFER,
&array,
usage.to_const(),
);
Ok(Self {
buffer,
len: indices.len(),
ty: WebGlRenderingContext::UNSIGNED_INT,
})
}
/// Calls the draw operation on a
pub(crate) fn draw(
&self,
mode: RenderPrimitiveType,
context: &Context,
items: impl RangeBounds<usize>,
) {
let gl = &context.native;
let (start, end) = resolve_range(items, self.len);
gl.bind_buffer(
WebGlRenderingContext::ELEMENT_ARRAY_BUFFER,
Some(&self.buffer),
);
gl.draw_elements_with_i32(mode.to_const(), end - start, self.ty, start);
}
/// Creates a subindex that implements [`AbstractIndices`](AbstractIndices).
pub fn subindex<B: RangeBounds<usize> + Copy>(&self, bounds: B) -> SubIndices<'_, B> {
SubIndices {
indices: self,
bounds,
}
}
}
/// A contiguous subsequence of an [`Indices`][Indices] buffer,
/// used to implement [`AbstractIndices`][AbstractIndices].
pub struct SubIndices<'t, B: RangeBounds<usize> + Copy> {
indices: &'t Indices,
bounds: B,
}
/// Types implementing this trait can be used to specify which vertices of a buffer to draw.
pub trait AbstractIndices {
/// Draws the vertices in `buffer` indexed by `self`.
///
/// Call [`Program::use_program`][Program::use_program] before calling this method.
///
/// This method does not reassign uniforms.
/// Use the `with_uniforms` method (derived by the [`Program`][super::Program] macro)
/// to draw with uniforms specified.
fn draw<P: Program>(
&self,
mode: RenderPrimitiveType,
context: &Context,
program: &P,
buffer: &Buffer<P::AttrStruct>,
);
}
impl AbstractIndices for Indices {
fn draw<P: Program>(
&self,
mode: RenderPrimitiveType,
context: &Context,
program: &P,
buffer: &Buffer<P::AttrStruct>,
) {
program.apply_attrs(context, buffer);
self.draw(mode, context, ..);
}
}
impl<'t, B: RangeBounds<usize> + Copy> AbstractIndices for SubIndices<'t, B> {
fn draw<P: Program>(
&self,
mode: RenderPrimitiveType,
context: &Context,
program: &P,
buffer: &Buffer<P::AttrStruct>,
) {
program.apply_attrs(context, buffer);
self.indices.draw(mode, context, self.bounds);
}
}
macro_rules! impl_bounds {
($ty:ty) => {
impl AbstractIndices for $ty {
fn draw<P: Program>(
&self,
mode: RenderPrimitiveType,
context: &Context,
program: &P,
buffer: &Buffer<P::AttrStruct>,
) {
program.apply_attrs(context, buffer);
let (start, end) = resolve_range(self.clone(), buffer.count);
context.native.draw_arrays(mode.to_const(), start, end);
}
}
};
}
impl_bounds!(ops::Range<usize>);
impl_bounds!(ops::RangeFrom<usize>);
impl_bounds!(ops::RangeFull);
impl_bounds!(ops::RangeInclusive<usize>);
impl_bounds!(ops::RangeTo<usize>);
impl_bounds!(ops::RangeToInclusive<usize>);
impl<'t, T: AbstractIndices> AbstractIndices for &'t T {
fn draw<P: Program>(
&self,
mode: RenderPrimitiveType,
context: &Context,
program: &P,
buffer: &Buffer<P::AttrStruct>,
) {
(&**self).draw(mode, context, program, buffer);
}
}
|
use test_implement::*;
use windows::core::*;
use Windows::Foundation::Collections::*;
#[implement(
Windows::Foundation::Collections::IVectorView<i32>,
Windows::Foundation::Collections::IIterable<i32>,
)]
struct Thing();
#[allow(non_snake_case)]
impl Thing {
pub fn GetAt(&self, index: u32) -> Result<i32> {
Ok(index as _)
}
pub fn Size(&self) -> Result<u32> {
Ok(123)
}
pub fn IndexOf(&self, value: i32, index: &mut u32) -> Result<bool> {
*index = value as _;
Ok(true)
}
pub fn GetMany(&self, _startindex: u32, _items: &mut [i32]) -> Result<u32> {
panic!();
}
fn First(&self) -> Result<IIterator<i32>> {
panic!();
}
}
#[test]
fn test_implement() -> Result<()> {
let v: IVectorView<i32> = Thing().into();
assert_eq!(012, v.GetAt(012)?);
assert_eq!(123, v.Size()?);
let mut index = 0;
assert_eq!(true, v.IndexOf(456, &mut index)?);
assert_eq!(456, index);
Ok(())
}
|
extern crate rand;
extern crate sfml;
use crate::app::*;
use rand::*;
use sfml::graphics::*;
use sfml::system::*;
pub struct SnowCtx<'a> {
snow: Vec<CircleShape<'a>>,
initialized: bool,
counter: i32,
offsets: Vec<i32>,
}
impl SnowCtx<'_> {
pub fn new() -> SnowCtx<'static> {
SnowCtx {
snow: Vec::new(),
offsets: Vec::new(),
initialized: false,
counter: 0,
}
}
}
pub fn update_snow(ctx: &mut SnowCtx, delta: f32) {
ctx.counter += 1;
if !ctx.initialized {
init_snow(ctx);
}
for i in 0..ctx.snow.len() {
let mut flake = ctx.snow.get_mut(i).unwrap();
let iter = ctx.counter + ctx.offsets.get(i).unwrap();
let sin = f32::sin(iter as f32 * 5. * delta) * 20.;
flake.move_(((20. + sin) * delta, 50. * delta));
clamp_position(&mut flake);
}
}
pub fn draw_snow(ctx: &mut SnowCtx, window: &mut RenderWindow) {
for flake in &ctx.snow {
window.draw(flake);
}
}
fn init_snow(ctx: &mut SnowCtx) {
for _i in 1..100 {
ctx.snow.push(CircleShape::new(1.5, 5));
let flake = ctx.snow.last_mut().unwrap();
let pos: Vector2f = Vector2f::new(
(random::<u32>() % WINDOW_WIDTH) as f32,
(random::<u32>() % WINDOW_HEIGHT) as f32,
);
flake.set_position(pos);
flake.set_fill_color(Color::WHITE);
ctx.offsets.push(random());
}
ctx.initialized = true;
}
fn clamp_position(flake: &mut CircleShape) {
if flake.position().x > WINDOW_WIDTH as f32 {
flake.move_((-(WINDOW_WIDTH as f32), 0.));
}
if flake.position().y > WINDOW_HEIGHT as f32 {
flake.move_((0., -(WINDOW_HEIGHT as f32)));
}
}
|
use crate::{
BlockHash, BlockNumber, BlockTimestamp, ClassCommitment, EventCommitment, GasPrice,
SequencerAddress, StarknetVersion, StateCommitment, StateUpdate, StorageCommitment,
TransactionCommitment,
};
use fake::Dummy;
#[derive(Debug, Clone, PartialEq, Eq, Default, Dummy)]
pub struct BlockHeader {
pub hash: BlockHash,
pub parent_hash: BlockHash,
pub number: BlockNumber,
pub timestamp: BlockTimestamp,
pub gas_price: GasPrice,
pub sequencer_address: SequencerAddress,
pub starknet_version: StarknetVersion,
pub class_commitment: ClassCommitment,
pub event_commitment: EventCommitment,
pub state_commitment: StateCommitment,
pub storage_commitment: StorageCommitment,
pub transaction_commitment: TransactionCommitment,
pub transaction_count: usize,
pub event_count: usize,
}
pub struct BlockHeaderBuilder(BlockHeader);
impl BlockHeader {
/// Creates a [builder](BlockHeaderBuilder) with all fields initialized to default values.
pub fn builder() -> BlockHeaderBuilder {
BlockHeaderBuilder(BlockHeader::default())
}
/// Creates a [builder](BlockHeaderBuilder) with an incremented block number and parent hash set to this
/// block's hash.
pub fn child_builder(&self) -> BlockHeaderBuilder {
BlockHeaderBuilder(BlockHeader::default())
.with_number(self.number + 1)
.with_parent_hash(self.hash)
}
/// Creates a [StateUpdate] with the block hash and state commitment fields intialized
/// to match this header.
pub fn init_state_update(&self) -> StateUpdate {
StateUpdate::default()
.with_block_hash(self.hash)
.with_state_commitment(self.state_commitment)
}
}
impl BlockHeaderBuilder {
pub fn with_number(mut self, number: BlockNumber) -> Self {
self.0.number = number;
self
}
pub fn with_parent_hash(mut self, parent_hash: BlockHash) -> Self {
self.0.parent_hash = parent_hash;
self
}
pub fn with_state_commitment(mut self, state_commmitment: StateCommitment) -> Self {
self.0.state_commitment = state_commmitment;
self
}
/// Sets the [StateCommitment] by calculating its value from the current [StorageCommitment] and [ClassCommitment].
pub fn with_calculated_state_commitment(mut self) -> Self {
self.0.state_commitment =
StateCommitment::calculate(self.0.storage_commitment, self.0.class_commitment);
self
}
pub fn with_timestamp(mut self, timestamp: BlockTimestamp) -> Self {
self.0.timestamp = timestamp;
self
}
pub fn with_gas_price(mut self, gas_price: GasPrice) -> Self {
self.0.gas_price = gas_price;
self
}
pub fn with_sequencer_address(mut self, sequencer_address: SequencerAddress) -> Self {
self.0.sequencer_address = sequencer_address;
self
}
pub fn with_transaction_commitment(
mut self,
transaction_commitment: TransactionCommitment,
) -> Self {
self.0.transaction_commitment = transaction_commitment;
self
}
pub fn with_event_commitment(mut self, event_commitment: EventCommitment) -> Self {
self.0.event_commitment = event_commitment;
self
}
pub fn with_storage_commitment(mut self, storage_commitment: StorageCommitment) -> Self {
self.0.storage_commitment = storage_commitment;
self
}
pub fn with_class_commitment(mut self, class_commitment: ClassCommitment) -> Self {
self.0.class_commitment = class_commitment;
self
}
pub fn with_starknet_version(mut self, starknet_version: StarknetVersion) -> Self {
self.0.starknet_version = starknet_version;
self
}
pub fn with_transaction_count(mut self, transaction_count: usize) -> Self {
self.0.transaction_count = transaction_count;
self
}
pub fn with_event_count(mut self, event_count: usize) -> Self {
self.0.event_count = event_count;
self
}
pub fn finalize_with_hash(mut self, hash: BlockHash) -> BlockHeader {
self.0.hash = hash;
self.0
}
}
|
pub trait Collidable<Other: ?Sized> {
/// Returns whether the `Other` is at least partially contained in `self`.
/// This does include the degenerate case of two boundaries touching, if
/// the concept of boundaries applies. Should be reflexive and is assumed
/// so by the library.
fn intersects(self: &Self, col: &Other) -> bool;
}
pub trait CollisionDescribable<Other: ?Sized> {
type CollisionType;
/// Returns the type of collision between two objects. Presuming
/// `CollisionType` isn't `None` but is `Option`, `intersects` should be
/// true. Should be reflexive and is assumed so by the library.
fn get_collision(self: &Self, col: &Other) -> Self::CollisionType;
}
/// Automatically implement `Collidable<Other>` for types implementing trait
/// `CollisionDescribable<Option<Other>>`, with the `intersects` function
/// returning false iff the collision is `None`. Intended for consistency
/// between `CollisionDescribable` and `Collidable`.
impl<CT, Other, T> Collidable<Other> for T
where Other: ?Sized,
T: CollisionDescribable<Other, CollisionType=Option<CT>>
{
#[inline]
fn intersects(self: &Self, col: &Other) -> bool {
self.get_collision(col).is_some()
}
} |
pub use VkSampleCountFlags::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkSampleCountFlags {
VK_SAMPLE_COUNT_1_BIT = 0x0000_0001,
VK_SAMPLE_COUNT_2_BIT = 0x0000_0002,
VK_SAMPLE_COUNT_4_BIT = 0x0000_0004,
VK_SAMPLE_COUNT_8_BIT = 0x0000_0008,
VK_SAMPLE_COUNT_16_BIT = 0x0000_0010,
VK_SAMPLE_COUNT_32_BIT = 0x0000_0020,
VK_SAMPLE_COUNT_64_BIT = 0x0000_0040,
}
use crate::SetupVkFlags;
#[repr(C)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct VkSampleCountFlagBits(u32);
SetupVkFlags!(VkSampleCountFlags, VkSampleCountFlagBits);
impl Default for VkSampleCountFlags {
fn default() -> Self {
VK_SAMPLE_COUNT_1_BIT
}
}
impl Default for VkSampleCountFlagBits {
fn default() -> Self {
VK_SAMPLE_COUNT_1_BIT.into()
}
}
|
// Copyright 2012 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.
#![feature(generic_associated_types)]
//FIXME(#44265): "lifetime parameter not allowed on this type" errors will be addressed in a
// follow-up PR
use std::fmt::Display;
trait StreamingIterator {
type Item<'a>;
// Applying the lifetime parameter `'a` to `Self::Item` inside the trait.
fn next<'a>(&'a self) -> Option<Self::Item<'a>>;
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
}
struct Foo<T: StreamingIterator> {
// Applying a concrete lifetime to the constructor outside the trait.
bar: <T as StreamingIterator>::Item<'static>,
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
}
// Users can bound parameters by the type constructed by that trait's associated type constructor
// of a trait using HRTB. Both type equality bounds and trait bounds of this kind are valid:
//FIXME(sunjay): This next line should parse and be valid
//fn foo<T: for<'a> StreamingIterator<Item<'a>=&'a [i32]>>(iter: T) { /* ... */ }
fn foo<T>(iter: T) where T: StreamingIterator, for<'a> T::Item<'a>: Display { /* ... */ }
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
// Full example of enumerate iterator
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
struct StreamEnumerate<I> {
iter: I,
count: usize,
}
impl<I: StreamingIterator> StreamingIterator for StreamEnumerate<I> {
type Item<'a> = (usize, I::Item<'a>);
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
fn next<'a>(&'a self) -> Option<Self::Item<'a>> {
//~^ ERROR lifetime parameters are not allowed on this type [E0110]
match self.iter.next() {
None => None,
Some(val) => {
let r = Some((self.count, val));
self.count += 1;
r
}
}
}
}
impl<I> StreamEnumerate<I> {
pub fn new(iter: I) -> Self {
StreamEnumerate {
count: 0,
iter: iter,
}
}
}
fn test_stream_enumerate() {
let v = vec!["a", "b", "c"];
let se = StreamEnumerate::new(v.iter());
let a: &str = se.next().unwrap().1;
for (i, s) in se {
println!("{} {}", i, s);
}
println!("{}", a);
}
fn main() {}
|
use ethers::{middleware::gas_escalator::GeometricGasPrice, types::U256};
pub fn init_gas_escalator() -> GeometricGasPrice {
let coefficient = 1.12501;
let every_secs: u64 = 5; // TODO: Make this be 90s
let max_gas_price = Some(U256::from(5000 * 1e9 as u64)); // 5k gwei
GeometricGasPrice::new(coefficient, every_secs, max_gas_price)
}
|
use anyhow::Context;
use pathfinder_common::TransactionHash;
use starknet_gateway_types::pending::PendingData;
use starknet_gateway_types::reply::transaction::ExecutionStatus;
use crate::context::RpcContext;
#[derive(serde::Deserialize, Debug, PartialEq, Eq)]
pub struct GetGatewayTransactionInput {
transaction_hash: TransactionHash,
}
crate::error::generate_rpc_error_subset!(GetGatewayTransactionError:);
pub async fn get_transaction_status(
context: RpcContext,
input: GetGatewayTransactionInput,
) -> Result<TransactionStatus, GetGatewayTransactionError> {
// Check in pending block.
if let Some(pending) = &context.pending_data {
if let Some(status) = pending_status(pending, &input.transaction_hash).await {
return Ok(status);
}
}
// Check database.
let span = tracing::Span::current();
let db_status = tokio::task::spawn_blocking(move || {
let _g = span.enter();
let mut db = context
.storage
.connection()
.context("Opening database connection")?;
let db_tx = db.transaction().context("Creating database transaction")?;
let Some((_, receipt, block_hash)) = db_tx
.transaction_with_receipt(input.transaction_hash)
.context("Fetching receipt from database")? else {
return anyhow::Ok(None);
};
if receipt.execution_status == ExecutionStatus::Reverted {
return Ok(Some(TransactionStatus::Reverted));
}
let l1_accepted = db_tx
.block_is_l1_accepted(block_hash.into())
.context("Quering block's status")?;
if l1_accepted {
Ok(Some(TransactionStatus::AcceptedOnL1))
} else {
Ok(Some(TransactionStatus::AcceptedOnL2))
}
})
.await
.context("Joining database task")??;
if let Some(db_status) = db_status {
return Ok(db_status);
}
// Check gateway for rejected transactions.
use starknet_gateway_client::GatewayApi;
context
.sequencer
.transaction(input.transaction_hash)
.await
.context("Fetching transaction from gateway")
.map(|tx| tx.status.into())
.map_err(GetGatewayTransactionError::Internal)
}
async fn pending_status(
pending: &PendingData,
tx_hash: &TransactionHash,
) -> Option<TransactionStatus> {
pending
.block()
.await
.map(|block| {
block.transaction_receipts.iter().find_map(|rx| {
if &rx.transaction_hash == tx_hash {
if rx.execution_status == ExecutionStatus::Reverted {
Some(TransactionStatus::Reverted)
} else {
Some(TransactionStatus::AcceptedOnL2)
}
} else {
None
}
})
})
.unwrap_or_default()
}
#[derive(Copy, Clone, Debug, serde::Serialize, PartialEq)]
pub enum TransactionStatus {
#[serde(rename = "NOT_RECEIVED")]
NotReceived,
#[serde(rename = "RECEIVED")]
Received,
#[serde(rename = "PENDING")]
Pending,
#[serde(rename = "REJECTED")]
Rejected,
#[serde(rename = "ACCEPTED_ON_L1")]
AcceptedOnL1,
#[serde(rename = "ACCEPTED_ON_L2")]
AcceptedOnL2,
#[serde(rename = "REVERTED")]
Reverted,
#[serde(rename = "ABORTED")]
Aborted,
}
impl From<starknet_gateway_types::reply::Status> for TransactionStatus {
fn from(value: starknet_gateway_types::reply::Status) -> Self {
use starknet_gateway_types::reply::Status;
match value {
Status::NotReceived => Self::NotReceived,
Status::Received => Self::Received,
Status::Pending => Self::Pending,
Status::Rejected => Self::Rejected,
Status::AcceptedOnL1 => Self::AcceptedOnL1,
Status::AcceptedOnL2 => Self::AcceptedOnL2,
Status::Reverted => Self::Reverted,
Status::Aborted => Self::Aborted,
}
}
}
#[cfg(test)]
mod tests {
use pathfinder_common::macro_prelude::*;
use super::*;
#[tokio::test]
async fn l1_accepted() {
let context = RpcContext::for_tests();
// This transaction is in block 0 which is L1 accepted.
let tx_hash = transaction_hash_bytes!(b"txn 0");
let input = GetGatewayTransactionInput {
transaction_hash: tx_hash,
};
let status = get_transaction_status(context, input).await.unwrap();
assert_eq!(status, TransactionStatus::AcceptedOnL1);
}
#[tokio::test]
async fn l2_accepted() {
let context = RpcContext::for_tests();
// This transaction is in block 1 which is not L1 accepted.
let tx_hash = transaction_hash_bytes!(b"txn 1");
let input = GetGatewayTransactionInput {
transaction_hash: tx_hash,
};
let status = get_transaction_status(context, input).await.unwrap();
assert_eq!(status, TransactionStatus::AcceptedOnL2);
}
#[tokio::test]
async fn pending() {
let context = RpcContext::for_tests_with_pending().await;
let tx_hash = transaction_hash_bytes!(b"pending tx hash 0");
let input = GetGatewayTransactionInput {
transaction_hash: tx_hash,
};
let status = get_transaction_status(context, input).await.unwrap();
assert_eq!(status, TransactionStatus::AcceptedOnL2);
}
#[tokio::test]
async fn rejected() {
let input = GetGatewayTransactionInput {
// Transaction hash known to be rejected by the testnet gateway.
transaction_hash: transaction_hash!(
"0x07c64b747bdb0831e7045925625bfa6309c422fded9527bacca91199a1c8d212"
),
};
let context = RpcContext::for_tests();
let status = get_transaction_status(context, input).await.unwrap();
assert_eq!(status, TransactionStatus::Rejected);
}
#[tokio::test]
async fn reverted() {
let context = RpcContext::for_tests_with_pending()
.await
.with_version("v0.3");
let input = GetGatewayTransactionInput {
transaction_hash: transaction_hash_bytes!(b"txn reverted"),
};
let status = get_transaction_status(context.clone(), input)
.await
.unwrap();
assert_eq!(status, TransactionStatus::Reverted);
let input = GetGatewayTransactionInput {
transaction_hash: transaction_hash_bytes!(b"pending reverted"),
};
let status = get_transaction_status(context, input).await.unwrap();
assert_eq!(status, TransactionStatus::Reverted);
}
}
|
use std::env;
use std::fs::File;
use std::io::Write;
fn main() -> std::io::Result<()> {
let file_name = env::args().nth(1).unwrap_or_default();
let mut file = File::create(file_name)?;
file.write_all(b"sample data")?;
Ok(())
}
|
/// `sysinfo`
pub type Sysinfo = linux_raw_sys::system::sysinfo;
pub(crate) type RawUname = linux_raw_sys::system::new_utsname;
|
use specs;
/// Color component. R, G, B, A format.
pub struct CompColor(pub [f32; 4]);
impl specs::Component for CompColor {
type Storage = specs::VecStorage<CompColor>;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.