text stringlengths 8 4.13M |
|---|
extern crate raster;
use raster::{
editor::{blend, fill, resize},
open, save, transform, BlendMode, Color, Image, PositionMode, ResizeMode,
};
struct Imagem {
imagem: Image,
salvar: String,
}
impl Imagem {
fn obter_imagem() -> Self {
if std::env::args().len() != 2 {
panic!("Favor entrar com um arquivo.")
};
let arquivo = std::env::args().nth(1).unwrap();
Self {
imagem: open(&arquivo).unwrap(),
salvar: arquivo.trim().replace(".jpg", "-10x15.jpg"),
}
}
fn montar_cartela(mut self) {
resize(&mut self.imagem, 354, 472, ResizeMode::Fit).unwrap();
let mut img_dupla_3x4 = Image::blank(354, 974);
fill(&mut img_dupla_3x4, Color::rgb(255, 255, 255)).unwrap();
for &i in [0, 502].iter() {
img_dupla_3x4 = blend(
&img_dupla_3x4,
&self.imagem,
BlendMode::Normal,
1.0,
PositionMode::TopLeft,
0,
i,
).unwrap();
}
let mut cartela = Image::blank(1200, 1800);
fill(&mut cartela, Color::rgb(255, 255, 255)).unwrap();
let mut pos = 30;
for i in 1..6 {
cartela = blend(
&cartela,
&img_dupla_3x4,
BlendMode::Normal,
1.0,
PositionMode::TopLeft,
pos,
30,
).unwrap();
pos += 384;
if i == 3 {
transform::rotate(&mut cartela, 90, Color::rgb(255, 255, 255)).unwrap();
pos = 30;
}
}
save(&mut cartela, &self.salvar).unwrap();
}
}
pub fn executar() {
Imagem::obter_imagem().montar_cartela();
}
|
use shrev::{EventChannel, ReaderId};
use specs::prelude::{Read, Resources, System, Write};
use crate::event;
pub struct EventSystem {
reader: Option<ReaderId<event::Event>>,
}
impl EventSystem {
pub fn new() -> Self {
EventSystem {
reader: None,
}
}
fn process_event(event: &event::Event, output: &mut EventChannel<event::WindowEvent>) {
match *event {
event::Event::WindowEvent { ref event, .. } => match event {
event::WindowEvent::WindowResize(width, height) => {},
}
}
}
}
impl<'a> System<'a> for EventSystem {
type SystemData = (
Read<'a, EventChannel<event::Event>>,
Write<'a, EventChannel<event::WindowEvent>>,
);
fn run(&mut self, (input, mut output): Self::SystemData) {
for event in input.read(&mut self.reader.as_mut().unwrap()) {
Self::process_event(event, &mut *output);
}
}
fn setup(&mut self, res: &mut Resources) {
use specs::prelude::SystemData;
Self::SystemData::setup(res);
self.reader = Some(res.fetch_mut::<EventChannel<event::Event>>().register_reader());
info!("Setting up WindowSystem");
}
} |
#[doc = "Reader of register APB1ENR2"]
pub type R = crate::R<u32, super::APB1ENR2>;
#[doc = "Writer for register APB1ENR2"]
pub type W = crate::W<u32, super::APB1ENR2>;
#[doc = "Register APB1ENR2 `reset()`'s with value 0"]
impl crate::ResetValue for super::APB1ENR2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LPUART1EN`"]
pub type LPUART1EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LPUART1EN`"]
pub struct LPUART1EN_W<'a> {
w: &'a mut W,
}
impl<'a> LPUART1EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `I2C4EN`"]
pub type I2C4EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `I2C4EN`"]
pub struct I2C4EN_W<'a> {
w: &'a mut W,
}
impl<'a> I2C4EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `UCPD1EN`"]
pub type UCPD1EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `UCPD1EN`"]
pub struct UCPD1EN_W<'a> {
w: &'a mut W,
}
impl<'a> UCPD1EN_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
}
}
impl R {
#[doc = "Bit 0 - Low power UART 1 clock enable"]
#[inline(always)]
pub fn lpuart1en(&self) -> LPUART1EN_R {
LPUART1EN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - I2C4 clock enable"]
#[inline(always)]
pub fn i2c4en(&self) -> I2C4EN_R {
I2C4EN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 8 - UCPD1 clock enable"]
#[inline(always)]
pub fn ucpd1en(&self) -> UCPD1EN_R {
UCPD1EN_R::new(((self.bits >> 8) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Low power UART 1 clock enable"]
#[inline(always)]
pub fn lpuart1en(&mut self) -> LPUART1EN_W {
LPUART1EN_W { w: self }
}
#[doc = "Bit 1 - I2C4 clock enable"]
#[inline(always)]
pub fn i2c4en(&mut self) -> I2C4EN_W {
I2C4EN_W { w: self }
}
#[doc = "Bit 8 - UCPD1 clock enable"]
#[inline(always)]
pub fn ucpd1en(&mut self) -> UCPD1EN_W {
UCPD1EN_W { w: self }
}
}
|
use std::collections::BTreeMap;
use models::messages::*;
use models::{AppState, Canvas, ChannelID};
#[derive(Debug, Default)]
pub struct MessageBuffer {
messages: BTreeMap<MessageID, Message>,
}
impl MessageBuffer {
pub fn new() -> Self {
MessageBuffer {
messages: BTreeMap::new(),
}
}
pub fn add<E: HistoryEntry>(&mut self, entry: E) {
let message = entry.into_message();
self.messages.insert(message.id().clone(), message);
}
pub fn render_as_canvas(&self, state: &AppState, width: u16) -> Canvas {
use tui::style::Style;
let mut canvas = Canvas::new(width);
if state.is_loading_more_messages {
canvas += LoadingMessage::new().render_as_canvas(state, width);
}
for (_id, message) in self
.messages
.iter()
.filter(|&(_, m)| m.channel_id() == state.selected_channel_id())
{
canvas += message.render_as_canvas(state, width);
canvas.add_string_truncated("\n", Style::default());
}
canvas
}
}
#[cfg(test)]
mod tests {
use super::*;
use models::User;
#[test]
fn it_renders_messages_as_canvas() {
let mut state = AppState::fixture();
state.selected_channel_id = ChannelID::from("C1");
state.users.add_user(User::fixture("U55", "Example"));
let mut message_buffer = MessageBuffer::new();
message_buffer.add(StandardMessage {
user_id: "U55".into(),
body: "Hello...".into(),
message_id: "1110000.0000".into(),
thread_id: "1110000.0000".into(),
channel_id: "C1".into(),
});
message_buffer.add(StandardMessage {
user_id: "U55".into(),
body: "...World!".into(),
message_id: "1110001.0000".into(),
thread_id: "1110001.0000".into(),
channel_id: "C1".into(),
});
let canvas = message_buffer.render_as_canvas(&state, 10);
assert_eq!(
&canvas.render_to_string(Some("|")),
"Example |
Hello... |
|
Example |
...World! |
|"
);
}
#[test]
fn it_adds_loading_message_when_loading() {
let mut state = AppState::fixture();
let mut message_buffer = MessageBuffer::new();
message_buffer.add(StandardMessage {
user_id: "U55".into(),
body: "Hello World".into(),
message_id: "1110000.0000".into(),
thread_id: "1110000.0000".into(),
channel_id: "C1".into(),
});
state.selected_channel_id = ChannelID::from("C1");
state.is_loading_more_messages = true;
let canvas = message_buffer.render_as_canvas(&state, 50);
assert_eq!(
&canvas.render_to_string(Some("|")),
" Loading more messages |
U55 |
Hello World |
|"
);
}
#[test]
fn it_skips_messages_in_other_channels() {
let mut state = AppState::fixture();
state.selected_channel_id = ChannelID::from("C2");
let mut message_buffer = MessageBuffer::new();
message_buffer.add(StandardMessage {
user_id: "Example".into(),
body: "First channel".into(),
message_id: "1110000.0000".into(),
thread_id: "1110000.0000".into(),
channel_id: "C1".into(),
});
message_buffer.add(StandardMessage {
user_id: "Example".into(),
body: "Second channel".into(),
message_id: "1110000.0000".into(),
thread_id: "1110000.0000".into(),
channel_id: "C2".into(),
});
let canvas = message_buffer.render_as_canvas(&state, 50);
let rendered = canvas.render_to_string(Some("|"));
assert!(rendered.contains("Second channel"));
assert!(!rendered.contains("First channel"));
}
}
|
use proptest::strategy::{Just, Strategy};
use liblumen_alloc::erts::process::alloc::TermAlloc;
use crate::erlang::binary_to_list_3::result;
use crate::test::strategy;
#[test]
fn without_binary_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_not_binary(arc_process.clone()),
)
},
|(arc_process, binary)| {
let start = arc_process.integer(1);
let stop = arc_process.integer(1);
prop_assert_badarg!(
result(&arc_process, binary, start, stop),
format!("binary ({}) must be a binary", binary)
);
Ok(())
},
);
}
#[test]
fn with_binary_without_integer_start_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_binary(arc_process.clone()),
strategy::term::is_not_integer(arc_process.clone()),
)
},
|(arc_process, binary, start)| {
let stop = arc_process.integer(1);
prop_assert_badarg!(
result(&arc_process, binary, start, stop),
format!("start ({}) must be a one-based integer index between 1 and the byte size of the binary", start)
);
Ok(())
},
);
}
#[test]
fn with_binary_with_positive_integer_start_without_integer_stop_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_binary(arc_process.clone()),
strategy::term::integer::positive(arc_process.clone()),
strategy::term::is_not_integer(arc_process.clone()),
)
},
|(arc_process, binary, start, stop)| {
prop_assert_badarg!(
result(&arc_process, binary, start, stop),
format!("stop ({}) must be a one-based integer index between 1 and the byte size of the binary", stop)
);
Ok(())
},
);
}
// `with_binary_with_start_less_than_or_equal_to_stop_returns_list_of_bytes` in integration tests
#[test]
fn with_binary_with_start_greater_than_stop_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::byte_vec::with_size_range((2..=4).into()),
)
.prop_flat_map(|(arc_process, byte_vec)| {
// -1 so that start can be greater
let max_stop = byte_vec.len() - 1;
(
Just(arc_process.clone()),
Just(byte_vec.len()),
strategy::term::binary::containing_bytes(byte_vec, arc_process.clone()),
(1..=max_stop),
)
})
.prop_flat_map(|(arc_process, max_start, binary, stop)| {
(
Just(arc_process.clone()),
Just(binary),
(stop + 1)..=max_start,
Just(stop),
)
})
},
|(arc_process, binary, start, stop)| {
let (start_term, stop_term) = {
let mut heap = arc_process.acquire_heap();
let start_term = heap.integer(start).unwrap();
let stop_term = heap.integer(stop).unwrap();
(start_term, stop_term)
};
prop_assert_badarg!(
result(&arc_process, binary, start_term, stop_term),
format!(
"start ({}) must be less than or equal to stop ({})",
start, stop
)
);
Ok(())
},
);
}
|
#[allow(unused_attributes)]
#[link_args = "--js-library src/js/console.js"]
extern "C" {
pub fn init_console();
pub fn set_console_text(s: *const i8);
pub fn set_console_color(s: *const i8);
}
|
use crate::formats::{ReferenceFormat, ReferenceFormatSpecification, NAMES};
use crate::object::{ObjectId, UUID_LENGTH};
use crate::Result;
use std::collections::{hash_map, HashMap};
use std::convert::TryInto;
use std::io;
use std::io::{BufRead, Read, Write};
use std::ops::Index;
type NamesDataType = HashMap<ObjectId, String>;
pub struct Names {
data: NamesDataType,
}
impl Names {
pub fn new() -> Self {
Names {
data: HashMap::new(),
}
}
pub fn insert(&mut self, id: &ObjectId, name: &str) -> Option<String> {
self.data.insert(*id, name.into())
}
pub fn remove(&mut self, id: &ObjectId) -> Option<String> {
self.data.remove(id)
}
pub fn remove_name(&mut self, name: &str) -> Option<ObjectId> {
if let Some(id) = self.get_id(name).copied() {
return self.data.remove(&id).map(|_| id);
}
None
}
pub fn get_name(&self, id: &ObjectId) -> Option<&String> {
self.data.get(id)
}
pub fn get_id(&self, name: &str) -> Option<&ObjectId> {
self.data.iter().find(|x| *x.1 == name).map(|x| x.0)
}
pub fn get_ids(&self) -> hash_map::Keys<'_, ObjectId, String> {
self.data.keys()
}
pub fn iter(&self) -> hash_map::Iter<'_, ObjectId, String> {
self.data.iter()
}
}
impl ReferenceFormat for Names {
fn specification() -> &'static ReferenceFormatSpecification {
&NAMES
}
fn load<R: BufRead + Read>(&mut self, reader: &mut R) -> Result<()> {
Self::check_magic_bytes(reader)?;
let mut uuid = Vec::with_capacity(UUID_LENGTH);
loop {
uuid.clear();
let uuid_bytes_read = reader.take(UUID_LENGTH as u64).read_to_end(&mut uuid)?;
if uuid_bytes_read == 0 {
break;
}
if uuid_bytes_read < UUID_LENGTH {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
}
let mut string_buffer = Vec::new();
let name_bytes_read = reader.read_until(0u8, &mut string_buffer)?;
let name = String::from_utf8(string_buffer[..name_bytes_read - 1].to_vec()).unwrap();
self.data.insert(uuid.as_slice().try_into().unwrap(), name);
}
Ok(())
}
fn save<W: Write>(&self, writer: &mut W) -> Result<()> {
writer.write_all(Self::specification().magic_bytes)?;
for name in self.data.iter() {
writer.write_all(name.0)?;
// Strip name of non-ASCII characters
writer.write_all(
&name
.1
.chars()
.filter(|c| c.is_ascii() && *c != '\0')
.collect::<String>()
.as_bytes(),
)?;
writer.write_all(&[0u8])?;
}
Ok(())
}
}
impl Index<ObjectId> for Names {
type Output = String;
fn index(&self, index: ObjectId) -> &Self::Output {
&self.data[&index]
}
}
impl Default for Names {
fn default() -> Self {
Names::new()
}
}
|
use crate::structs::parsed::weapons;
use crate::structs::raw::{
common, equip_affix_excel_config_data, material_excel_config_data,
weapon_curve_excel_config_data, weapon_excel_config_data, weapon_promote_excel_config_data,
};
use crate::utils::{readable::Readable, remove_xml, texthash::TextHash};
use std::fs;
fn load_data() -> crate::Result<(
Vec<weapon_excel_config_data::Data>,
Vec<weapon_curve_excel_config_data::Data>,
Vec<weapon_promote_excel_config_data::Data>,
Vec<equip_affix_excel_config_data::Data>,
Vec<material_excel_config_data::Data>,
)> {
let weapon_data =
fs::read_to_string("./data/ExcelBinOutput/WeaponExcelConfigData.json").unwrap();
let weapon_configs: Vec<weapon_excel_config_data::Data> =
serde_json::from_str(&weapon_data).unwrap();
let weapon_curve_data =
fs::read_to_string("./data/ExcelBinOutput/WeaponCurveExcelConfigData.json").unwrap();
let weapon_curves: Vec<weapon_curve_excel_config_data::Data> =
serde_json::from_str(&weapon_curve_data).unwrap();
let weapon_promote_data =
fs::read_to_string("./data/ExcelBinOutput/WeaponPromoteExcelConfigData.json").unwrap();
let weapon_promotes: Vec<weapon_promote_excel_config_data::Data> =
serde_json::from_str(&weapon_promote_data).unwrap();
let equip_data =
fs::read_to_string("./data/ExcelBinOutput/EquipAffixExcelConfigData.json").unwrap();
let equip_affixs: Vec<equip_affix_excel_config_data::Data> =
serde_json::from_str(&equip_data).unwrap();
let material_data =
fs::read_to_string("./data/ExcelBinOutput/MaterialExcelConfigData.json").unwrap();
let materials: Vec<material_excel_config_data::Data> =
serde_json::from_str(&material_data).unwrap();
Ok((
weapon_configs,
weapon_curves,
weapon_promotes,
equip_affixs,
materials,
))
}
fn parse_ascensions(
promotes: Vec<&weapon_promote_excel_config_data::Data>,
materials: &Vec<material_excel_config_data::Data>,
texthash: &TextHash,
) -> Vec<weapons::Ascension> {
let mut ascensions: Vec<weapons::Ascension> = vec![];
for promote in promotes.iter() {
let mut recipe: Vec<weapons::AscensionRecipe> = vec![];
for item in promote.cost_items.iter() {
if item.id.is_none() {
continue;
}
if item.count.is_none() {
continue;
}
let item_id = match item.id {
Some(id) => id,
None => 0,
};
let item_count = match item.count {
Some(count) => count,
None => 0,
};
let recipe_item = weapons::AscensionRecipe {
name: match materials.iter().find(|material| material.id == item_id) {
Some(material) => texthash.get_match(&material.name_text_map_hash).unwrap(),
None => "".to_owned(),
},
count: item_count,
game_id: item_id,
};
recipe.push(recipe_item);
}
let ascension = weapons::Ascension {
level: promote.promote_level.unwrap_or_default(),
recipe: recipe,
cost: promote.coin_cost.unwrap_or_default(),
max_level: promote.unlock_max_level,
required_player_level: promote.required_player_level.unwrap_or_default(),
};
ascensions.push(ascension);
}
ascensions
}
fn parse_passive(
equip_affixs: Vec<&equip_affix_excel_config_data::Data>,
texthash: &TextHash,
) -> Option<weapons::Passive> {
if equip_affixs.len() == 0 {
return None;
}
let name = texthash
.get_match(&equip_affixs[0].name_text_map_hash)
.unwrap();
let levels = equip_affixs
.iter()
.map(|affix| weapons::PassiveLevel {
description: remove_xml::remove_xml(
texthash.get_match(&affix.desc_text_map_hash).unwrap(),
)
.unwrap(),
additional_properties: affix
.add_props
.iter()
.filter(|prop| prop.prop_type.is_some())
.cloned()
.collect(),
params: affix.param_list.clone(),
level: match affix.level {
Some(level) => level + 1,
None => 1,
},
extra_config: affix.open_config.clone(),
extra_id: affix.id,
})
.collect();
Some(weapons::Passive { name, levels })
}
struct PromoteLevel {
max_level: usize,
add_atk: f64,
}
fn get_promotion_additinal_base_atk(
promotes: &Vec<weapon_promote_excel_config_data::Data>,
level: usize,
) -> f64 {
let promote_levels: Vec<PromoteLevel> = promotes
.iter()
.map(|promote| {
let add_prop = promote.add_props.iter().find(|prop| {
prop.prop_type.as_ref().unwrap() == &common::SubStatPropType::FightPropBaseAttack
});
let max_level = promote.unlock_max_level;
let add_atk = match add_prop {
Some(prop) => match prop.value {
Some(value) => value,
None => 0f64,
},
None => 0f64,
};
PromoteLevel {
max_level: max_level,
add_atk: add_atk,
}
})
.collect();
if promote_levels.len() >= 1 && level <= promote_levels[0].max_level {
return promote_levels[0].add_atk;
}
if promote_levels.len() >= 2
&& level > promote_levels[0].max_level
&& level <= promote_levels[1].max_level
{
return promote_levels[1].add_atk;
}
if promote_levels.len() >= 3
&& level > promote_levels[1].max_level
&& level <= promote_levels[2].max_level
{
return promote_levels[2].add_atk;
}
if promote_levels.len() >= 4
&& level > promote_levels[2].max_level
&& level <= promote_levels[3].max_level
{
return promote_levels[3].add_atk;
}
if promote_levels.len() >= 5
&& level > promote_levels[3].max_level
&& level <= promote_levels[4].max_level
{
return promote_levels[4].add_atk;
}
if promote_levels.len() >= 6
&& level > promote_levels[4].max_level
&& level <= promote_levels[5].max_level
{
return promote_levels[5].add_atk;
}
if promote_levels.len() >= 7
&& level > promote_levels[5].max_level
&& level <= promote_levels[6].max_level
{
return promote_levels[6].add_atk;
}
0f64
}
fn create_attack_scale(
weapon_curves: &Vec<weapon_curve_excel_config_data::Data>,
options: (
Option<f64>,
String,
&Vec<weapon_promote_excel_config_data::Data>,
usize,
),
) -> Vec<weapons::AttackLevel> {
let mut scale: Vec<weapons::AttackLevel> = vec![];
let init_value = match options.0 {
Some(value) => value,
None => 0f64,
};
let curve_type = options.1;
let promotes = options.2;
let weapon_id = options.3;
for curve in weapon_curves.iter() {
let promote_base_attack = get_promotion_additinal_base_atk(&promotes, curve.level);
if curve.level > 21 && promote_base_attack == 0f64 {
continue;
}
let value = match curve
.curve_infos
.iter()
.find(|info| info.r#type == curve_type)
{
Some(curve) => curve.value * init_value,
None => 1 as f64,
};
scale.push(weapons::AttackLevel {
level: curve.level,
value: value,
upgraded: false,
})
}
for (i, promote) in promotes
.iter()
.filter(|promote| promote.weapon_promote_id == weapon_id)
.enumerate()
{
let promote_add_prop = match promotes.len() >= i + 2 {
true => promotes[i + 1]
.add_props
.iter()
.find(|prop| match prop.prop_type.clone() {
Some(prop_type) => prop_type == common::SubStatPropType::FightPropBaseAttack,
None => false,
}),
false => None,
};
if promote_add_prop.is_none() {
continue;
}
let value = match weapon_curves
.iter()
.find(|curve| curve.level == promote.unlock_max_level)
{
Some(curve) => match curve
.curve_infos
.iter()
.find(|info| info.r#type == curve_type)
{
Some(curve) => {
let promote_base_attack =
get_promotion_additinal_base_atk(&promotes, promote.unlock_max_level);
(curve.value * init_value) + promote_base_attack
}
None => 1 as f64,
},
None => 1 as f64,
};
scale.push(weapons::AttackLevel {
level: promote.unlock_max_level,
value: value,
upgraded: true,
})
}
scale
}
fn create_sub_stat_scale(
weapon_curves: &Vec<weapon_curve_excel_config_data::Data>,
options: (
Option<f64>,
String,
Option<&weapon_promote_excel_config_data::Data>,
),
) -> Vec<weapons::SubStatLevel> {
let mut scale: Vec<weapons::SubStatLevel> = vec![];
let init_value = match options.0 {
Some(value) => value,
None => 0f64,
};
let curve_type = options.1;
let max_level = match options.2 {
Some(level) => level.unlock_max_level,
None => 90,
};
for curve in weapon_curves.iter() {
if curve.level > max_level {
continue;
}
let value = match curve
.curve_infos
.iter()
.find(|info| info.r#type == curve_type)
{
Some(curve) => curve.value * init_value,
None => 1 as f64,
};
if value == 0.0f64 {
continue;
}
scale.push(weapons::SubStatLevel {
level: curve.level,
value: value,
})
}
scale
}
pub fn parse(texthash: TextHash, readable: Readable) -> crate::Result<Vec<weapons::Data>> {
let (weapon_configs, weapon_curves, weapon_promotes, equip_affixs, materials) =
load_data().unwrap();
let mut weapon_data: Vec<weapons::Data> = vec![];
for weapon in weapon_configs {
let weapon_id = weapon.id;
let weapon_type = &weapon.weapon_type;
let name = texthash.get_match(&weapon.name_text_map_hash).unwrap();
let description =
remove_xml::remove_xml(texthash.get_match(&weapon.desc_text_map_hash).unwrap())
.unwrap();
let lore = remove_xml::remove_xml(
readable
.get_match(format!("Weapon{}", &weapon.id).as_str())
.unwrap(),
)
.unwrap();
let weapon_passive: Vec<&equip_affix_excel_config_data::Data> = equip_affixs
.iter()
.filter(|affix| affix.id == weapon.skill_affix[0])
.collect();
let mut promotes: Vec<&weapon_promote_excel_config_data::Data> = weapon_promotes
.iter()
.filter(|promote| promote.weapon_promote_id == weapon.id)
.collect();
let passive = parse_passive(weapon_passive, &texthash);
let rarity = weapon.rank_level;
let attack_levels = create_attack_scale(
&weapon_curves,
(
weapon.weapon_prop[0].init_value,
weapon.weapon_prop[0].r#type.clone(),
&weapon_promotes,
weapon_id,
),
);
let sub_stat_levels = match weapon.weapon_prop.len() >= 2 {
true => create_sub_stat_scale(
&weapon_curves,
(
weapon.weapon_prop[1].init_value,
weapon.weapon_prop[1].r#type.clone(),
weapon_promotes.last(),
),
),
false => vec![],
};
let weapon_sub_stat = match weapon.weapon_prop.len() >= 2 {
true => match &weapon.weapon_prop[1].prop_type {
Some(prop_type) => prop_type.to_string(),
None => "".to_owned(),
},
false => "".to_owned(),
};
promotes.rotate_right(1);
let ascensions = parse_ascensions(promotes, &materials, &texthash);
let weapon = weapons::Data {
weapon_id: weapon_id,
weapon: weapons::Weapon {
r#type: weapon_type.to_string(),
name: name,
description: description,
lore: lore,
passive: passive,
rarity: rarity,
attack_levels: attack_levels,
sub_stat_levels: sub_stat_levels,
sub_stat_type: weapon_sub_stat,
},
ascensions: ascensions,
};
weapon_data.push(weapon);
}
Ok(weapon_data)
}
|
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
use anyhow::Result;
use warp::{http::Method, Filter};
mod db;
mod graphql;
mod models;
mod schema;
pub async fn run() -> Result<()> {
::std::env::set_var("RUST_LOG", "warp_server");
env_logger::init();
let pool = db::setup()?;
let schema = graphql::schema();
let state = warp::any().map(move || graphql::context(pool.clone()));
let graphql_filter = juniper_warp::make_graphql_filter(schema, state.boxed());
let log = warp::log("warp_server");
log::info!("Listening on 127.0.0.1:3000");
let cors = warp::cors()
.allow_any_origin()
.allow_methods(&[Method::GET, Method::POST])
.allow_headers(vec!["content-type"]);
warp::serve(
warp::any()
.and(warp::path("graphiql"))
.and(juniper_warp::graphiql_filter("/graphql"))
.or(warp::path("graphql").and(graphql_filter))
.with(cors)
.with(log),
)
.run(([127, 0, 0, 1], 3000))
.await;
Ok(())
}
|
//!
//!
//! Create a `trait` definition
//!
use serde::Serialize;
use crate::traits::SrcCode;
use crate::{internal, AssociatedTypeDeclaration, FunctionSignature, Generic, SrcCodeVec};
use tera::{Context, Tera};
/// Represents a `trait` block.
///
/// Example
/// -------
/// ```
/// use proffer::*;
/// let tr8t = Trait::new("Foo")
/// .add_signature(FunctionSignature::new("bar"))
/// .to_owned();
/// let expected = r#"
/// trait Foo
/// {
/// fn bar() -> ();
/// }
/// "#;
/// assert_eq!(
/// norm_whitespace(expected),
/// norm_whitespace(tr8t.generate().as_str())
/// )
/// ```
#[derive(Serialize, Default, Clone)]
pub struct Trait {
name: String,
is_pub: bool,
generics: Vec<Generic>,
signatures: Vec<FunctionSignature>,
associated_types: Vec<AssociatedTypeDeclaration>,
}
impl Trait {
/// Create a new `trait`
pub fn new(name: impl ToString) -> Self {
Self {
name: name.to_string(),
..Self::default()
}
}
/// Get the trait name
pub fn name(&self) -> &str {
self.name.as_str()
}
/// Add a new signature requirement to this trait.
pub fn add_signature(&mut self, signature: FunctionSignature) -> &mut Self {
self.signatures.push(signature);
self
}
/// Set if this is a `pub` trait
pub fn set_is_pub(&mut self, is_pub: bool) -> &mut Self {
self.is_pub = is_pub;
self
}
/// Add a associated type to this trait.
pub fn add_associated_type(&mut self, associated_type: AssociatedTypeDeclaration) -> &mut Self {
self.associated_types.push(associated_type);
self
}
}
impl internal::Generics for Trait {
fn generics_mut(&mut self) -> &mut Vec<Generic> {
&mut self.generics
}
fn generics(&self) -> &[Generic] {
self.generics.as_slice()
}
}
impl SrcCode for Trait {
fn generate(&self) -> String {
let template = r#"
{% if self.is_pub %}pub {% endif %}trait {{ self.name }}{% if has_generics %}{{ generic_bounds }}{% endif %}
{
{% for associated_type in associated_types %}{{ associated_type }}{% endfor %}
{% for signature in signatures %}{{ signature }};{% endfor %}
}
"#;
let mut context = Context::new();
context.insert("self", &self);
context.insert("signatures", &self.signatures.to_src_vec());
context.insert("associated_types", &self.associated_types.to_src_vec());
context.insert("has_generics", &!self.generics.is_empty());
context.insert("generic_bounds", &self.generics.generate());
Tera::one_off(template, &context, false).unwrap()
}
}
|
use crate::FunctionData;
pub struct RemoveNopsPass;
impl super::Pass for RemoveNopsPass {
fn name(&self) -> &str {
"nop elimination"
}
fn time(&self) -> crate::timing::TimedBlock {
crate::timing::remove_nops()
}
fn run_on_function(&self, function: &mut FunctionData) -> bool {
// Nops are created by optimization passes to eliminate unneeded instructions.
// This pass will go through every block and remove nops from it.
for label in function.reachable_labels() {
function.blocks.get_mut(&label)
.unwrap()
.retain(|instruction| !instruction.is_nop());
}
// This optimization pass shouldn't change anything so just return false.
false
}
}
|
extern crate clap;
extern crate image;
mod cli;
mod utils;
mod intervals;
mod sorter;
fn main() {
let matches = cli::en();
let image_input_path = matches.value_of("INPUT").unwrap();
let image_output_path = format!("{}{}", utils::generate_id(), ".png");
println!("opening image...");
let mut img = image::open(image_input_path).expect("image not found.");
img = match matches.value_of("direction").unwrap() {
"l2r" => img,
"r2l" => img.rotate180(),
"t2b" => img.rotate270(),
"b2t" => img.rotate90(),
_ => panic!("could not determine in which direction to sort the image.")
};
let buf = img.to_rgb();
let mut output_img = match matches.subcommand_name() {
Some("threshold") => {
let lower = matches.subcommand_matches("threshold")
.unwrap().value_of("lower").unwrap().parse().unwrap();
let upper = matches.subcommand_matches("threshold")
.unwrap().value_of("upper").unwrap().parse().unwrap();
println!("computing intervals...");
let intervals = intervals::threshold(&buf, lower, upper);
println!("sorting pixels...");
image::DynamicImage::ImageRgb8(sorter::sort(buf, intervals))
},
Some("mask") => {
let mask_path = matches.subcommand_matches("mask")
.unwrap().value_of("mask").unwrap();
println!("opening mask picture...");
let mut mask = image::open(mask_path).expect("mask not found");
mask = match matches.value_of("direction").unwrap() {
"l2r" => mask,
"r2l" => mask.rotate180(),
"t2b" => mask.rotate270(),
"b2t" => mask.rotate90(),
_ => {panic!()}
};
println!("computing intervals...");
let intervals = intervals::mask(&mask.to_rgb());
image::DynamicImage::ImageRgb8(sorter::sort(buf, intervals))
}
_ => panic!("You need to provide an interval function. For more information use --help.")
};
output_img = match matches.value_of("direction").unwrap() {
"l2r" => output_img,
"r2l" => output_img.rotate180(),
"t2b" => output_img.rotate90(),
"b2t" => output_img.rotate270(),
_ => panic!("could not determine in which direction to sort the image.")
};
println!("writing output image...");
output_img.save(image_output_path).expect("something went wrong when saving file.");
} |
use std::io;
use std::result;
use std::fmt;
#[derive(Debug)]
pub enum Error {
None,
Io(io::Error),
HomeAssistant(homeassistant::Error),
Format(fmt::Error)
}
pub type Result<S> = result::Result<S, Error>;
impl From<()> for Error {
fn from(_err: ()) -> Error {
Error::None
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<homeassistant::Error> for Error {
fn from(err: homeassistant::Error) -> Error {
Error::HomeAssistant(err)
}
}
impl From<fmt::Error> for Error {
fn from(err: fmt::Error) -> Error {
Error::Format(err)
}
} |
use firefly_diagnostics::Spanned;
use firefly_syntax_base::*;
use super::Fun;
#[derive(Debug, Clone, Spanned)]
pub struct Function {
pub var_counter: usize,
#[span]
pub fun: Fun,
}
impl Eq for Function {}
impl PartialEq for Function {
fn eq(&self, other: &Self) -> bool {
self.fun == other.fun
}
}
impl Annotated for Function {
#[inline]
fn annotations(&self) -> &Annotations {
self.fun.annotations()
}
#[inline]
fn annotations_mut(&mut self) -> &mut Annotations {
self.fun.annotations_mut()
}
}
|
/*
* Copyright 2019 The Exonum Team
*
* 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.
*/
extern crate integration_tests;
extern crate java_bindings;
#[macro_use]
extern crate lazy_static;
use integration_tests::{
mock::transaction::{
create_mock_transaction_proxy, create_throwing_exec_exception_mock_transaction_proxy,
create_throwing_mock_transaction_proxy, AUTHOR_PK_ENTRY_NAME, ENTRY_VALUE, TEST_ENTRY_NAME,
TX_HASH_ENTRY_NAME,
},
vm::create_vm_for_tests_with_fake_classes,
};
use java_bindings::{
exonum::{
blockchain::{Transaction, TransactionContext, TransactionError, TransactionErrorType},
crypto::{Hash, PublicKey},
messages::RawTransaction,
storage::{Database, Entry, Fork, MemoryDB, Snapshot},
},
jni::JavaVM,
MainExecutor,
};
use std::sync::Arc;
const ARITHMETIC_EXCEPTION_CLASS: &str = "java/lang/ArithmeticException";
const OOM_ERROR_CLASS: &str = "java/lang/OutOfMemoryError";
lazy_static! {
static ref VM: Arc<JavaVM> = create_vm_for_tests_with_fake_classes();
pub static ref EXECUTOR: MainExecutor = MainExecutor::new(VM.clone());
}
#[test]
// TODO: reenable these tests after ECR-2789
#[ignore]
fn execute_valid_transaction() {
let db = MemoryDB::new();
{
let snapshot = db.snapshot();
let entry = create_test_entry(&*snapshot);
assert_eq!(None, entry.get());
}
{
let mut fork = db.fork();
let (valid_tx, raw) = create_mock_transaction_proxy(EXECUTOR.clone());
{
let tx_context = create_transaction_context(&mut fork, raw);
valid_tx
.execute(tx_context)
.map_err(TransactionError::from)
.unwrap_or_else(|err| {
panic!(
"Execution error: {:?}; {}",
err.error_type(),
err.description().unwrap_or_default()
)
});
}
db.merge(fork.into_patch())
.expect("Failed to merge transaction");
}
// Check the transaction has successfully written the expected value into the entry index.
let snapshot = db.snapshot();
let entry = create_test_entry(&*snapshot);
assert_eq!(Some(String::from(ENTRY_VALUE)), entry.get());
}
#[test]
#[ignore]
#[should_panic(expected = "Java exception: java.lang.OutOfMemoryError")]
fn execute_should_panic_if_java_error_occurred() {
let (panic_tx, raw) = create_throwing_mock_transaction_proxy(EXECUTOR.clone(), OOM_ERROR_CLASS);
let db = MemoryDB::new();
let mut fork = db.fork();
let tx_context = create_transaction_context(&mut fork, raw);
panic_tx.execute(tx_context).unwrap();
}
#[test]
#[ignore]
#[should_panic(expected = "Java exception: java.lang.ArithmeticException")]
fn execute_should_panic_if_java_exception_occurred() {
let (panic_tx, raw) =
create_throwing_mock_transaction_proxy(EXECUTOR.clone(), ARITHMETIC_EXCEPTION_CLASS);
let db = MemoryDB::new();
let mut fork = db.fork();
let tx_context = create_transaction_context(&mut fork, raw);
panic_tx.execute(tx_context).unwrap();
}
#[test]
#[ignore]
fn execute_should_return_err_if_tx_exec_exception_occurred() {
let err_code: i8 = 1;
let err_message = "Expected exception";
let (invalid_tx, raw) = create_throwing_exec_exception_mock_transaction_proxy(
EXECUTOR.clone(),
false,
err_code,
Some(err_message),
);
let db = MemoryDB::new();
let mut fork = db.fork();
let tx_context = create_transaction_context(&mut fork, raw);
let err = invalid_tx
.execute(tx_context)
.map_err(TransactionError::from)
.expect_err("This transaction should be executed with an error!");
assert_eq!(err.error_type(), TransactionErrorType::Code(err_code as u8));
assert!(err.description().unwrap().starts_with(err_message));
}
#[test]
#[ignore]
fn execute_should_return_err_if_tx_exec_exception_subclass_occurred() {
let err_code: i8 = 2;
let err_message = "Expected exception subclass";
let (invalid_tx, raw) = create_throwing_exec_exception_mock_transaction_proxy(
EXECUTOR.clone(),
true,
err_code,
Some(err_message),
);
let db = MemoryDB::new();
let mut fork = db.fork();
let tx_context = create_transaction_context(&mut fork, raw);
let err = invalid_tx
.execute(tx_context)
.map_err(TransactionError::from)
.expect_err("This transaction should be executed with an error!");
assert_eq!(err.error_type(), TransactionErrorType::Code(err_code as u8));
assert!(err.description().unwrap().starts_with(err_message));
}
#[test]
#[ignore]
fn execute_should_return_err_if_tx_exec_exception_occurred_no_message() {
let err_code: i8 = 3;
let (invalid_tx, raw) = create_throwing_exec_exception_mock_transaction_proxy(
EXECUTOR.clone(),
false,
err_code,
None,
);
let db = MemoryDB::new();
let mut fork = db.fork();
let tx_context = create_transaction_context(&mut fork, raw);
let err = invalid_tx
.execute(tx_context)
.map_err(TransactionError::from)
.expect_err("This transaction should be executed with an error!");
assert_eq!(err.error_type(), TransactionErrorType::Code(err_code as u8));
assert!(err.description().is_none());
}
#[test]
#[ignore]
fn execute_should_return_err_if_tx_exec_exception_subclass_occurred_no_message() {
let err_code: i8 = 4;
let (invalid_tx, raw) = create_throwing_exec_exception_mock_transaction_proxy(
EXECUTOR.clone(),
true,
err_code,
None,
);
let db = MemoryDB::new();
let mut fork = db.fork();
let tx_context = create_transaction_context(&mut fork, raw);
let err = invalid_tx
.execute(tx_context)
.map_err(TransactionError::from)
.expect_err("This transaction should be executed with an error!");
assert_eq!(err.error_type(), TransactionErrorType::Code(err_code as u8));
assert!(err.description().is_none());
}
#[test]
#[ignore]
fn passing_transaction_context() {
let db = MemoryDB::new();
let (tx_hash, author_pk) = {
let mut fork = db.fork();
let (valid_tx, raw) = create_mock_transaction_proxy(EXECUTOR.clone());
// get transaction hash and author public key from mock transaction
let (tx_hash, author_pk) = {
let context = create_transaction_context(&mut fork, raw);
let (tx_hash, author_pk) = (context.tx_hash(), context.author());
// execute transaction
valid_tx.execute(context).unwrap();
(tx_hash, author_pk)
};
db.merge(fork.into_patch()).unwrap();
(tx_hash, author_pk)
};
let snapshot = db.snapshot();
let tx_hash_entry: Entry<_, Hash> = Entry::new(TX_HASH_ENTRY_NAME, &snapshot);
assert_eq!(tx_hash_entry.get().unwrap(), tx_hash);
let author_pk_entry: Entry<_, PublicKey> = Entry::new(AUTHOR_PK_ENTRY_NAME, &snapshot);
assert_eq!(author_pk_entry.get().unwrap(), author_pk);
}
fn create_test_entry<V>(view: V) -> Entry<V, String>
where
V: AsRef<Snapshot + 'static>,
{
Entry::new(TEST_ENTRY_NAME, view)
}
fn create_transaction_context(fork: &mut Fork, raw: RawTransaction) -> TransactionContext {
let (service_id, service_transaction) = (raw.service_id(), raw.service_transaction());
let (pk, sk) = java_bindings::exonum::crypto::gen_keypair();
let signed_transaction = java_bindings::exonum::messages::Message::sign_transaction(
service_transaction,
service_id,
pk,
&sk,
);
TransactionContext::new(fork, &signed_transaction)
}
|
//! Implementation of the service which processes [`Command`]s from client and
//! [`Event`]s.
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::{Rc, Weak},
};
use futures::StreamExt as _;
use tokio::task::spawn_local;
use crate::{
proto::{Command, Event},
rpc_connection::ServerRpcConnection,
server::room::Room,
snapshot::{PeerSnapshot, RoomSnapshot},
};
pub(crate) type MemberId = u64;
struct SnapshotResolverInner {
/// Actual snapshot of the [`Room`] which owns this [`SnapshotResolver`].
snapshot: RefCell<HashMap<MemberId, RoomSnapshot>>,
/// Weak reference to the [`Room`] which owns this [`SnapshotResolver`].
room: Weak<RefCell<Room>>,
/// RPC connections with [`MemberId`]s.
connections: RefCell<HashMap<MemberId, Box<dyn ServerRpcConnection>>>,
/// List of `Member`s which [`RoomSnapshot`]s are currently syncing.
members_in_sync_state: RefCell<HashSet<MemberId>>,
}
impl SnapshotResolverInner {
pub fn new(room: Weak<RefCell<Room>>) -> Self {
Self {
snapshot: RefCell::new(HashMap::new()),
room,
connections: RefCell::new(HashMap::new()),
members_in_sync_state: RefCell::new(HashSet::new()),
}
}
}
/// Service which processes [`Command`]s from client and [`Event`]s.
#[derive(Clone)]
pub struct SnapshotResolver(Rc<SnapshotResolverInner>);
impl SnapshotResolver {
/// Returns new [`SnapshotResolver`].
pub fn new(room: Weak<RefCell<Room>>) -> Self {
Self(Rc::new(SnapshotResolverInner::new(room)))
}
/// Inserts new `Member`'s [`ServerRpcConnection`] and starts polling
/// [`Command`]s from it.
pub fn new_member_conn(
&self,
member_id: MemberId,
conn: Box<dyn ServerRpcConnection>,
) {
let mut command_stream = conn.on_command();
self.0.connections.borrow_mut().insert(member_id, conn);
let mut room_snap = RoomSnapshot::new();
room_snap.peers.insert(
1,
PeerSnapshot {
sdp_answer: None,
sdp_offer: None,
},
);
self.0
.snapshot
.borrow_mut()
.insert(member_id.clone(), room_snap);
let weak_inner = Rc::downgrade(&self.0);
spawn_local(async move {
while let Some(command) = command_stream.next().await {
if let Some(inner) = weak_inner.upgrade() {
let this = SnapshotResolver(inner);
this.on_command(member_id.clone(), command);
}
}
});
}
/// Processes [`Command::SynchronizeMe`] or pass normal [`Command`]s to the
/// [`Room`].
fn on_command(&self, member_id: MemberId, command: Command) {
match command {
Command::MakeSdpAnswer {
peer_id,
sdp_answer,
} => {
if let Some(room) = self.0.room.upgrade() {
room.borrow_mut()
.on_make_sdp_offer(peer_id, sdp_answer.clone());
}
}
Command::SynchronizeMe { snapshot } => {
self.sync(member_id, snapshot);
}
_ => (),
}
}
/// Sends [`Event`] to the `Member`, updates [`RoomSnapshot`] of this
/// `Member`.
pub fn send_event(&self, member_id: u64, event: Event) {
if let Some(current_snapshot) =
self.0.snapshot.borrow_mut().get_mut(&member_id)
{
match &event {
Event::PeersRemoved { peers_ids } => {
for peer_id in peers_ids {
current_snapshot.peers.remove(&peer_id);
}
}
Event::SdpAnswerMade {
peer_id,
sdp_answer,
} => {
if let Some(peer) = current_snapshot.peers.get_mut(&peer_id)
{
peer.sdp_answer = Some(sdp_answer.clone());
}
}
Event::SnapshotSynchronized { snapshot: _ } => {
self.0
.members_in_sync_state
.borrow_mut()
.remove(&member_id);
}
}
if !self.0.members_in_sync_state.borrow().contains(&member_id) {
if let Some(conn) = self.0.connections.borrow().get(&member_id)
{
conn.send_event(event);
}
}
}
}
/// Synchronizes client and server [`RoomSnapshot`]s after reconnection.
fn sync(&self, member_id: MemberId, with_snapshot: RoomSnapshot) {
let peer_diffs: Vec<_> = if let Some(room_snapshot) =
self.0.snapshot.borrow().get(&member_id)
{
self.0.members_in_sync_state.borrow_mut().insert(member_id);
with_snapshot
.peers
.into_iter()
.filter_map(|(peer_id, new_peer)| {
room_snapshot.peers.get(&peer_id).map(|current_peer| {
(peer_id, current_peer.diff(&new_peer))
})
})
.collect()
} else {
return;
};
for (peer_id, peer_diff) in peer_diffs {
if let Some(on_make_sdp_offer) = peer_diff.on_make_sdp_offer() {
if let Some(room) = self.0.room.upgrade() {
room.borrow_mut().on_make_sdp_offer(
peer_id,
on_make_sdp_offer.sdp_offer.unwrap(),
);
}
}
}
let final_room_snapshot =
self.0.snapshot.borrow().get(&member_id).unwrap().clone();
self.send_event(
member_id,
Event::SnapshotSynchronized {
snapshot: final_room_snapshot,
},
);
}
}
|
use std::collections::HashMap;
#[allow(dead_code)]
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub enum Stat {
// primary
Strength,
Dexterity,
Vitality,
Intelligence,
Mind,
// offensive
CriticalHitRate,
Determination,
DirectHitRate,
// defensive
Defense,
MagicDefense,
// physical properties
AttackPower,
SkillSpeed,
// mental properties
AttackMagicPotency,
HealingMagicPotency,
SpellSpeed,
// role
Piety,
Tenacity,
// other
PhysicalWeaponDamage,
MagicWeaponDamage,
}
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub enum SpecialStat {
CriticalHitPercentOverride,
}
#[derive(Default)]
pub struct Stats {
delta: HashMap<Stat, i64>,
base: HashMap<Stat, i64>,
special: HashMap<SpecialStat, i64>,
}
impl Stats {
pub fn get(&self, stat: Stat) -> i64 {
self.delta.get(&stat).unwrap_or(&0) + self.base.get(&stat).unwrap_or(&0)
}
pub fn add(&mut self, stat: Stat, amount: i64) {
match self.delta.get_mut(&stat) {
Some(value) => *value += amount,
None => {
self.delta.insert(stat, amount);
}
}
}
pub fn reset(&mut self) {
self.delta.clear();
self.special.clear();
}
pub fn set_base(&mut self, stat: Stat, amount: i64) {
self.base.insert(stat, amount);
}
pub fn set_special(&mut self, stat: SpecialStat, amount: i64) {
self.special.insert(stat, amount);
}
pub fn get_special(&self, stat: SpecialStat) -> Option<&i64> {
self.special.get(&stat)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get() {
let mut stats = Stats::default();
stats.add(Stat::CriticalHitRate, 10);
assert_eq!(10, stats.get(Stat::CriticalHitRate));
stats.set_base(Stat::CriticalHitRate, 5);
assert_eq!(15, stats.get(Stat::CriticalHitRate));
}
#[test]
fn add() {
let mut stats = Stats::default();
stats.add(Stat::CriticalHitRate, 10);
assert_eq!(10, stats.get(Stat::CriticalHitRate));
}
#[test]
fn set_base() {
let mut stats = Stats::default();
stats.set_base(Stat::CriticalHitRate, 10);
assert_eq!(10, stats.base[&Stat::CriticalHitRate]);
assert_eq!(false, stats.delta.contains_key(&Stat::CriticalHitRate));
assert_eq!(10, stats.get(Stat::CriticalHitRate));
}
#[test]
fn reset() {
let mut stats = Stats::default();
stats.set_base(Stat::CriticalHitRate, 10);
stats.add(Stat::CriticalHitRate, 5);
assert_eq!(15, stats.get(Stat::CriticalHitRate));
stats.reset();
assert_eq!(10, stats.get(Stat::CriticalHitRate));
}
}
|
//!
//! Channel Subscriber
//!
use super::Network;
use crate::iota_channels_lite::utils::{payload::json::Payload, random_seed};
use iota::client as iota_client;
use iota_streams::app::transport::tangle::{client::RecvOptions, PAYLOAD_BYTES};
use iota_streams::app::transport::Transport;
use iota_streams::app_channels::{
api::{
tangle::{Address, Subscriber},
SequencingState,
},
message,
};
use anyhow::Result;
///
/// Channel subscriber
///
pub struct Channel {
subscriber: Subscriber,
is_connected: bool,
announcement_link: Address,
subscription_link: Address,
channel_address: String,
}
impl Channel {
///
/// Initialize the subscriber
///
pub fn new(
node: Network,
channel_address: String,
announcement_tag: String,
seed_option: Option<String>,
) -> Channel {
let seed = match seed_option {
Some(seed) => seed,
None => random_seed::new(),
};
iota_client::Client::add_node(node.as_string()).unwrap();
let subscriber = Subscriber::new(&seed, "utf-8", PAYLOAD_BYTES);
Self {
subscriber: subscriber,
is_connected: false,
announcement_link: Address::from_str(&channel_address, &announcement_tag).unwrap(),
subscription_link: Address::default(),
channel_address: channel_address,
}
}
///
/// Connect
///
pub fn connect(&mut self) -> Result<String> {
let message_list = iota_client::Client::get()
.recv_messages_with_options(&self.announcement_link, RecvOptions { flags: 0 })?;
let mut found_valid_msg = false;
for tx in message_list.iter() {
let header = tx.parse_header()?;
if header.check_content_type(message::ANNOUNCE) {
self.subscriber.unwrap_announcement(header.clone())?;
found_valid_msg = true;
break;
}
}
if found_valid_msg {
self.is_connected = true;
} else {
println!("No valid announce message found");
}
Ok(self.subscription_link.msgid.to_string())
}
///
/// Read signed packet
///
pub fn read_signed(
&mut self,
signed_packet_tag: String,
) -> Result<Vec<(Option<String>, Option<String>)>> {
let mut response: Vec<(Option<String>, Option<String>)> = Vec::new();
if self.is_connected {
let link = Address::from_str(&self.channel_address, &signed_packet_tag).unwrap();
let message_list = iota_client::Client::get()
.recv_messages_with_options(&link, RecvOptions { flags: 0 })?;
for tx in message_list.iter() {
let header = tx.parse_header()?;
if header.check_content_type(message::SIGNED_PACKET) {
match self.subscriber.unwrap_signed_packet(header.clone()) {
Ok((_signer, unwrapped_public, unwrapped_masked)) => {
response.push((
Payload::unwrap_data(
&String::from_utf8(unwrapped_public.0).unwrap(),
)
.unwrap(),
Payload::unwrap_data(
&String::from_utf8(unwrapped_masked.0).unwrap(),
)
.unwrap(),
));
}
Err(e) => println!("Signed Packet Error: {}", e),
}
}
}
} else {
println!("Channel not connected");
}
Ok(response)
}
///
/// Generates the next message in the channels
///
pub fn get_next_message(&mut self) -> Option<String> {
let ids = self.subscriber.gen_next_msg_ids(false);
let mut tag: Option<String> = None;
for (_pk, SequencingState(next_id, seq_num)) in ids.iter() {
let msg = iota_client::Client::get()
.recv_message_with_options(&next_id, RecvOptions { flags: 0 })
.ok();
if msg.is_none() {
continue;
}
let unwrapped = msg.unwrap();
loop {
let preparsed = unwrapped.parse_header().unwrap();
match preparsed.header.content_type.0 {
message::SIGNED_PACKET => {
let _unwrapped = self.subscriber.unwrap_signed_packet(preparsed.clone());
tag = Some(next_id.msgid.to_string());
break;
}
message::TAGGED_PACKET => {
let _unwrapped = self.subscriber.unwrap_tagged_packet(preparsed.clone());
tag = Some(next_id.msgid.to_string());
break;
}
message::KEYLOAD => {
let _unwrapped = self.subscriber.unwrap_keyload(preparsed.clone());
tag = Some(next_id.msgid.to_string());
break;
}
_ => {
break;
}
}
}
self.subscriber
.store_state_for_all(next_id.clone(), *seq_num);
}
tag
}
}
|
use crate::values::{Register, Value};
#[derive(Debug)]
pub enum Operation {
Halt,
Set(Register, Value),
Push(Value),
Pop(Register),
Equal(Register, Value, Value),
GreaterThan(Register, Value, Value),
Jump(Value),
JumpTrue(Value, Value),
JumpFalse(Value, Value),
Add(Register, Value, Value),
Multiply(Register, Value, Value),
Modulo(Register, Value, Value),
And(Register, Value, Value),
Or(Register, Value, Value),
Not(Register, Value),
ReadMem(Register, Value),
WriteMem(Value, Value),
Call(Value),
Return,
Out(Value),
Input(Register),
Noop,
}
|
use crate::any::connection::AnyConnectionKind;
use crate::any::options::{AnyConnectOptions, AnyConnectOptionsKind};
use crate::any::AnyConnection;
use crate::connection::Connection;
use crate::error::Error;
impl AnyConnection {
pub(crate) async fn establish(options: &AnyConnectOptions) -> Result<Self, Error> {
match &options.0 {
#[cfg(feature = "mysql")]
AnyConnectOptionsKind::MySql(options) => {
crate::mysql::MySqlConnection::connect_with(options)
.await
.map(AnyConnectionKind::MySql)
}
#[cfg(feature = "postgres")]
AnyConnectOptionsKind::Postgres(options) => {
crate::postgres::PgConnection::connect_with(options)
.await
.map(AnyConnectionKind::Postgres)
}
#[cfg(feature = "sqlite")]
AnyConnectOptionsKind::Sqlite(options) => {
crate::sqlite::SqliteConnection::connect_with(options)
.await
.map(AnyConnectionKind::Sqlite)
}
#[cfg(feature = "mssql")]
AnyConnectOptionsKind::Mssql(options) => {
crate::mssql::MssqlConnection::connect_with(options)
.await
.map(AnyConnectionKind::Mssql)
}
}
.map(AnyConnection)
}
}
|
/**
* Copyright © 2019
* Sami Shalayel <sami.shalayel@tutamail.com>,
* Carl Schwan <carl@carlschwan.eu>,
* Daniel Freiermuth <d_freiermu14@cs.uni-kl.de>
*
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See the LICENSE file for more details.
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See the LICENSE
* file for more details. **/
use crate::ray::Ray;
use crate::shader::Shader;
use crate::world::World;
use nalgebra::{Unit, Vector2, Vector3};
pub struct DiffuseShader {
pub color: Vector3<f64>,
}
impl DiffuseShader {
pub fn new(color: Vector3<f64>) -> Box<Shader> {
Box::new(DiffuseShader { color } )
}
}
impl Shader for DiffuseShader {
fn get_appearance_for(
&self,
intersection_pos: Vector3<f64>,
_ray_dir: Vector3<f64>,
_surface_normal: Vector3<f64>,
world: &World,
_surface_pos: Vector2<f64>,
_recursion_depth: f64,
) -> Vector3<f64> {
let mut i_diffuse = Vector3::new(0.0, 0.0, 0.0);
for light in &world.lights {
let shade_ray = Ray {
dir: Unit::new_normalize(intersection_pos - light.pos),
start: light.pos,
};
if let Some(shade_intersection) = world.next_intersection(&shade_ray) {
if (shade_intersection.pos - intersection_pos).norm() < 0.001 {
let l_m = shade_ray.dir.normalize();
let n_hat = shade_intersection.normal_at_surface.normalize();
i_diffuse += 2.0 * (-l_m.dot(&n_hat) * self.color).component_mul(&light.color);
}
}
}
i_diffuse
}
}
|
// 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::task::Context;
use std::task::Poll;
use common_exception::Result;
use common_expression::DataBlock;
pub struct DataBlockStream {
current: usize,
data: Vec<DataBlock>,
projects: Option<Vec<usize>>,
}
impl DataBlockStream {
pub fn create(projects: Option<Vec<usize>>, data: Vec<DataBlock>) -> Self {
DataBlockStream {
current: 0,
data,
projects,
}
}
}
impl futures::Stream for DataBlockStream {
type Item = Result<DataBlock>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
Poll::Ready(if self.current < self.data.len() {
self.current += 1;
let block = &self.data[self.current - 1];
Some(Ok(match &self.projects {
Some(v) => DataBlock::new(
v.iter().map(|x| block.get_by_offset(*x).clone()).collect(),
block.num_rows(),
),
None => block.clone(),
}))
} else {
None
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.data.len(), Some(self.data.len()))
}
}
|
pub trait FromSingle
|
mod weather;
mod config;
mod wallpaper;
mod worker;
use std::{env, error::Error, fs::create_dir, io::{ErrorKind, Read}, path::Path};
use reqwest::{blocking::Client, header::{HeaderMap, HeaderValue}};
use serde::{Serialize, Deserialize};
pub use config::Config;
pub use weather::get_weather;
pub use worker::{Worker, Message, MetaMessage, State};
pub use crate::config::{DownloadQuality, DEFAULT_CONFIG_PATH};
pub use crate::wallpaper::set_wallpaper::set_wallpaper;
const API_BASE_URL: &str = "https://api.unsplash.com";
pub const DEFAULT_DOWNLOAD_PATH: &str = "download";
const MAXIMUM_PER_PAGE: i32 = 100;
#[derive(Serialize, Deserialize, Debug)]
pub struct Urls {
pub raw: String,
pub full: String,
pub regular: String,
pub small: String,
pub thumb: String
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SearchResult {
pub id: String,
pub urls: Urls
}
#[derive(Serialize, Deserialize, Debug)]
pub struct SearchResults {
pub total: usize,
pub results: Vec<SearchResult>
}
pub fn make_unsplash_client(config: &Config) -> Result<Client, Box<dyn Error>> {
let mut default_headers = HeaderMap::new();
default_headers.append("Authorization", HeaderValue::from_str(
&format!("Client-ID {}", match &config.unsplash_access_key {
Some(key) => key.clone(),
None => {
env::var("AWC_UNSPLASH_KEY")?
}
}))?);
let client = Client::builder()
.default_headers(default_headers)
.build()?;
Ok(client)
}
pub fn search_photos(client: &Client, query: &str) -> Result<SearchResults, Box<dyn Error>> {
let mut response = client.get(format!("{}/search/photos?query={}&per_page={}",
API_BASE_URL,
query,
MAXIMUM_PER_PAGE)).send()?;
let mut data = String::new();
response.read_to_string(&mut data)?;
let data: SearchResults = serde_json::from_str(&data)?;
Ok(data)
}
pub fn download_photo(client: &Client, photo: &SearchResult, quality: DownloadQuality) -> Result<String, Box<dyn Error>> {
let save_path = format!("{}/{}.jpg", DEFAULT_DOWNLOAD_PATH, photo.id);
if Path::new(&save_path).exists() {
return Ok(save_path);
}
let url = match quality {
DownloadQuality::Raw => &photo.urls.raw,
DownloadQuality::Full => &photo.urls.full,
DownloadQuality::Regular => &photo.urls.regular,
DownloadQuality::Small => &photo.urls.small,
DownloadQuality::Thumb => &photo.urls.thumb
};
let mut response = client.get(url).send()?;
if let Err(e) = create_dir(DEFAULT_DOWNLOAD_PATH) {
if e.kind() != ErrorKind::AlreadyExists {
return Err(Box::new(e));
}
}
let mut data = Vec::new();
response.read_to_end(&mut data)?;
std::fs::write(&save_path, data)?;
Ok(save_path)
}
pub struct Hour(pub u32);
impl ToString for Hour {
fn to_string(&self) -> String {
match self.0 {
1 | 2 | 3 => {
String::from("midnight")
},
4 | 5 => {
String::from("twilight")
},
6 | 7 => {
String::from("sunrise")
},
8 | 9 => {
String::from("morning")
},
10 | 11 => {
String::from("day")
},
12 | 13 => {
String::from("noon")
},
14 | 15 | 16 => {
String::from("afternoon")
},
17 | 18 => {
String::from("sunset")
},
19 | 20 => {
String::from("evening")
},
21 | 22 => {
String::from("night")
},
23 | 0 => {
String::from("late night")
},
_ => panic!("Unreachable")
}
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use chrono::{Local, Timelike};
use super::*;
#[test]
fn test_client() {
assert!(make_unsplash_client(&Config::from_path(DEFAULT_CONFIG_PATH).unwrap()).is_ok());
}
#[test]
fn test_search() {
let client = make_unsplash_client(&Config::from_path(DEFAULT_CONFIG_PATH).unwrap()).unwrap();
assert!(search_photos(&client, "noon").is_ok());
}
#[test]
#[ignore]
fn test_download() {
let fake_result = SearchResult {
id: String::from("6GHNuQAVC8Y"),
urls: Urls {
raw: String::new(),
full: String::from("https://images.unsplash.com/photo-1616762897553-c3a04bcf795d?ixid=MnwyMjk2MjV8MHwxfHNlYXJjaHwxfHxub29ufGVufDB8fHx8MTYyMDU2NzEzNA\\u0026ixlib=rb-1.2.1"),
regular: String::new(),
small: String::new(),
thumb: String::new()
}
};
let path = download_photo(&make_unsplash_client(&Config::from_path(DEFAULT_CONFIG_PATH).unwrap()).unwrap(), &fake_result, DownloadQuality::Full).unwrap();
assert!(Path::new(&path).exists());
}
#[test]
fn test_generate_config() {
match std::fs::remove_file("test.json") {
Ok(_) => {},
Err(e) => {
if e.kind() != ErrorKind::NotFound {
panic!("{}", e);
}
}
}
let config = Config::from_path("test.json").unwrap();
assert_eq!(config.repeat_secs, 1);
match config.quality {
DownloadQuality::Full => {},
_ => panic!("Incorrect quality")
}
let config = Config::from_path("test.json").unwrap();
assert_eq!(config.repeat_secs, 1);
match config.quality {
DownloadQuality::Full => {},
_ => panic!("Incorrect quality")
}
match std::fs::remove_file("test.json") {
Ok(_) => {},
Err(e) => {
if e.kind() != ErrorKind::NotFound {
panic!("{}", e);
}
}
}
}
#[test]
#[ignore = "It might not be 23:00 now"]
fn test_now() {
assert_eq!(Hour(Local::now().hour()).to_string(), "late night");
}
}
|
pub struct Clock {
h:i32,
m:i32
}
// adding comment
// !! looks like its off by one somewhere o well!
impl Clock {
pub fn new(hours: i32, minutes: i32) -> Self {
let h_adjust = if hours < 0 { 24 }else { 0 };
let m_adjust = if minutes < 0 { 60 } else { 0 };
Clock{
h:h_adjust +( hours + minutes/60)%24,
m:(m_adjust +minutes%60)%60
}
}
pub fn to_string(&self)-> String {
format!("{:02}:{:02}",self.h,self.m)
}
pub fn add_minutes(&self, minutes: i32) -> Self {
let mut copy = Clock::new(self.h,self.m);
if (minutes + copy.m)as f32/60.0 > 1.0 {
copy.h += 1;
}
copy.m = (copy.m + minutes)%60;
copy
}
}
|
mod delta;
mod index;
mod pack;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use dashmap::DashMap;
use self::index::{FindIndexOffsetError, IndexFile, ReadIndexFileError};
use self::pack::{PackFile, ReadPackFileError};
use crate::object::database::ObjectReader;
use crate::object::ShortId;
use thiserror::Error;
const PACKS_FOLDER: &str = "objects/pack";
const MAX_REFRESH_INTERVAL: Duration = Duration::from_secs(2);
#[derive(Debug)]
pub struct PackedObjectDatabase {
path: PathBuf,
// last: Mutex<Arc<PackFile>>, why is this useful?
packs: DashMap<PathBuf, Arc<Entry>>,
last_refresh: Mutex<Option<Instant>>,
}
#[derive(Debug, Error)]
pub(in crate::object) enum ReadPackedError {
#[error("the object id was not found in the packed database")]
NotFound,
#[error("the object id is ambiguous in the packed database")]
Ambiguous,
#[error(transparent)]
ReadEntry(#[from] ReadEntryError),
#[error("io error reading from the packed object database")]
Io(
#[source]
#[from]
io::Error,
),
}
#[derive(Debug, Error)]
#[error("failed to read packed database entry {name}")]
pub(in crate::object) struct ReadEntryError {
name: String,
#[source]
kind: ReadEntryErrorKind,
}
#[derive(Debug, Error)]
enum ReadEntryErrorKind {
#[error("failed to read the pack index file")]
ReadIndexFile(#[source] ReadIndexFileError),
#[error("failed to read the pack file")]
ReadPackFile(#[source] ReadPackFileError),
#[error("the pack index file and pack file have a different number of entries")]
CountMismatch,
#[error("the pack index file and pack file have a different id")]
IdMismatch,
}
#[derive(Debug)]
struct Entry {
name: String,
index: IndexFile,
pack: PackFile,
}
impl PackedObjectDatabase {
pub fn open(path: &Path) -> Self {
PackedObjectDatabase {
path: path.join(PACKS_FOLDER),
packs: DashMap::new(),
last_refresh: Mutex::new(None),
}
}
pub(in crate::object::database) fn read_object(
&self,
short_id: &ShortId,
) -> Result<ObjectReader, ReadPackedError> {
match self.try_read_object(short_id) {
Err(ReadPackedError::NotFound) if self.refresh()? => self.try_read_object(short_id),
result => result,
}
}
fn try_read_object(&self, short_id: &ShortId) -> Result<ObjectReader, ReadPackedError> {
let mut result = None;
let mut found_id = None;
for entry in self.packs.iter() {
match entry.value().index.find_offset(short_id) {
Err(FindIndexOffsetError::Ambiguous) => return Err(ReadPackedError::Ambiguous),
Ok((_, id)) if found_id.is_some() && found_id != Some(id) => {
return Err(ReadPackedError::Ambiguous)
}
Ok((offset, id)) => {
found_id = Some(id);
result = Some((entry.value().clone(), offset))
}
Err(FindIndexOffsetError::NotFound) => continue,
Err(FindIndexOffsetError::ReadIndexFile(err)) => {
return Err(ReadPackedError::ReadEntry(ReadEntryError {
name: entry.name.clone(),
kind: ReadEntryErrorKind::ReadIndexFile(err),
}))
}
}
}
match result {
Some((entry, offset)) => match entry.pack.read_object(&entry.index, offset) {
Ok(reader) => Ok(reader),
Err(err) => Err(ReadPackedError::ReadEntry(ReadEntryError {
name: entry.name.clone(),
kind: ReadEntryErrorKind::ReadPackFile(err),
})),
},
None => Err(ReadPackedError::NotFound),
}
}
fn refresh(&self) -> Result<bool, ReadPackedError> {
// Keep the mutex locked while refreshing so we don't have multiple thread refreshing simultaneously.
// This isn't necessary for correctness, but is just an optimization.
let mut last_refresh_guard = self.last_refresh.lock().unwrap();
match *last_refresh_guard {
Some(last_refresh) if last_refresh.elapsed() < MAX_REFRESH_INTERVAL => {
return Ok(false)
}
_ => (),
}
for entry in fs_err::read_dir(&self.path)? {
let path = entry?.path();
if path.extension() == Some("idx".as_ref()) {
self.packs
.entry(path.clone())
.or_try_insert_with(move || Entry::open(path).map(Arc::new))?;
}
}
*last_refresh_guard = Some(Instant::now());
Ok(true)
}
}
impl Entry {
fn open(path: PathBuf) -> Result<Self, ReadEntryError> {
// The file has an extension so it must have a file name
let name = path.file_name().unwrap().to_string_lossy().into_owned();
let index = match IndexFile::open(path.clone()) {
Ok(index) => index,
Err(err) => {
return Err(ReadEntryError {
name,
kind: ReadEntryErrorKind::ReadIndexFile(err),
})
}
};
let pack = match PackFile::open(path.with_extension("pack")) {
Ok(pack) => pack,
Err(err) => {
return Err(ReadEntryError {
name,
kind: ReadEntryErrorKind::ReadPackFile(err),
})
}
};
if index.count() != pack.count() {
return Err(ReadEntryError {
name,
kind: ReadEntryErrorKind::CountMismatch,
});
}
if index.id() != pack.id() {
return Err(ReadEntryError {
name,
kind: ReadEntryErrorKind::IdMismatch,
});
}
Ok(Entry { pack, index, name })
}
}
|
#[derive(Default, Debug)]
pub struct OsSpecificConfig {
pub enable_game_mode: bool,
}
// ============================================================
// ====================== Linux =========================
// ============================================================
#[cfg(target_os = "linux")]
use crate::core::osspecific::linux;
#[cfg(target_os = "linux")]
pub struct OsSpecific {
gamemode: Option<linux::gamemode::GameMode>,
}
#[cfg(target_os = "linux")]
impl OsSpecific {
pub fn new(config: &OsSpecificConfig) -> OsSpecific {
let gamemode = if config.enable_game_mode {
match linux::gamemode::GameMode::new() {
Ok(gamemode) => Some(gamemode),
Err(msg) => {
println!("{}", msg);
None
}
}
} else {
None
};
OsSpecific { gamemode: gamemode }
}
}
#[cfg(target_os = "linux")]
impl std::fmt::Debug for OsSpecific {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let some = match &self.gamemode {
Some(_) => "Some",
None => "None",
};
write!(f, "OsSpecific {{ gamemode: {} }}", some)
}
}
// ============================================================
// ===================== Others =========================
// ============================================================
#[cfg(not(target_os = "linux"))]
pub struct OsSpecific;
#[cfg(not(target_os = "linux"))]
impl OsSpecific {
pub fn new(_config: &OsSpecificConfig) -> OsSpecific {
OsSpecific
}
pub fn enable(&self) {}
pub fn disable(&self) {}
}
#[cfg(not(target_os = "linux"))]
impl std::fmt::Debug for OsSpecific {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "OsSpecific {{ }}")
}
}
|
/// References
///
/// - they're pointers that ONLY borrow data
fn references() {
println!("--- REFERENCES ---");
let foo: &str = "baz";
println!("printing a reference {}\n", &foo);
}
/// Smart Pointers
///
/// data structures that not only act like a pointer but also have
/// - additional metadata
/// - additional capabilities
/// - not unique to Rust as C++ has them as well
/// - allows us to own some memory and manipulate it
/// - typically implemented using structs
/// - they implement `Deref` and `Drop` traits
///
/// examples (most common):
/// - `String`
/// - `Vec<T>`
/// - `Box<T>`
/// - `Rc<T>`
/// - `Ref<T>`
/// - `RefMut<T>` and accessed through `RefCell<T>`
#[allow(dead_code)]
fn smart_pointers() {}
/// Box Pointers
///
/// - store data on the heap (instead of stack)
/// - stack contains a pointer to the heap data
/// - no performance overhead
/// - use cases:
/// - type whose size is unknown at compile time and want to use the value of the type in context
/// that requires an exact size (e.g., recursive types)
/// - large amount of data and want to transfer ownership but disallow copying (mitigating stack
/// allocation and copying that is slow)
/// - 3. trait objects -- desire to own a value and we only care about type that implements a particular trait
fn box_pointers() {
println!("--- BOX POINTERS ---");
let b = Box::new(5);
println!("b = {}\n", b);
// NOTE: recursive types with boxes
// cons lists - data type that is common in functional programming languages
enum List {
Cons(i32, Box<List>), // Box is a "smart" pointer (fixed size)
Nil,
}
use List::{Cons, Nil};
#[allow(unused_variables)]
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
}
/// dereference pointer (*) allows us to follow the pointer to the data
fn dereference() {
println!("--- DEREF TRAIT ---");
let x = 5;
let y = MyBox::new(x); // setting `y` to a reference of `x`
assert_eq!(5, x);
// because y is a reference to a reference, we need to follow it to obtain the value
assert_eq!(5, *y); // * is a call to the `deref` method
}
/// defining our own smart pointer
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
use std::ops::Deref;
impl<T> Deref for MyBox<T> {
type Target = T; // defines associated type for `Deref` trait to use
fn deref(&self) -> &T {
&self.0 // this avoids moving the value out of self by returning a reference
}
}
/// deref coercion
fn hello(name: &str) {
println!("Hello, {}!", name);
}
mod drop;
use drop::CustomSmartPointer;
fn drops() {
#[allow(unused_variables)]
let c = CustomSmartPointer {
data: String::from("my stuff"),
};
#[allow(unused_variables)]
let d = CustomSmartPointer {
data: String::from("other stuff"),
};
println!("CustomSmartPointers created.\n");
println!("--- DROP EXAMPLE ---");
// drop example
let c2 = CustomSmartPointer {
data: String::from("some data"),
};
println!("CustomSmartPointer created");
drop(c2);
println!("CustomSmartPointer dropped before the end of main.");
}
/// Rc<T>, the reference counted smart pointer
///
/// - primary use to share data
/// - e.g. graph node with many in-degrees
///
/// NOTE: use in only single-threaded scenarios; diff method for ref-counting in concurrent programs
fn multiple_ownership() {
println!("\n--- multiple ownership with Rc<T>");
enum List {
Cons(i32, Rc<List>),
Nil,
}
use std::rc::Rc;
use List::{Cons, Nil};
// b -> 3 -> \
// \
// a -> 5 -> 10 -> Nil
// /
// c -> 4 -> /
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("count after create a = {}", Rc::strong_count(&a));
let _b = Cons(3, Rc::clone(&a));
println!("count after create b = {}", Rc::strong_count(&a));
{
let _c = Cons(4, Rc::clone(&a));
println!("count after create c = {}", Rc::strong_count(&a));
}
println!("count after c goes out of scope = {}", Rc::strong_count(&a));
}
mod ref_cell;
mod multiple_ownership;
mod ref_cycles_mem_leak;
mod ref_bidirectional_tree;
fn main() {
references();
box_pointers();
dereference();
// deref coercion with MyBox
let m = MyBox::new(String::from("Rust"));
hello(&m); // deref coercion saves us from having to write...
// hello(&(*m)[..]);
// - the (*m) does the deref into MyBox<String> and into String
// - the & and [..] take a string slice of the String that is equal to the entire string to
// match the signature of hello
drops();
multiple_ownership();
multiple_ownership::main();
ref_cycles_mem_leak::main();
ref_bidirectional_tree::main();
}
|
use ptgui::prelude::*;
use raylib::prelude::*;
#[derive(PartialEq)]
enum State {
Empty,
}
fn main() {
let (mut rl_handler, rl_thread) = raylib::init().size(1280, 720).title("Label test").build();
rl_handler.set_target_fps(60);
let mut g_handler = GuiHandler::new(Colour::WHITE);
g_handler
.add_label("Main Menu")
.add_button("Test button", "")
.set_button_action_function(|s, a| match a {
_ => *s = State::Empty,
})
.set_components_fix_widths(true);
while !rl_handler.window_should_close() {
let mut draw_handler = g_handler.draw(&mut rl_handler, &rl_thread).unwrap();
draw_handler.draw_fps(0, 0);
}
}
|
extern crate ardop_interface;
extern crate async_std;
#[macro_use]
extern crate clap;
extern crate futures;
#[macro_use]
extern crate log;
extern crate stderrlog;
use std::net::ToSocketAddrs;
use std::process::exit;
use std::str;
use std::time::Duration;
use async_std::task;
use clap::{App, Arg};
use futures::prelude::*;
use ardop_interface::tnc::*;
const SHAKESPEARE: &[&[u8]] = &[
b"Now is the winter of our discontent / Made glorious summer by this sun of York.\n",
b"Some are born great, some achieve greatness / And some have greatness thrust upon them.\n",
b"Friends, Romans, countrymen - lend me your ears! / I come not to praise Caesar, but to bury him.\n",
b"The evil that men do lives after them / The good is oft interred with their bones.\n",
];
fn main() {
task::block_on(async_main())
}
async fn async_main() {
// argument parsing
let matches = App::new("echoclient")
.version(crate_version!())
.arg(
Arg::with_name("ADDRESS")
.help("TNC hostname:port")
.required(true)
.index(1),
)
.arg(
Arg::with_name("MYCALL")
.help("Client callsign")
.required(true)
.index(2),
)
.arg(
Arg::with_name("TARGET")
.help("Peer callsign-SSID to dial")
.required(true)
.index(3),
)
.arg(
Arg::with_name("BW")
.help("ARQ connection bandwidth")
.default_value("500")
.required(false)
.index(4),
)
.arg(
Arg::with_name("verbosity")
.short("v")
.multiple(true)
.help("Increase message verbosity"),
)
.arg(
Arg::with_name("attempts")
.short("n")
.default_value("5")
.help("Number of connection attempts"),
)
.arg(
Arg::with_name("clear-time")
.short("c")
.default_value("10")
.help("Minimum clear channel time, in seconds"),
)
.get_matches();
let tnc_address_str = matches.value_of("ADDRESS").unwrap();
let mycallstr = matches.value_of("MYCALL").unwrap();
let targetcallstr = matches.value_of("TARGET").unwrap();
let arq_bandwidth = value_t!(matches, "BW", u16).unwrap_or_else(|e| e.exit());
let attempts = value_t!(matches, "attempts", u16).unwrap_or_else(|e| e.exit());
let verbose = matches.occurrences_of("verbosity") as usize;
let clear_time_secs = value_t!(matches, "clear-time", u64).unwrap_or_else(|e| e.exit());
stderrlog::new()
.module(module_path!())
.module("ardop_interface")
.verbosity(verbose + 2)
.timestamp(stderrlog::Timestamp::Millisecond)
.color(stderrlog::ColorChoice::Auto)
.init()
.unwrap();
// parse and resolve socket address of TNC
let tnc_address = tnc_address_str
.to_socket_addrs()
.expect("Invalid socket address")
.next()
.expect("Error resolving TNC address");
// connect to TNC
let mut tnc = ArdopTnc::new(&tnc_address, mycallstr)
.await
.expect("Unable to connect to ARDOP TNC");
// set the minimum clear channel time
// the channel must be clear for at least this long before we transmit
tnc.set_clear_time(Duration::from_secs(clear_time_secs));
// set a more reasonable ARQ timeout
tnc.set_arqtimeout(30).await.expect("Can't set ARQTIMEOUT.");
// set my grid square
tnc.set_gridsquare("EM00")
.await
.expect("Can't set GRIDSQUARE.");
// make the connection
let mut connection = match tnc
.connect(targetcallstr, arq_bandwidth, false, attempts)
.await
.expect("TNC error while dialing")
{
Err(reason) => {
error!("Unable to connect to {}: {}", targetcallstr, reason);
exit(1)
}
Ok(conn) => conn,
};
// try to transmit each stanza
let mut iter = 0usize;
for &stanza in SHAKESPEARE {
let rxbuf = &mut [0u8; 512];
// write some
match connection.write_all(&stanza).await {
// wrote them
Ok(_ok) => info!("TX: {}", str::from_utf8(&stanza).unwrap()),
// peer connection is dead
Err(e) => {
error!("Transmit failed: {}", e);
break;
}
}
// read back -- no need for framing, as we know precisely
// the length of data that we are going to receive
match connection.read_exact(&mut rxbuf[0..stanza.len()]).await {
Ok(_o) => (),
Err(e) => {
error!("Receive failed: {}", e);
break;
}
}
// check for match
debug!("RX: {}", str::from_utf8(&rxbuf[0..stanza.len()]).unwrap());
if stanza == &rxbuf[0..stanza.len()] {
info!("Received good echo for stanza {}.", iter);
}
iter += 1;
}
if iter >= SHAKESPEARE.len() {
info!("Echo server echoed all stanzas correctly. Will now disconnect.");
} else {
error!("Echo server failed to echo all stanzas.");
}
// connection drops automatically as it passes out of scope
}
|
#[doc = "Writer for register C15IFCR"]
pub type W = crate::W<u32, super::C15IFCR>;
#[doc = "Register C15IFCR `reset()`'s with value 0"]
impl crate::ResetValue for super::C15IFCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `CTEIF15`"]
pub struct CTEIF15_W<'a> {
w: &'a mut W,
}
impl<'a> CTEIF15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Write proxy for field `CCTCIF15`"]
pub struct CCTCIF15_W<'a> {
w: &'a mut W,
}
impl<'a> CCTCIF15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Write proxy for field `CBRTIF15`"]
pub struct CBRTIF15_W<'a> {
w: &'a mut W,
}
impl<'a> CBRTIF15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Write proxy for field `CBTIF15`"]
pub struct CBTIF15_W<'a> {
w: &'a mut W,
}
impl<'a> CBTIF15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Write proxy for field `CLTCIF15`"]
pub struct CLTCIF15_W<'a> {
w: &'a mut W,
}
impl<'a> CLTCIF15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
impl W {
#[doc = "Bit 0 - Channel x clear transfer error interrupt flag Writing a 1 into this bit clears TEIFx in the MDMA_ISRy register"]
#[inline(always)]
pub fn cteif15(&mut self) -> CTEIF15_W {
CTEIF15_W { w: self }
}
#[doc = "Bit 1 - Clear Channel transfer complete interrupt flag for channel x Writing a 1 into this bit clears CTCIFx in the MDMA_ISRy register"]
#[inline(always)]
pub fn cctcif15(&mut self) -> CCTCIF15_W {
CCTCIF15_W { w: self }
}
#[doc = "Bit 2 - Channel x clear block repeat transfer complete interrupt flag Writing a 1 into this bit clears BRTIFx in the MDMA_ISRy register"]
#[inline(always)]
pub fn cbrtif15(&mut self) -> CBRTIF15_W {
CBRTIF15_W { w: self }
}
#[doc = "Bit 3 - Channel x Clear block transfer complete interrupt flag Writing a 1 into this bit clears BTIFx in the MDMA_ISRy register"]
#[inline(always)]
pub fn cbtif15(&mut self) -> CBTIF15_W {
CBTIF15_W { w: self }
}
#[doc = "Bit 4 - CLear buffer Transfer Complete Interrupt Flag for channel x Writing a 1 into this bit clears TCIFx in the MDMA_ISRy register"]
#[inline(always)]
pub fn cltcif15(&mut self) -> CLTCIF15_W {
CLTCIF15_W { w: self }
}
}
|
use std::error::Error;
pub mod add;
pub mod clone;
pub mod info;
pub mod init;
pub mod ls;
pub mod unlink;
pub trait Command {
fn run(&self) -> Result<(), Box<dyn Error>> {
Ok(())
}
}
|
use juniper::FieldResult;
use tokio;
use super::model::{TodoItem, TodoList};
use super::Context;
use crate::db::{todo_item, todo_list};
pub struct QueryRoot;
#[juniper::object(
// Here we specify the context type for this object.
Context = Context,
)]
impl QueryRoot {
#[graphql(description = "List of all todo lists")]
fn todo_lists(ctx: &Context) -> FieldResult<Vec<TodoList>> {
// create new async runtime using tokio
let mut rt = tokio::runtime::Runtime::new().unwrap();
// run async fn get_todos using tokio runtime
let todo = match rt.block_on(todo_list::get_todos(&ctx.db)) {
Ok(todo) => todo,
Err(e) => Err(e)?,
};
// println!("todo_lists: {:?}", todo);
// return todo
Ok(todo)
}
#[graphql(
description = "Single todo list item in an array. If item is not found empty array is returned."
)]
fn todo_list_item(id: i32, ctx: &Context) -> FieldResult<Vec<TodoList>> {
// create new async runtime using tokio
let mut rt = tokio::runtime::Runtime::new().unwrap();
// run async fn get_todos using tokio runtime
let todo = match rt.block_on(todo_list::get_todo_list(&ctx.db, id)) {
Ok(todo) => todo,
Err(e) => Err(e)?,
};
Ok(todo)
}
#[graphql(
description = "Single todo item return in array. If item is not found empty array is returned."
)]
fn todo_item(lid: i32, id: i32, ctx: &Context) -> FieldResult<Vec<TodoItem>> {
// create new async runtime using tokio
let mut rt = tokio::runtime::Runtime::new().unwrap();
// run async fn get_todos using tokio runtime
let todo = match rt.block_on(todo_item::get_todo_item(&ctx.db, id)) {
Ok(todo) => todo,
Err(e) => Err(e)?,
};
Ok(todo)
}
#[graphql(description = "All todo items from specified todo list.")]
fn todo_items_for_list(lid: i32, ctx: &Context) -> FieldResult<Vec<TodoItem>> {
// create new async runtime using tokio
let mut rt = tokio::runtime::Runtime::new().unwrap();
// run async fn get_todos using tokio runtime
let todo = match rt.block_on(todo_item::get_todo_items(&ctx.db, lid)) {
Ok(todo) => todo,
Err(e) => Err(e)?,
};
Ok(todo)
}
}
|
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
#[macro_use] extern crate prettytable;
extern crate clap;
use clap::{App, SubCommand, Arg};
use std::process::{Command, Output};
use std::io::Write;
use regex::Regex;
use prettytable::{Table, format};
use levenshtein::levenshtein;
fn main() {
// search sub-command
let search_sub_command= SubCommand::with_name("search")
.about("search for packages across distributions.")
.arg(
Arg::with_name("QUERY").takes_value(true)
);
let application = App::new("troll")
.version("0.1.0")
.about("Utility for finding, installing, and removing universal Linux packages.")
.author("Ross Harrison")
.subcommand(search_sub_command);
ensure_requirements();
let matches = application
.get_matches_safe()
.unwrap();
if let Some(matches) = matches.subcommand_matches("search") {
let query = matches.value_of("QUERY").expect("Query string required for search");
search(query);
}
}
fn ensure_requirements() {
let all_available = (
check_for_requirement("snap"),
check_for_requirement("flatpak")
);
match all_available {
(Ok(_), Ok(_)) => return,
(snap, flatpak) => {
if snap.is_err() {
writeln!(std::io::stderr(), "{}", snap.err().unwrap())
.unwrap();
}
if flatpak.is_err() {
writeln!(std::io::stderr(), "{}", flatpak.err().unwrap())
.unwrap();
}
std::process::exit(1);
}
}
}
fn check_for_requirement(required_command: &str) -> Result<Output, String>{
let result = Command::new("which")
.arg(required_command)
.output();
match &result {
Ok(output) => {
if output.stdout.len() == 0 {
return Err(format!("requirement not found: {}", required_command));
}
return Ok(output.clone());
},
Err(_) => {
return Err("Error Running `which`".to_string());
}
}
}
#[derive(Clone, Debug)]
struct SearchResult {
name: String,
version: String,
publisher: String,
source: String,
description: String,
/// levenshtein distance from query string to result name
lv_distance: usize,
}
// TODO: Move search into own ... module?
fn search(name: &str) {
// filter results, logging errors
let snap_results = search_snap(name);
let flatpak_results = search_flatpak(name);
let mut results = [snap_results, flatpak_results].concat();
results.sort_by(|a, b| a.lv_distance.partial_cmp(&b.lv_distance)
.unwrap());
/*
*print results table
*/
let mut table = Table::new();
let format = format::FormatBuilder::new()
.borders(' ')
.separators(&[format::LinePosition::Top],
format::LineSeparator::new(' ', ' ', ' ', ' '))
.padding(0, 5)
.build();
table.set_format(format);
// add header
table.add_row(row!["SOURCE", "NAME", "VERSION", "PUBLISHER", "Lv Distance", "Description"]);
// add result rows
results.iter().for_each(|result| {
table.add_row(
row![result.source, result.name, result.version, result.publisher, result.lv_distance, result.description]
);
});
print!("{}", table.to_string());
}
fn search_flatpak(name: &str) -> Vec<SearchResult> {
let flatpak_command_output = Command::new("flatpak")
.arg("search")
.arg(name)
.output().unwrap();
let std_out_string = String::from_utf8_lossy(&flatpak_command_output.stdout);
let unfiltered_results: Vec<Result<SearchResult, String>> = std_out_string.split('\n')
.map(|result| flatpak_line_to_result(result, name))
.skip(1)
.collect();
return filter_search_results(unfiltered_results);
}
fn search_snap(name: &str) -> Vec<SearchResult> {
let snap_command_output = Command::new("snap")
.arg("search")
.arg(name)
.output().unwrap();
let std_out_string = String::from_utf8_lossy(&snap_command_output.stdout);
let unfiltered_results: Vec<Result<SearchResult, String>> = std_out_string.split('\n')
.map(|result| snap_line_to_result(result, name))
.skip(1)
.collect();
return filter_search_results(unfiltered_results);
}
///
/// Return the OK results, and log the error-ing lines out
///
fn filter_search_results(results: Vec<Result<SearchResult, String>>) -> Vec<SearchResult> {
results.iter().fold(vec![], |ok_results, result| {
match result {
Ok(ok_result) => [&ok_results[..], &vec![ok_result.clone()][..]].concat(),
Err(error) => {
error!("{}", error);
ok_results
}
}
})
}
///
/// Create vector of results from the flatpak output line
///
fn flatpak_line_to_result(flatpak_line: &str, query_name: &str) -> Result<SearchResult, String> {
println!("{}", flatpak_line);
lazy_static! {
static ref FLATPAK_LINE_REGEX: Regex = Regex::new(r"^([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+(.+)$").unwrap();
}
let capture_group = match FLATPAK_LINE_REGEX.captures(flatpak_line) {
Some(_capture_group) => _capture_group,
_ => return Err(format!("Couldn't parse: {}", flatpak_line.to_string()))
};
let name = match capture_group.get(1) {
Some(name_capture) => name_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get name from line:\n {}", flatpak_line.to_string()))
};
let version = match capture_group.get(2) {
Some(version_capture) => version_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get version from line:\n {}", flatpak_line.to_string()))
};
let branch = match capture_group.get(3) {
Some(publisher_capture) => publisher_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get publisher from line:\n {}", flatpak_line.to_string()))
};
let source = match capture_group.get(4) {
Some(description_capture) => description_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get distributor from line:\n {}", flatpak_line.to_string()))
};
let description = match capture_group.get(5) {
Some(description_capture) => description_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get description from line:\n {}", flatpak_line.to_string()))
};
Ok(SearchResult{
name: name.clone(),
publisher: "UNKNOWN".to_string(),
version,
source,
description,
lv_distance: levenshtein(query_name, &name)
})
}
///
/// Vector of results, either a struct representing the result,
/// or an error wrapping a line that failed to parse
///
fn snap_line_to_result(snap_line: &str, query_name: &str) -> Result<SearchResult, String> {
lazy_static! {
static ref SNAP_LINE_REGEX: Regex = Regex::new(r"^(\w+)\s+([\w\.]+)\s+([^\s\t]+)\s+([^\s\t]+)\s(.+)$").unwrap();
}
let capture_group = match SNAP_LINE_REGEX.captures(snap_line) {
Some(_capture_group) => _capture_group,
_ => return Err(format!("Couldn't parse: {}", snap_line.to_string()))
};
let name = match capture_group.get(1) {
Some(name_capture) => name_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get name from line:\n {}", snap_line.to_string()))
};
let version = match capture_group.get(2) {
Some(version_capture) => version_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get version from line:\n {}", snap_line.to_string()))
};
let publisher = match capture_group.get(3) {
Some(publisher_capture) => publisher_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get publisher from line:\n {}", snap_line.to_string()))
};
let description = match capture_group.get(4) {
Some(description_capture) => description_capture.as_str().to_string(),
_ => return Err(format!("Couldn't get description from line:\n {}", snap_line.to_string()))
};
Ok(SearchResult{
name: name.clone(),
publisher,
version,
source: "SNAP".to_string(),
description,
lv_distance: levenshtein(query_name, &name)
})
}
|
use std::sync::Arc;
use crate::graphics::Format;
use crate::graphics::Backend;
use std::hash::Hasher;
use std::hash::Hash;
use super::BindingFrequency;
#[derive(Debug, Clone, Copy, PartialEq, Hash, Eq)]
pub enum InputRate {
PerVertex,
PerInstance
}
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct ShaderInputElement {
pub input_assembler_binding: u32,
pub location_vk_mtl: u32,
pub semantic_name_d3d: String,
pub semantic_index_d3d: u32,
pub offset: usize,
pub format: Format
}
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct InputAssemblerElement {
pub binding: u32,
pub input_rate: InputRate,
pub stride: usize
}
impl Default for ShaderInputElement {
fn default() -> ShaderInputElement {
ShaderInputElement {
input_assembler_binding: 0,
location_vk_mtl: 0,
semantic_name_d3d: String::new(),
semantic_index_d3d: 0,
offset: 0,
format: Format::Unknown,
}
}
}
impl Default for InputAssemblerElement {
fn default() -> InputAssemblerElement {
InputAssemblerElement {
binding: 0,
input_rate: InputRate::PerVertex,
stride: 0
}
}
}
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct VertexLayoutInfo<'a> {
pub shader_inputs: &'a [ShaderInputElement],
pub input_assembler: &'a [InputAssemblerElement]
}
// ignore input assembler for now and always use triangle lists
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FillMode {
Fill,
Line
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CullMode {
None,
Front,
Back
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FrontFace {
CounterClockwise,
Clockwise
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SampleCount {
Samples1,
Samples2,
Samples4,
Samples8
}
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
pub struct RasterizerInfo {
pub fill_mode: FillMode,
pub cull_mode: CullMode,
pub front_face: FrontFace,
pub sample_count: SampleCount
}
impl Default for RasterizerInfo {
fn default() -> Self {
RasterizerInfo {
fill_mode: FillMode::Fill,
cull_mode: CullMode::Back,
front_face: FrontFace::Clockwise,
sample_count: SampleCount::Samples1
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompareFunc {
Never,
Less,
LessEqual,
Equal,
NotEqual,
GreaterEqual,
Greater,
Always
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StencilOp {
Keep,
Zero,
Replace,
IncreaseClamp,
DecreaseClamp,
Invert,
Increase,
Decrease
}
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct StencilInfo {
pub fail_op: StencilOp,
pub depth_fail_op: StencilOp,
pub pass_op: StencilOp,
pub func: CompareFunc
}
impl Default for StencilInfo {
fn default() -> Self {
StencilInfo {
fail_op: StencilOp::Keep,
depth_fail_op: StencilOp::Keep,
pass_op: StencilOp::Keep,
func: CompareFunc::Always
}
}
}
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct DepthStencilInfo {
pub depth_test_enabled: bool,
pub depth_write_enabled: bool,
pub depth_func: CompareFunc,
pub stencil_enable: bool,
pub stencil_read_mask: u8,
pub stencil_write_mask: u8,
pub stencil_front: StencilInfo,
pub stencil_back: StencilInfo
}
impl Default for DepthStencilInfo {
fn default() -> Self {
DepthStencilInfo {
depth_test_enabled: true,
depth_write_enabled: true,
depth_func: CompareFunc::Less,
stencil_enable: false,
stencil_read_mask: 0,
stencil_write_mask: 0,
stencil_front: StencilInfo::default(),
stencil_back: StencilInfo::default()
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LogicOp {
Clear,
Set,
Copy,
CopyInverted,
Noop,
Invert,
And,
Nand,
Or,
Nor,
Xor,
Equivalent,
AndReversed,
AndInverted,
OrReverse,
OrInverted
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BlendFactor {
Zero,
One,
SrcColor,
OneMinusSrcColor,
DstColor,
OneMinusDstColor,
SrcAlpha,
OneMinusSrcAlpha,
DstAlpha,
OneMinusDstAlpha,
ConstantColor,
OneMinusConstantColor,
SrcAlphaSaturate,
Src1Color,
OneMinusSrc1Color,
Src1Alpha,
OneMinusSrc1Alpha
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BlendOp {
Add,
Subtract,
ReverseSubtract,
Min,
Max
}
#[derive(Debug, Clone)]
pub struct BlendInfo<'a> {
pub alpha_to_coverage_enabled: bool,
pub logic_op_enabled: bool,
pub logic_op: LogicOp,
pub attachments: &'a [AttachmentBlendInfo],
pub constants: [f32; 4]
}
impl Hash for BlendInfo<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.alpha_to_coverage_enabled.hash(state);
self.logic_op_enabled.hash(state);
self.logic_op.hash(state);
self.attachments.hash(state);
let constants_data: &[u32] = unsafe { std::slice::from_raw_parts(self.constants.as_ptr() as *const u32, self.constants.len()) };
constants_data.hash(state);
}
}
impl PartialEq for BlendInfo<'_> {
fn eq(&self, other: &Self) -> bool {
self.alpha_to_coverage_enabled == other.alpha_to_coverage_enabled
&& self.logic_op_enabled == other.logic_op_enabled
&& self.logic_op == other.logic_op
&& self.attachments == other.attachments
&& (self.constants[0] - other.constants[0]).abs() < 0.01f32
&& (self.constants[1] - other.constants[1]).abs() < 0.01f32
&& (self.constants[2] - other.constants[2]).abs() < 0.01f32
&& (self.constants[3] - other.constants[3]).abs() < 0.01f32
}
}
impl Eq for BlendInfo<'_> {}
impl Default for BlendInfo<'_> {
fn default() -> Self {
BlendInfo {
alpha_to_coverage_enabled: false,
logic_op_enabled: false,
logic_op: LogicOp::And,
attachments: &[],
constants: [0f32, 0f32, 0f32, 0f32]
}
}
}
bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ColorComponents : u8 {
const RED = 0b0001;
const GREEN = 0b0010;
const BLUE = 0b0100;
const ALPHA = 0b1000;
}
}
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct AttachmentBlendInfo {
pub blend_enabled: bool,
pub src_color_blend_factor: BlendFactor,
pub dst_color_blend_factor: BlendFactor,
pub color_blend_op: BlendOp,
pub src_alpha_blend_factor: BlendFactor,
pub dst_alpha_blend_factor: BlendFactor,
pub alpha_blend_op: BlendOp,
pub write_mask: ColorComponents
}
impl Default for AttachmentBlendInfo {
fn default() -> Self {
AttachmentBlendInfo {
blend_enabled: false,
src_color_blend_factor: BlendFactor::ConstantColor,
dst_color_blend_factor: BlendFactor::ConstantColor,
color_blend_op: BlendOp::Add,
src_alpha_blend_factor: BlendFactor::ConstantColor,
dst_alpha_blend_factor: BlendFactor::ConstantColor,
alpha_blend_op: BlendOp::Add,
write_mask: ColorComponents::RED | ColorComponents::GREEN | ColorComponents::BLUE | ColorComponents::ALPHA
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ShaderType {
VertexShader = 0,
FragmentShader,
GeometryShader,
TessellationControlShader,
TessellationEvaluationShader,
ComputeShader,
RayGen,
RayMiss,
RayClosestHit,
// TODO add mesh shaders (?)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum PrimitiveType {
Triangles,
TriangleStrip,
Lines,
LineStrip,
Points
}
pub trait Shader {
fn shader_type(&self) -> ShaderType;
}
#[derive(Hash, Eq, PartialEq)]
pub struct GraphicsPipelineInfo<'a, B: Backend> {
pub vs: &'a Arc<B::Shader>,
pub fs: Option<&'a Arc<B::Shader>>,
pub vertex_layout: VertexLayoutInfo<'a>,
pub rasterizer: RasterizerInfo,
pub depth_stencil: DepthStencilInfo,
pub blend: BlendInfo<'a>,
pub primitive_type: PrimitiveType
}
impl<B: Backend> Clone for GraphicsPipelineInfo<'_, B> {
fn clone(&self) -> Self {
Self {
vs: self.vs,
fs: self.fs,
vertex_layout: self.vertex_layout.clone(),
rasterizer: self.rasterizer.clone(),
depth_stencil: self.depth_stencil.clone(),
blend: self.blend.clone(),
primitive_type: self.primitive_type
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum BindingType {
StorageBuffer,
StorageTexture,
SampledTexture,
ConstantBuffer,
Sampler,
TextureAndSampler
}
#[derive(Debug)]
pub struct BindingInfo<'a> {
pub name: &'a str,
pub binding_type: BindingType
}
pub trait ComputePipeline {
fn binding_info(&self, set: BindingFrequency, slot: u32) -> Option<BindingInfo>;
}
|
mod channel;
mod info;
mod set;
use crate::services::config::Config as BotConfig;
use crate::services::database::guild::DBGuild;
use self::channel::CHANNEL_COMMAND;
use self::info::CONFIG_INFO_COMMAND;
use self::set::SET_COMMAND;
use crate::extensions::context::ClientContextExt;
use crate::extensions::MessageExt;
use anyhow::Result;
use serenity::{framework::standard::macros::group, model::channel::Message, prelude::*};
pub fn format_setting(setting: bool, name: &str, config: &BotConfig) -> String {
let emote = if setting {
&config.emotes.enabled
} else {
&config.emotes.disabled
};
format!("{} **{}**\n", emote, name)
}
async fn send_settings(guild_db: &DBGuild, msg: &Message, ctx: &Context) -> Result<()> {
let config = ctx.get_config().await;
let mut settings: String = "".to_string();
settings.push_str(format_setting(guild_db.launches, "Launches", &config).as_str());
settings.push_str(
format_setting(
guild_db.apod,
"APOD (Astronomy Picture of the Day)",
&config,
)
.as_str(),
);
settings.push_str(format_setting(guild_db.events, "Events", &config).as_str());
msg.reply_success(ctx, settings).await?;
Ok(())
}
#[group()]
#[prefixes("config", "update")]
#[commands(channel, set)]
#[default_command(config_info)]
#[required_permissions(MANAGE_CHANNELS)]
pub struct Config;
|
// Copyright 2017 Dasein Phaos aka. Luxko
//
// 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.
//! Various types of safe textures
use super::raw::*;
use super::traits::*;
use device::Device;
use error::WinError;
use format::DxgiFormat;
#[derive(Debug)]
pub struct DefaultTex2D {
raw: RawResource,
width: u64,
height: u32,
mip_levels: u16,
format: DxgiFormat,
}
impl DefaultTex2D {
/// intial state is generic read
#[inline]
pub fn new(
device: &mut Device, width: u64, height: u32,
mip_levels: u16, format: DxgiFormat
) -> Result<DefaultTex2D, WinError> {
let raw = device.create_committed_resource(
&Default::default(),
Default::default(), // TODO: check if additional denies helps?
&super::description::ResourceDesc::tex2d(
width, height, 1, mip_levels, format,
Default::default(), Default::default()
),
Default::default() // TODO: other initial states?
)?;
Ok(DefaultTex2D{raw, width, height, mip_levels, format})
}
}
impl_as_raw!(Resource, DefaultTex2D, RawResource);
unsafe impl Texture for DefaultTex2D {
#[inline]
fn get_format(&mut self) -> ::format::DxgiFormat {
self.format
}
}
unsafe impl Tex2D for DefaultTex2D {
#[inline]
fn get_width(&mut self) -> u64 {
self.width
}
#[inline]
fn get_height(&mut self) -> u32 {
self.height
}
}
unsafe impl GpuOnly for DefaultTex2D {}
unsafe impl AllowShaderResource for DefaultTex2D {}
#[derive(Debug)]
pub struct DsableTex2D {
raw: RawResource,
width: u64,
height: u32,
mip_levels: u16,
format: DxgiFormat,
}
impl DsableTex2D {
/// intial state is depth write
#[inline]
pub fn new(
device: &mut Device, width: u64, height: u32,
mip_levels: u16, format: DxgiFormat
) -> Result<DsableTex2D, WinError> {
debug_assert!(
format == ::format::DXGI_FORMAT_D16_UNORM ||
format == ::format::DXGI_FORMAT_D32_FLOAT ||
format == ::format::DXGI_FORMAT_D24_UNORM_S8_UINT ||
format == ::format::DXGI_FORMAT_D32_FLOAT_S8X24_UINT
);
let raw = device.create_committed_resource(
&Default::default(),
Default::default(), // TODO: check if additional denies helps?
&super::description::ResourceDesc::tex2d(
width, height, 1, mip_levels, format,
super::description::ResourceFlags::ALLOW_DEPTH_STENCIL,
Default::default()
),
super::ResourceStates::DEPTH_WRITE // TODO: other initial states?
)?;
Ok(DsableTex2D{raw, width, height, mip_levels, format})
}
}
impl_as_raw!(Resource, DsableTex2D, RawResource);
unsafe impl Texture for DsableTex2D {
#[inline]
fn get_format(&mut self) -> ::format::DxgiFormat {
self.format
}
}
unsafe impl Tex2D for DsableTex2D {
#[inline]
fn get_width(&mut self) -> u64 {
self.width
}
#[inline]
fn get_height(&mut self) -> u32 {
self.height
}
}
unsafe impl GpuOnly for DsableTex2D {}
unsafe impl AllowShaderResource for DsableTex2D {}
unsafe impl AllowDepthStencil for DsableTex2D {}
#[derive(Debug)]
pub struct RenderableTex2D {
raw: RawResource,
width: u64,
height: u32,
mip_levels: u16,
format: DxgiFormat,
}
impl RenderableTex2D {
/// intial state is generic read
#[inline]
pub fn new(
device: &mut Device, width: u64, height: u32,
mip_levels: u16, format: DxgiFormat
) -> Result<RenderableTex2D, WinError> {
let raw = device.create_committed_resource(
&Default::default(),
Default::default(), // TODO: check if additional denies helps?
&super::description::ResourceDesc::tex2d(
width, height, 1, mip_levels, format,
super::description::ResourceFlags::ALLOW_RENDER_TARGET,
Default::default()
),
Default::default() // TODO: other initial states?
)?;
Ok(RenderableTex2D{raw, width, height, mip_levels, format})
}
}
impl_as_raw!(Resource, RenderableTex2D, RawResource);
unsafe impl Texture for RenderableTex2D {
#[inline]
fn get_format(&mut self) -> ::format::DxgiFormat {
self.format
}
}
unsafe impl Tex2D for RenderableTex2D {
#[inline]
fn get_width(&mut self) -> u64 {
self.width
}
#[inline]
fn get_height(&mut self) -> u32 {
self.height
}
}
unsafe impl GpuOnly for RenderableTex2D {}
unsafe impl AllowShaderResource for RenderableTex2D {}
unsafe impl AllowRenderTarget for RenderableTex2D {}
// TODO: placed textures, see https://msdn.microsoft.com/en-us/library/windows/desktop/dn788680(v=vs.85).aspx
|
use crate::types::{Size2i, Vector2i, Rgb8};
use std::fmt::*;
#[derive(Debug)]
pub struct Image {
pub size: Size2i,
pub data: Vec<u8>
}
impl Image {
pub fn new(size: Size2i) -> Image {
let mut data = Vec::<u8>::new();
let data_size = (size.width()*size.height()*3) as usize;
data.resize(data_size, 0);
Image::new_with_data(size, data)
}
pub fn new_with_data(size: Size2i, data: Vec<u8>) -> Image {
Image {
size,
data
}
}
/*
origin: upper left corner
*/
pub fn set_pixel(&mut self, position: Vector2i, rgb: Rgb8) {
assert!(position.y >= 0 && position.y < self.size.height());
assert!(position.x >= 0 && position.x < self.size.width());
let image_size = self.size.height() * self.size.width();
let pixel_index = position.y * self.size.width() + position.x;
// self.data[(0*image_size+pixel_index) as usize] = rgb.r;
// self.data[(1*image_size+pixel_index) as usize] = rgb.g;
// self.data[(2*image_size+pixel_index) as usize] = rgb.b;
self.data[(pixel_index*3+0) as usize] = rgb.r;
self.data[(pixel_index*3+1) as usize] = rgb.g;
self.data[(pixel_index*3+2) as usize] = rgb.b;
}
}
|
use crate::{
core::{Part, Solution},
utils::string::StrUtils,
};
pub fn solve(part: Part, input: String) -> String {
match part {
Part::P1 => Day05::solve_part_one(input),
Part::P2 => Day05::solve_part_two(input),
}
}
pub struct Day05;
impl Solution for Day05 {
fn solve_part_one(input: String) -> String {
let paragraphs = input.paragraphs().collect::<Vec<_>>();
let mut stacks = parse_stacks(paragraphs[0]);
for instruction in paragraphs[1].lines() {
let (count, from, to) = parse_moves(instruction);
let old_stack = &mut stacks[from];
let items = old_stack.split_off(old_stack.len() - count);
let new_stack = &mut stacks[to];
stack_crates(new_stack, items, 9000);
}
peek_top_crates(&stacks)
}
fn solve_part_two(input: String) -> String {
let paragraphs = input.paragraphs().collect::<Vec<_>>();
let mut stacks = parse_stacks(paragraphs[0]);
for instruction in paragraphs[1].lines() {
let (count, from, to) = parse_moves(instruction);
let old_stack = &mut stacks[from];
let items = old_stack.split_off(old_stack.len() - count);
let new_stack = &mut stacks[to];
stack_crates(new_stack, items, 9001);
}
peek_top_crates(&stacks)
}
}
fn parse_moves(instruction: &str) -> (usize, usize, usize) {
let moves: Vec<usize> = instruction
.split_whitespace()
.filter_map(|w| match w.parse::<usize>() {
Ok(n) => Some(n),
Err(_) => None,
})
.collect();
(moves[0], moves[1] - 1, moves[2] - 1)
}
fn parse_stacks(crates: &str) -> Vec<Vec<char>> {
let mut first = true;
let mut stacks = Vec::new();
for line in crates.lines().rev() {
if first {
first = false;
for _ in line.chars().enumerate().filter(|&(i, _)| i % 4 == 1) {
stacks.push(Vec::new());
}
} else {
let chars: Vec<char> = line
.chars()
.enumerate()
.filter(|&(i, _)| i % 4 == 1)
.map(|(_, v)| v)
.collect();
for (i, c) in chars.into_iter().enumerate() {
if !c.is_whitespace() {
stacks[i].push(c);
}
}
}
}
stacks
}
fn stack_crates(stack: &mut Vec<char>, crates: Vec<char>, model: u32) -> &mut Vec<char> {
match model {
9000 => {
for item in crates.iter().rev() {
stack.push(item.to_owned());
}
}
9001 => {
for item in crates {
stack.push(item);
}
}
_ => (),
}
stack
}
fn peek_top_crates(stacks: &Vec<Vec<char>>) -> String {
stacks
.into_iter()
.map(|stack| stack.last().unwrap())
.collect()
}
|
mod with_registered_name;
use super::*;
#[test]
fn without_supported_item_errors_badarg() {
with_process_arc(|arc_process| {
TestRunner::new(Config::with_source_file(file!()))
.run(&unsupported_item_atom(), |item| {
let pid = arc_process.pid_term();
prop_assert_badarg!(
result(&arc_process, pid, item),
"supported items are backtrace, binary, catchlevel, current_function, \
current_location, current_stacktrace, dictionary, error_handler, \
garbage_collection, garbage_collection_info, group_leader, heap_size, \
initial_call, links, last_calls, memory, message_queue_len, messages, \
min_heap_size, min_bin_vheap_size, monitored_by, monitors, \
message_queue_data, priority, reductions, registered_name, \
sequential_trace_token, stack_size, status, suspending, \
total_heap_size, trace, trap_exit"
);
Ok(())
})
.unwrap();
});
}
fn unsupported_item_atom() -> BoxedStrategy<Term> {
strategy::atom()
.prop_filter("Item cannot be supported", |atom| match atom.name() {
"registered_name" => false,
_ => true,
})
.prop_map(|atom| atom.encode().unwrap())
.boxed()
}
|
use super::*;
use crate::parser::Parser;
use std::str;
// This gives us a colorful diff.
#[cfg(test)]
use pretty_assertions::assert_eq;
fn format_helper(golden: &str) {
let file = Parser::new(golden).parse_file("".to_string());
let mut fmt = Formatter::new(golden.len());
fmt.format_file(&file, true);
let (ouput, _) = fmt.output();
assert_eq!(golden, ouput);
}
#[test]
fn binary_op() {
format_helper("1 + 1 - 2");
format_helper("1 * 1 / 2");
format_helper("2 ^ 4");
format_helper("1 * (1 / 2)");
}
#[test]
fn funcs() {
format_helper(
r#"(r) =>
(r.user == "user1")"#,
);
format_helper(
r#"add = (a, b) =>
(a + b)"#,
); // decl
format_helper("add(a: 1, b: 2)"); // call
format_helper(
r#"foo = (arg=[]) =>
(1)"#,
); // nil value as default
format_helper(
r#"foo = (arg=[1, 2]) =>
(1)"#,
); // none nil value as default
}
#[test]
fn object() {
format_helper("{a: 1, b: {c: 11, d: 12}}");
format_helper("{foo with a: 1, b: {c: 11, d: 12}}"); // with
format_helper("{a, b, c}"); // implicit key object literal
format_helper(r#"{"a": 1, "b": 2}"#); // object with string literal keys
format_helper(r#"{"a": 1, b: 2}"#); // object with mixed keys
}
#[test]
fn member() {
format_helper("object.property"); // member ident
format_helper(r#"object["property"]"#); // member string literal
}
#[test]
fn array() {
format_helper(
r#"a = [1, 2, 3]
a[i]"#,
);
}
#[test]
fn conditional() {
format_helper("if a then b else c");
format_helper(r#"if not a or b and c then 2 / (3 * 2) else obj.a(par: "foo")"#);
}
#[test]
fn return_expr() {
format_helper("return 42");
}
#[test]
fn option() {
format_helper("option foo = {a: 1}");
format_helper(r#"option alert.state = "Warning""#); // qualified
}
#[test]
fn vars() {
format_helper("0.1"); // float
format_helper("100000000.0"); // integer float
format_helper("365d"); // duration
format_helper("1d1m1s"); // duration_multiple
format_helper("2018-05-22T19:53:00Z"); // time
format_helper("2018-05-22T19:53:01+07:00"); // zone
format_helper("2018-05-22T19:53:23.09012Z"); // nano sec
format_helper("2018-05-22T19:53:01.09012-07:00"); // nano with zone
format_helper(r#"/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/"#); // regexp
format_helper(r#"/^http:\/\/\w+\.com$/"#); // regexp_escape
}
#[test]
fn block() {
format_helper(
r#"foo = () => {
foo(f: 1)
1 + 1
}"#,
);
}
#[test]
fn str_lit() {
format_helper(r#""foo""#);
format_helper(
r#""this is
a string
with multiple lines""#,
); // multi lines
format_helper(r#""foo \\ \" \r\n""#); // with escape
format_helper(r#""\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e""#); // with byte
}
#[test]
fn package_import() {
format_helper(
r#"package foo
"#,
); // package
format_helper(
r#"import "path/foo"
import bar "path/bar""#,
); // imports
format_helper(
r#"import foo "path/foo"
foo.from(bucket: "testdb")
|> range(start: 2018-05-20T19:53:26Z)"#,
); // no_package
format_helper(
r#"package foo
from(bucket: "testdb")
|> range(start: 2018-05-20T19:53:26Z)"#,
); // no_imports
format_helper(
r#"package foo
import "path/foo"
import bar "path/bar"
from(bucket: "testdb")
|> range(start: 2018-05-20T19:53:26Z)"#,
); // package import
}
#[test]
fn simple() {
format_helper(
r#"from(bucket: "testdb")
|> range(start: 2018-05-20T19:53:26Z)
|> filter(fn: (r) =>
(r.name =~ /.*0/))
|> group(by: ["_measurement", "_start"])
|> map(fn: (r) =>
({_time: r._time, io_time: r._value}))"#,
);
}
#[test]
fn medium() {
format_helper(
r#"from(bucket: "testdb")
|> range(start: 2018-05-20T19:53:26Z)
|> filter(fn: (r) =>
(r.name =~ /.*0/))
|> group(by: ["_measurement", "_start"])
|> map(fn: (r) =>
({_time: r1._time, io_time: r._value}))"#,
)
}
#[test]
fn complex() {
format_helper(
r#"left = from(bucket: "test")
|> range(start: 2018-05-22T19:53:00Z, stop: 2018-05-22T19:55:00Z)
|> drop(columns: ["_start", "_stop"])
|> filter(fn: (r) =>
(r.user == "user1"))
|> group(by: ["user"])
right = from(bucket: "test")
|> range(start: 2018-05-22T19:53:00Z, stop: 2018-05-22T19:55:00Z)
|> drop(columns: ["_start", "_stop"])
|> filter(fn: (r) =>
(r.user == "user2"))
|> group(by: ["_measurement"])
join(tables: {left: left, right: right}, on: ["_time", "_measurement"])"#,
);
}
#[test]
fn option_complete() {
format_helper(
r#"option task = {
name: "foo",
every: 1h,
delay: 10m,
cron: "02***",
retry: 5,
}
from(bucket: "test")
|> range(start: 2018-05-22T19:53:26Z)
|> window(every: task.every)
|> group(by: ["_field", "host"])
|> sum()
|> to(bucket: "test", tagColumns: ["host", "_field"])"#,
)
}
#[test]
fn functions_complete() {
format_helper(
r#"foo = () =>
(from(bucket: "testdb"))
bar = (x=<-) =>
(x
|> filter(fn: (r) =>
(r.name =~ /.*0/)))
baz = (y=<-) =>
(y
|> map(fn: (r) =>
({_time: r._time, io_time: r._value})))
foo()
|> bar()
|> baz()"#,
)
}
#[test]
fn multi_indent() {
format_helper(
r#"_sortLimit = (n, desc, columns=["_value"], tables=<-) =>
(tables
|> sort(columns: columns, desc: desc)
|> limit(n: n))
_highestOrLowest = (n, _sortLimit, reducer, columns=["_value"], by, tables=<-) =>
(tables
|> group(by: by)
|> reducer()
|> group(none: true)
|> _sortLimit(n: n, columns: columns))
highestAverage = (n, columns=["_value"], by, tables=<-) =>
(tables
|> _highestOrLowest(
n: n,
columns: columns,
by: by,
reducer: (tables=<-) =>
(tables
|> mean(columns: [columns[0]])),
_sortLimit: top,
))"#,
)
}
|
#[doc = "Reader of register PLLSAI2CFGR"]
pub type R = crate::R<u32, super::PLLSAI2CFGR>;
#[doc = "Writer for register PLLSAI2CFGR"]
pub type W = crate::W<u32, super::PLLSAI2CFGR>;
#[doc = "Register PLLSAI2CFGR `reset()`'s with value 0x1000"]
impl crate::ResetValue for super::PLLSAI2CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x1000
}
}
#[doc = "Reader of field `PLLSAI2R`"]
pub type PLLSAI2R_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PLLSAI2R`"]
pub struct PLLSAI2R_W<'a> {
w: &'a mut W,
}
impl<'a> PLLSAI2R_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 25)) | (((value as u32) & 0x03) << 25);
self.w
}
}
#[doc = "Reader of field `PLLSAI2REN`"]
pub type PLLSAI2REN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PLLSAI2REN`"]
pub struct PLLSAI2REN_W<'a> {
w: &'a mut W,
}
impl<'a> PLLSAI2REN_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 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `PLLSAI2P`"]
pub type PLLSAI2P_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PLLSAI2P`"]
pub struct PLLSAI2P_W<'a> {
w: &'a mut W,
}
impl<'a> PLLSAI2P_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `PLLSAI2PEN`"]
pub type PLLSAI2PEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PLLSAI2PEN`"]
pub struct PLLSAI2PEN_W<'a> {
w: &'a mut W,
}
impl<'a> PLLSAI2PEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `PLLSAI2N`"]
pub type PLLSAI2N_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PLLSAI2N`"]
pub struct PLLSAI2N_W<'a> {
w: &'a mut W,
}
impl<'a> PLLSAI2N_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 8)) | (((value as u32) & 0x7f) << 8);
self.w
}
}
#[doc = "Reader of field `PLLSAI2PDIV`"]
pub type PLLSAI2PDIV_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PLLSAI2PDIV`"]
pub struct PLLSAI2PDIV_W<'a> {
w: &'a mut W,
}
impl<'a> PLLSAI2PDIV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 27)) | (((value as u32) & 0x1f) << 27);
self.w
}
}
impl R {
#[doc = "Bits 25:26 - PLLSAI2 division factor for PLLADC2CLK (ADC clock)"]
#[inline(always)]
pub fn pllsai2r(&self) -> PLLSAI2R_R {
PLLSAI2R_R::new(((self.bits >> 25) & 0x03) as u8)
}
#[doc = "Bit 24 - PLLSAI2 PLLADC2CLK output enable"]
#[inline(always)]
pub fn pllsai2ren(&self) -> PLLSAI2REN_R {
PLLSAI2REN_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 17 - SAI1PLL division factor for PLLSAI2CLK (SAI1 or SAI2 clock)"]
#[inline(always)]
pub fn pllsai2p(&self) -> PLLSAI2P_R {
PLLSAI2P_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16 - SAI2PLL PLLSAI2CLK output enable"]
#[inline(always)]
pub fn pllsai2pen(&self) -> PLLSAI2PEN_R {
PLLSAI2PEN_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bits 8:14 - SAI2PLL multiplication factor for VCO"]
#[inline(always)]
pub fn pllsai2n(&self) -> PLLSAI2N_R {
PLLSAI2N_R::new(((self.bits >> 8) & 0x7f) as u8)
}
#[doc = "Bits 27:31 - PLLSAI2 division factor for PLLSAI2CLK"]
#[inline(always)]
pub fn pllsai2pdiv(&self) -> PLLSAI2PDIV_R {
PLLSAI2PDIV_R::new(((self.bits >> 27) & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 25:26 - PLLSAI2 division factor for PLLADC2CLK (ADC clock)"]
#[inline(always)]
pub fn pllsai2r(&mut self) -> PLLSAI2R_W {
PLLSAI2R_W { w: self }
}
#[doc = "Bit 24 - PLLSAI2 PLLADC2CLK output enable"]
#[inline(always)]
pub fn pllsai2ren(&mut self) -> PLLSAI2REN_W {
PLLSAI2REN_W { w: self }
}
#[doc = "Bit 17 - SAI1PLL division factor for PLLSAI2CLK (SAI1 or SAI2 clock)"]
#[inline(always)]
pub fn pllsai2p(&mut self) -> PLLSAI2P_W {
PLLSAI2P_W { w: self }
}
#[doc = "Bit 16 - SAI2PLL PLLSAI2CLK output enable"]
#[inline(always)]
pub fn pllsai2pen(&mut self) -> PLLSAI2PEN_W {
PLLSAI2PEN_W { w: self }
}
#[doc = "Bits 8:14 - SAI2PLL multiplication factor for VCO"]
#[inline(always)]
pub fn pllsai2n(&mut self) -> PLLSAI2N_W {
PLLSAI2N_W { w: self }
}
#[doc = "Bits 27:31 - PLLSAI2 division factor for PLLSAI2CLK"]
#[inline(always)]
pub fn pllsai2pdiv(&mut self) -> PLLSAI2PDIV_W {
PLLSAI2PDIV_W { w: self }
}
}
|
use crate::types::{Array, Str};
use crate::value::{FromValue, ToValue, Value};
macro_rules! value_i {
($t:ty) => {
impl ToValue for $t {
fn to_value(&self) -> $crate::Value {
$crate::Value::i64(self.clone() as i64)
}
}
impl FromValue for $t {
fn from_value(v: $crate::Value) -> $t {
v.i64_val() as $t
}
}
};
($($t:ty),*) => {
$(value_i!($t);)*
}
}
macro_rules! value_f {
($t:ty) => {
impl ToValue for $t {
fn to_value(&self) -> $crate::Value {
$crate::Value::f64(self.clone().into())
}
}
impl FromValue for $t {
fn from_value(v: $crate::Value) -> $t {
v.f64_val() as $t
}
}
};
($($t:ty),*) => {
$(value_f!($t);)*
}
}
value_i!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize);
value_f!(f32, f64);
impl ToValue for String {
fn to_value(&self) -> Value {
let s = Str::from(self.as_str());
Value::from(s)
}
}
impl FromValue for String {
fn from_value(v: Value) -> String {
let s = Str::from(v);
String::from(s.as_str())
}
}
impl<V: ToValue> ToValue for Vec<V> {
fn to_value(&self) -> Value {
let tmp: Vec<Value> = self.iter().map(|x| x.to_value()).collect();
crate::array!(_ tmp).into()
}
}
impl<V: FromValue> FromValue for Vec<V> {
fn from_value(v: Value) -> Vec<V> {
let arr = Array::from(v);
let mut dst = Vec::with_capacity(arr.len());
for i in 0..arr.len() {
dst.push(V::from_value(arr.get(i).unwrap()))
}
dst
}
}
|
pub struct Solution;
impl Solution {
pub fn word_pattern(pattern: String, str: String) -> bool {
use std::collections::hash_map::Entry;
use std::collections::HashMap;
let mut letter2word = HashMap::new();
let mut word2letter = HashMap::new();
let mut p = 0;
let mut i = 0;
while p < pattern.len() && i < str.len() {
let mut j = i;
while j < str.len() && str.as_bytes()[j] != b' ' {
j += 1;
}
let letter = pattern.as_bytes()[p];
let word = &str[i..j];
match letter2word.entry(letter) {
Entry::Vacant(e) => {
e.insert(word);
}
Entry::Occupied(e) => {
if e.get() != &word {
return false;
}
}
}
match word2letter.entry(word) {
Entry::Vacant(e) => {
e.insert(letter);
}
Entry::Occupied(e) => {
if e.get() != &letter {
return false;
}
}
}
p += 1;
i = j + 1;
}
p == pattern.len() && i >= str.len()
}
}
#[test]
fn test0290() {
fn case(pattern: &str, str: &str, want: bool) {
let got = Solution::word_pattern(pattern.to_string(), str.to_string());
assert_eq!(got, want);
}
case("abba", "dog cat cat dog", true);
case("abba", "dog cat cat fish", false);
case("aaaa", "dog cat cat dog", false);
case("abba", "dog dog dog dog", false);
}
|
use crate::{
conv,
device::Device,
native,
Backend as B,
GlContainer,
PhysicalDevice,
QueueFamily,
Starc,
};
use arrayvec::ArrayVec;
use glow::HasContext;
use hal::{adapter::Adapter, format as f, image, window};
use std::iter;
use wasm_bindgen::JsCast;
#[cfg(feature = "winit")]
use winit::{platform::web::WindowExtWebSys, window::Window};
#[derive(Clone, Debug)]
pub struct Swapchain {
pub(crate) extent: window::Extent2D,
pub(crate) fbos: ArrayVec<[native::RawFrameBuffer; 3]>,
}
impl window::Swapchain<B> for Swapchain {
unsafe fn acquire_image(
&mut self,
_timeout_ns: u64,
_semaphore: Option<&native::Semaphore>,
_fence: Option<&native::Fence>,
) -> Result<(window::SwapImageIndex, Option<window::Suboptimal>), window::AcquireError> {
// TODO: sync
Ok((0, None))
}
}
#[derive(Clone, Debug)]
pub struct Surface {
canvas: Starc<web_sys::HtmlCanvasElement>,
pub(crate) swapchain: Option<Swapchain>,
renderbuffer: Option<native::Renderbuffer>,
}
impl Surface {
pub fn from_canvas(canvas: web_sys::HtmlCanvasElement) -> Self {
Surface {
canvas: Starc::new(canvas),
swapchain: None,
renderbuffer: None,
}
}
pub fn from_raw_handle(has_handle: &impl raw_window_handle::HasRawWindowHandle) -> Self {
if let raw_window_handle::RawWindowHandle::Web(handle) = has_handle.raw_window_handle() {
let canvas = web_sys::window()
.and_then(|win| win.document())
.expect("Cannot get document")
.query_selector(&format!("canvas[data-raw-handle=\"{}\"]", handle.id))
.expect("Cannot query for canvas")
.expect("Canvas is not found")
.dyn_into()
.expect("Failed to downcast to canvas type");
Self::from_canvas(canvas)
} else {
unreachable!()
}
}
fn swapchain_formats(&self) -> Vec<f::Format> {
vec![f::Format::Rgba8Unorm, f::Format::Bgra8Unorm]
}
}
impl window::Surface<B> for Surface {
fn supports_queue_family(&self, _: &QueueFamily) -> bool {
true
}
fn capabilities(&self, _physical_device: &PhysicalDevice) -> window::SurfaceCapabilities {
let extent = hal::window::Extent2D {
width: self.canvas.width(),
height: self.canvas.height(),
};
window::SurfaceCapabilities {
present_modes: window::PresentMode::FIFO, //TODO
composite_alpha_modes: window::CompositeAlphaMode::OPAQUE, //TODO
image_count: 1 ..= 1,
current_extent: Some(extent),
extents: extent ..= extent,
max_image_layers: 1,
usage: image::Usage::COLOR_ATTACHMENT | image::Usage::TRANSFER_SRC,
}
}
fn supported_formats(&self, _physical_device: &PhysicalDevice) -> Option<Vec<f::Format>> {
Some(self.swapchain_formats())
}
}
impl window::PresentationSurface<B> for Surface {
type SwapchainImage = native::ImageView;
unsafe fn configure_swapchain(
&mut self,
device: &Device,
config: window::SwapchainConfig,
) -> Result<(), window::CreationError> {
let gl = &device.share.context;
if let Some(old) = self.swapchain.take() {
for fbo in old.fbos {
gl.delete_framebuffer(fbo);
}
}
if self.renderbuffer.is_none() {
self.renderbuffer = Some(gl.create_renderbuffer().unwrap());
}
let desc = conv::describe_format(config.format).unwrap();
gl.bind_renderbuffer(glow::RENDERBUFFER, self.renderbuffer);
gl.renderbuffer_storage(
glow::RENDERBUFFER,
desc.tex_internal,
config.extent.width as i32,
config.extent.height as i32,
);
let fbo = gl.create_framebuffer().unwrap();
gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(fbo));
gl.framebuffer_renderbuffer(
glow::READ_FRAMEBUFFER,
glow::COLOR_ATTACHMENT0,
glow::RENDERBUFFER,
self.renderbuffer,
);
self.swapchain = Some(Swapchain {
extent: config.extent,
fbos: iter::once(fbo).collect(),
});
Ok(())
}
unsafe fn unconfigure_swapchain(&mut self, device: &Device) {
let gl = &device.share.context;
if let Some(old) = self.swapchain.take() {
for fbo in old.fbos {
gl.delete_framebuffer(fbo);
}
}
if let Some(rbo) = self.renderbuffer.take() {
gl.delete_renderbuffer(rbo);
}
}
unsafe fn acquire_image(
&mut self,
_timeout_ns: u64,
) -> Result<(Self::SwapchainImage, Option<window::Suboptimal>), window::AcquireError> {
let image = native::ImageView::Renderbuffer(self.renderbuffer.unwrap());
Ok((image, None))
}
}
impl hal::Instance<B> for Surface {
fn create(_name: &str, _version: u32) -> Result<Self, hal::UnsupportedBackend> {
unimplemented!()
}
fn enumerate_adapters(&self) -> Vec<Adapter<B>> {
let adapter = PhysicalDevice::new_adapter((), GlContainer::from_canvas(&self.canvas)); // TODO: Move to `self` like native/window
vec![adapter]
}
unsafe fn create_surface(
&self,
_: &impl raw_window_handle::HasRawWindowHandle,
) -> Result<Surface, window::InitError> {
unimplemented!()
}
unsafe fn destroy_surface(&self, _surface: Surface) {
// TODO: Implement Surface cleanup
}
}
|
//! Interact with the file system using io-uring
use std::alloc::{alloc, dealloc, handle_alloc_error, Layout};
use std::cmp;
use std::fs;
use std::future::Future;
use std::io;
use std::mem::{self, ManuallyDrop};
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::path::Path;
use std::pin::Pin;
use std::ptr;
use std::slice;
use std::task::{Context, Poll};
use futures_core::ready;
use futures_io::{AsyncRead, AsyncBufRead, AsyncWrite, AsyncSeek};
use crate::drive::Drive;
use crate::drive::demo::DemoDriver;
use crate::engine::Engine;
use crate::event::{OpenAt, Cancellation};
use crate::Submission;
/// A file handle that runs on io-uring
pub struct File<D: Drive = DemoDriver<'static>> {
engine: Engine<Op, D>,
buf: Buffer,
pos: usize,
}
#[derive(Debug, Eq, PartialEq)]
enum Op {
Read,
Write,
Close,
}
/// A future representing an opening file.
pub struct Open<D: Drive = DemoDriver<'static>>(Submission<OpenAt, D>);
impl<D: Drive> Future for Open<D> {
type Output = io::Result<File<D>>;
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<File<D>>> {
let (_, driver, result) = ready!(self.inner().poll(ctx));
let fd = result? as i32;
Poll::Ready(Ok(File::from_fd(fd, driver)))
}
}
impl<D: Drive> Open<D> {
fn inner(self: Pin<&mut Self>) -> Pin<&mut Submission<OpenAt, D>> {
unsafe { Pin::map_unchecked_mut(self, |this| &mut this.0) }
}
}
/// A future representing a file being created.
pub struct Create<D: Drive = DemoDriver<'static>>(Submission<OpenAt, D>);
impl<D: Drive> Create<D> {
fn inner(self: Pin<&mut Self>) -> Pin<&mut Submission<OpenAt, D>> {
unsafe { Pin::map_unchecked_mut(self, |this| &mut this.0) }
}
}
impl<D: Drive> Future for Create<D> {
type Output = io::Result<File<D>>;
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<File<D>>> {
let (_, driver, result) = ready!(self.inner().poll(ctx));
let fd = result? as i32;
Poll::Ready(Ok(File::from_fd(fd, driver)))
}
}
impl File {
/// Open a file using the default driver
pub fn open(path: impl AsRef<Path>) -> Open {
File::open_on_driver(path, DemoDriver::default())
}
/// Create a new file using the default driver
pub fn create(path: impl AsRef<Path>) -> Create {
File::create_on_driver(path, DemoDriver::default())
}
}
impl<D: Drive> File<D> {
/// Open a file
pub fn open_on_driver(path: impl AsRef<Path>, driver: D) -> Open<D> {
let flags = libc::O_CLOEXEC | libc::O_RDONLY;
let event = OpenAt::new(path, libc::AT_FDCWD, flags, 0o666);
Open(Submission::new(event, driver))
}
/// Create a file
pub fn create_on_driver(path: impl AsRef<Path>, driver: D) -> Create<D> {
let flags = libc::O_CLOEXEC | libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC;
let event = OpenAt::new(path, libc::AT_FDCWD, flags, 0o666);
Create(Submission::new(event, driver))
}
/// Take an existing file and run its IO on an io-uring driver
pub fn run_on_driver(file: fs::File, driver: D) -> File<D> {
let file = ManuallyDrop::new(file);
File::from_fd(file.as_raw_fd(), driver)
}
fn from_fd(fd: RawFd, driver: D) -> File<D> {
File {
engine: Engine::new(fd, driver),
buf: Buffer::new(),
pos: 0,
}
}
/// Access any data that has been read into the buffer, but not consumed
///
/// This is similar to the fill_buf method from AsyncBufRead, but instead of performing IO if
/// the buffer is empty, it will just return an empty slice. This method can be used to copy
/// out any left over buffered data before closing or performing a write.
pub fn read_buffered(&self) -> &[u8] {
if self.engine.active() == Some(&Op::Read) && self.buf.data != ptr::null_mut() {
unsafe {
let ptr = self.buf.data.offset(self.buf.consumed as isize);
slice::from_raw_parts(ptr, (self.buf.read - self.buf.consumed) as usize)
}
} else { &[] }
}
fn cancel(self: Pin<&mut Self>) {
let (mut engine, buf, _) = self.split();
if let Some(active) = engine.active() {
let cancellation = match active {
Op::Read | Op::Write => buf.cancellation(),
Op::Close => Cancellation::null(),
};
engine.as_mut().cancel(cancellation);
engine.unset_active();
}
}
#[inline(always)]
fn split(self: Pin<&mut Self>) -> (Pin<&mut Engine<Op, D>>, &mut Buffer, &mut usize) {
unsafe {
let this = Pin::get_unchecked_mut(self);
(Pin::new_unchecked(&mut this.engine), &mut this.buf, &mut this.pos)
}
}
#[inline(always)]
fn engine(self: Pin<&mut Self>) -> Pin<&mut Engine<Op, D>> {
unsafe { Pin::map_unchecked_mut(self, |this| &mut this.engine) }
}
#[inline(always)]
fn buf(self: Pin<&mut Self>) -> Pin<&mut Buffer> {
unsafe { Pin::map_unchecked_mut(self, |this| &mut this.buf) }
}
#[inline(always)]
fn pos(self: Pin<&mut Self>) -> Pin<&mut usize> {
unsafe { Pin::map_unchecked_mut(self, |this| &mut this.pos) }
}
}
impl<D: Drive> AsyncRead for File<D> {
fn poll_read(mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut [u8])
-> Poll<io::Result<usize>>
{
let mut inner = ready!(self.as_mut().poll_fill_buf(ctx))?;
let len = io::Read::read(&mut inner, buf)?;
self.consume(len);
Poll::Ready(Ok(len))
}
}
impl<D: Drive> AsyncBufRead for File<D> {
fn poll_fill_buf(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
if !matches!(self.engine.active(), None | Some(&Op::Read)) {
println!("{:?}", self.engine.active());
self.as_mut().cancel();
}
let (mut engine, buf, pos) = self.split();
engine.as_mut().set_active(Op::Read);
if buf.consumed >= buf.read {
buf.read = unsafe {
ready!(engine.poll(ctx, |sqe, fd| sqe.prep_read(fd, buf.read_buf(), *pos)))? as u32
};
buf.consumed = 0;
*pos += buf.read as usize;
}
let consumed = buf.consumed as usize;
let read = buf.read as usize;
Poll::Ready(Ok(&buf.data()[consumed..read]))
}
fn consume(self: Pin<&mut Self>, amt: usize) {
self.buf().consume(amt);
}
}
impl<D: Drive> AsyncWrite for File<D> {
fn poll_write(mut self: Pin<&mut Self>, ctx: &mut Context<'_>, slice: &[u8]) -> Poll<io::Result<usize>> {
if !matches!(self.engine.active(), None | Some(&Op::Write)) {
self.as_mut().cancel();
}
let (mut engine, buf, pos) = self.split();
engine.as_mut().set_active(Op::Write);
if buf.written == 0 {
buf.written = io::Write::write(&mut buf.data_mut(), slice).unwrap() as u32;
}
let result = unsafe {
ready!(engine.poll(ctx, |sqe, fd| sqe.prep_write(fd, buf.write_buf(), *pos)))
};
if let &Ok(n) = &result {
*pos += n;
}
buf.written = 0;
Poll::Ready(result)
}
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
ready!(self.poll_write(ctx, &[]))?;
Poll::Ready(Ok(()))
}
fn poll_close(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
if !matches!(self.engine.active(), None | Some(&Op::Close)) {
self.as_mut().cancel();
}
let mut engine = self.engine();
engine.as_mut().set_active(Op::Close);
unsafe {
ready!(engine.poll(ctx, |sqe, fd| uring_sys::io_uring_prep_close(sqe.raw_mut(), fd)))?;
}
Poll::Ready(Ok(()))
}
}
impl<D: Drive> AsyncSeek for File<D> {
fn poll_seek(mut self: Pin<&mut Self>, _: &mut Context, pos: io::SeekFrom)
-> Poll<io::Result<u64>>
{
match pos {
io::SeekFrom::Start(n) => *self.as_mut().pos() = n as usize,
io::SeekFrom::Current(n) => {
*self.as_mut().pos() += if n < 0 { n.abs() } else { n } as usize;
}
io::SeekFrom::End(_) => {
const MSG: &str = "cannot seek to end of io-uring file";
return Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, MSG)))
}
}
Poll::Ready(Ok(self.pos as u64))
}
}
impl From<fs::File> for File {
fn from(file: fs::File) -> File {
File::run_on_driver(file, DemoDriver::default())
}
}
impl<D: Drive> From<File<D>> for fs::File {
fn from(mut file: File<D>) -> fs::File {
unsafe {
Pin::new_unchecked(&mut file).cancel();
let file = ManuallyDrop::new(file);
fs::File::from_raw_fd(file.engine.fd())
}
}
}
impl<D: Drive> Drop for File<D> {
fn drop(&mut self) {
unsafe {
if self.engine.active().is_some() {
Pin::new_unchecked(self).cancel();
} else {
libc::close(self.engine.fd());
}
}
}
}
struct Buffer {
data: *mut u8,
capacity: u32,
consumed: u32,
read: u32,
written: u32,
}
impl Buffer {
fn new() -> Buffer {
let capacity = 4096 * 2;
let data = ptr::null_mut();
Buffer {
data, capacity,
consumed: 0,
read: 0,
written: 0,
}
}
fn read_buf(&mut self) -> &mut [u8] {
&mut self.data_mut()[..]
}
fn write_buf(&mut self) -> &mut [u8] {
let written = self.written as usize;
&mut self.data_mut()[..written]
}
fn consume(&mut self, amt: usize) {
self.consumed = cmp::min(self.consumed + amt as u32, self.read);
}
fn data(&mut self) -> &[u8] {
let data = self.lazy_alloc();
unsafe { slice::from_raw_parts(data, self.capacity as usize) }
}
fn data_mut(&mut self) -> &mut [u8] {
let data = self.lazy_alloc();
unsafe { slice::from_raw_parts_mut(data, self.capacity as usize) }
}
fn cancellation(&mut self) -> Cancellation {
let data = mem::replace(&mut self.data, ptr::null_mut());
unsafe { Cancellation::buffer(data, self.capacity as usize) }
}
#[inline(always)]
fn lazy_alloc(&mut self) -> *mut u8 {
if self.data == ptr::null_mut() {
let layout = Layout::array::<u8>(self.capacity as usize).unwrap();
let ptr = unsafe { alloc(layout) };
if ptr == ptr::null_mut() {
handle_alloc_error(layout);
}
self.data = ptr;
}
self.data
}
}
unsafe impl Send for Buffer { }
unsafe impl Sync for Buffer { }
impl Drop for Buffer {
fn drop(&mut self) {
if self.data != ptr::null_mut() {
unsafe {
dealloc(self.data, Layout::array::<u8>(self.capacity as usize).unwrap());
}
}
}
}
|
use std;
import ctypes::*;
import str::sbuf;
import std::c_vec;
import std::io::{print, println};
// ---------------------------------------------------------------------------
#[link_args = "-L ../rust/build-make/llvm/x86_64-apple-darwin/Release+Asserts/lib"]
native mod clang {
type CXIndex;
type CXTranslationUnit;
type CXFile;
fn clang_getCString(++string: CXString) -> sbuf;
fn clang_disposeString(++string: CXString);
fn clang_getFileName(SFile: CXFile) -> CXString;
fn clang_createIndex(excludeDeclarationsFromPCH: c_int,
displayDiagnostics: c_int) -> CXIndex;
fn clang_disposeIndex(index: CXIndex);
fn clang_parseTranslationUnit(
CIdx: CXIndex,
source_filename: sbuf,
command_line_args: *sbuf,
num_command_line_args: c_int,
unsaved_files: *CXUnsavedFile,
num_unsaved_files: unsigned,
options: unsigned) -> CXTranslationUnit;
fn clang_disposeTranslationUnit(tu: CXTranslationUnit);
fn clang_getTranslationUnitSpelling(tu: CXTranslationUnit) -> CXString;
fn clang_getTranslationUnitCursor(tu: CXTranslationUnit) -> CXCursor;
fn clang_getCursorKindSpelling(kind: enum) -> CXString;
fn clang_isDeclaration(kind: enum) -> unsigned;
fn clang_isReference(kind: enum) -> unsigned;
fn clang_isExpression(kind: enum) -> unsigned;
fn clang_isStatement(kind: enum) -> unsigned;
fn clang_isAttribute(kind: enum) -> unsigned;
fn clang_isInvalid(kind: enum) -> unsigned;
fn clang_isTranslationUnit(kind: enum) -> unsigned;
fn clang_isPreprocessing(kind: enum) -> unsigned;
fn clang_isUnexposed(kind: enum) -> unsigned;
fn clang_getTypeKindSpelling(kind: enum) -> CXString;
}
#[link_args = "-L."]
native mod rustclang {
fn rustclang_getInclusions(tu: clang::CXTranslationUnit,
&inclusions: *_file_inclusion,
&len: unsigned);
fn rustclang_getExpansionLocation(location: CXSourceLocation,
&file: clang::CXFile,
&line: unsigned,
&column: unsigned,
&offset: unsigned);
fn rustclang_visitChildren(parent: CXCursor,
&children: *CXCursor,
&len: unsigned);
// Work around bug #1402.
fn rustclang_getCursorKind(cursor: CXCursor) -> enum;
fn rustclang_getCursorUSR(cursor: CXCursor, string: CXString);
fn rustclang_getCursorSpelling(cursor: CXCursor, string: CXString);
fn rustclang_getCursorDisplayName(cursor: CXCursor, string: CXString);
fn rustclang_getTypedefDeclUnderlyingType(cursor: CXCursor, ty: CXType);
fn rustclang_getEnumDeclIntegerType(cursor: CXCursor, ty: CXType);
fn rustclang_getEnumConstantDeclValue(cursor: CXCursor, value: longlong);
fn rustclang_getEnumConstantDeclUnsignedValue(cursor: CXCursor,
value: ulonglong);
fn rustclang_getCursorType(cursor: CXCursor, ty: CXType);
fn rustclang_getCursorResultType(cursor: CXCursor, ty: CXType);
fn rustclang_getCursorAvailability(cursor: CXCursor) -> enum;
fn rustclang_getCursorLanguage(cursor: CXCursor) -> enum;
fn rustclang_getCanonicalType(in_ty: CXType, ty: CXType);
fn rustclang_isConstQualified(ty: CXType) -> unsigned;
fn rustclang_isVolatileQualified(ty: CXType) -> unsigned;
fn rustclang_isRestrictQualified(ty: CXType) -> unsigned;
fn rustclang_getPointeeType(in_ty: CXType, out_ty: CXType);
fn rustclang_getTypeDeclaration(ty: CXType, cursor: CXCursor);
fn rustclang_getFunctionTypeCallingConv(ty: CXType) -> enum;
fn rustclang_getResultType(in_ty: CXType, out_ty: CXType);
fn rustclang_getNumArgTypes(ty: CXType) -> unsigned;
fn rustclang_getArgType(in_ty: CXType, i: unsigned, out_ty: CXType);
fn rustclang_isFunctionTypeVariadic(ty: CXType) -> unsigned;
fn rustclang_getElementType(in_ty: CXType, out_ty: CXType);
fn rustclang_getNumElements(ty: CXType) -> longlong;
fn rustclang_isPODType(ty: CXType) -> unsigned;
fn rustclang_getArrayElementType(in_ty: CXType, out_ty: CXType);
fn rustclang_getArraySize(ty: CXType) -> longlong;
}
// ---------------------------------------------------------------------------
type CXString = {
data: *void,
private_flags: unsigned,
};
fn empty_cxstring() -> CXString {
{ data: ptr::null(), private_flags: 0u as unsigned }
}
iface string {
fn to_str() -> str;
}
// CXString wrapper.
fn new_string(string: CXString) -> string {
resource string_res(string: CXString) {
clang::clang_disposeString(string);
}
impl of string for string_res {
fn to_str() -> str unsafe {
str::from_cstr(clang::clang_getCString(*self))
}
}
string_res(string) as string
}
// ---------------------------------------------------------------------------
type CXSourceLocation = {
// This should actually be an array of 2 void*, but we can't express that.
// Hopefully we won't run into alignment issues in the meantime.
ptr_data0: *void,
ptr_data1: *void,
int_data: unsigned,
};
type expansion = {
file: file,
line: uint,
column: uint,
offset: uint,
};
iface source_location {
fn expansion() -> expansion;
fn to_str() -> str;
}
// CXSourceLocation wrapper.
impl of source_location for CXSourceLocation {
fn expansion() -> expansion unsafe {
let file = unsafe::reinterpret_cast(0u);
let line = 0u32;
let column = 0u32;
let offset = 0u32;
rustclang::rustclang_getExpansionLocation(self,
file,
line,
column,
offset);
{
file: file as file,
line: line as uint,
column: column as uint,
offset: offset as uint,
}
}
fn to_str() -> str {
let e = self.expansion();
#fmt("<source_location file %s, line %u, column %u>",
e.file.filename().to_str(),
e.line,
e.column)
}
}
// ---------------------------------------------------------------------------
iface file {
fn filename() -> string;
}
// CXFile wrapper.
impl of file for clang::CXFile {
fn filename() -> string {
new_string(clang::clang_getFileName(self))
}
}
// ---------------------------------------------------------------------------
type CXUnsavedFile = {
Filename: sbuf,
Contents: sbuf,
Length: ulong
};
// ---------------------------------------------------------------------------
type _file_inclusion = {
included_file: clang::CXFile,
location: CXSourceLocation,
depth: uint
};
type file_inclusion = {
included_file: file,
location: source_location,
depth: uint
};
// file_inclusion wrapper.
fn new_file_inclusion(fu: _file_inclusion) -> file_inclusion {
{
included_file: fu.included_file as file,
location: fu.location as source_location,
depth: fu.depth
}
}
// ---------------------------------------------------------------------------
type CXCursor = {
kind: enum,
xdata: c_int,
data0: *void,
data1: *void,
data2: *void
};
fn empty_cxcursor() -> CXCursor {
{
kind: 0 as enum,
xdata: 0 as c_int,
data0: ptr::null(),
data1: ptr::null(),
data2: ptr::null(),
}
}
iface cursor {
fn kind() -> cursor_kind;
fn USR() -> string;
fn spelling() -> string;
fn display_name() -> string;
fn children() -> [cursor];
fn typedef_decl_underlying_type() -> cursor_type;
fn enum_decl_integer_type() -> cursor_type;
fn cursor_type() -> cursor_type;
fn result_type() -> cursor_type;
}
impl of cursor for CXCursor {
fn kind() -> cursor_kind {
rustclang::rustclang_getCursorKind(self) as cursor_kind
}
fn USR() -> string {
let string = empty_cxstring();
rustclang::rustclang_getCursorUSR(self, string);
new_string(string)
}
fn spelling() -> string {
let string = empty_cxstring();
rustclang::rustclang_getCursorSpelling(self, string);
new_string(string)
}
fn display_name() -> string {
let string = empty_cxstring();
rustclang::rustclang_getCursorDisplayName(self, string);
new_string(string)
}
fn children() -> [cursor] unsafe {
let len = 0u as unsigned;
let children = ptr::null::<CXCursor>();
rustclang::rustclang_visitChildren(self, children, len);
let len = len as uint;
let cv : c_vec::t<CXCursor> = c_vec::create(
unsafe::reinterpret_cast(children),
len);
let v = vec::init_fn({|i| c_vec::get(cv, i) as cursor }, len);
// llvm handles cleaning up the inclusions for us, so we can
// just let them leak.
v
}
fn typedef_decl_underlying_type() -> cursor_type {
let ty = empty_cxtype();
rustclang::rustclang_getTypedefDeclUnderlyingType(self, ty);
ty as cursor_type
}
fn enum_decl_integer_type() -> cursor_type {
let ty = empty_cxtype();
rustclang::rustclang_getEnumDeclIntegerType(self, ty);
ty as cursor_type
}
fn cursor_type() -> cursor_type {
let ty = empty_cxtype();
rustclang::rustclang_getCursorType(self, ty);
ty as cursor_type
}
fn result_type() -> cursor_type {
let ty = empty_cxtype();
rustclang::rustclang_getCursorResultType(self, ty);
ty as cursor_type
}
}
// ---------------------------------------------------------------------------
const CXCursor_UnexposedDecl : uint = 1u;
const CXCursor_StructDecl : uint = 2u;
const CXCursor_UnionDecl : uint = 3u;
const CXCursor_ClassDecl : uint = 4u;
const CXCursor_EnumDecl : uint = 5u;
const CXCursor_FieldDecl : uint = 6u;
const CXCursor_EnumConstantDecl : uint = 7u;
const CXCursor_FunctionDecl : uint = 8u;
const CXCursor_VarDecl : uint = 9u;
const CXCursor_ParmDecl : uint = 10u;
const CXCursor_ObjCInterfaceDecl : uint = 11u;
const CXCursor_ObjCCategoryDecl : uint = 12u;
const CXCursor_ObjCProtocolDecl : uint = 13u;
const CXCursor_ObjCPropertyDecl : uint = 14u;
const CXCursor_ObjCIvarDecl : uint = 15u;
const CXCursor_ObjCInstanceMethodDecl : uint = 16u;
const CXCursor_ObjCClassMethodDecl : uint = 17u;
const CXCursor_ObjCImplementationDecl : uint = 18u;
const CXCursor_ObjCCategoryImplDecl : uint = 19u;
const CXCursor_TypedefDecl : uint = 20u;
const CXCursor_CXXMethod : uint = 21u;
const CXCursor_Namespace : uint = 22u;
const CXCursor_LinkageSpec : uint = 23u;
const CXCursor_Constructor : uint = 24u;
const CXCursor_Destructor : uint = 25u;
const CXCursor_ConversionFunction : uint = 26u;
const CXCursor_TemplateTypeParameter : uint = 27u;
const CXCursor_NonTypeTemplateParameter : uint = 28u;
const CXCursor_TemplateTemplateParameter : uint = 29u;
const CXCursor_FunctionTemplate : uint = 30u;
const CXCursor_ClassTemplate : uint = 31u;
const CXCursor_ClassTemplatePartialSpecialization : uint = 32u;
const CXCursor_NamespaceAlias : uint = 33u;
const CXCursor_UsingDirective : uint = 34u;
const CXCursor_UsingDeclaration : uint = 35u;
const CXCursor_TypeAliasDecl : uint = 36u;
const CXCursor_ObjCSynthesizeDecl : uint = 37u;
const CXCursor_ObjCDynamicDecl : uint = 38u;
const CXCursor_CXXAccessSpecifier : uint = 39u;
const CXCursor_FirstDecl : uint = 1u; // CXCursor_UnexposedDecl;
const CXCursor_LastDecl : uint = 39u; // CXCursor_CXXAccessSpecifier;
const CXCursor_FirstRef : uint = 40u;
const CXCursor_ObjCSuperClassRef : uint = 40u;
const CXCursor_ObjCProtocolRef : uint = 41u;
const CXCursor_ObjCClassRef : uint = 42u;
const CXCursor_TypeRef : uint = 43u;
const CXCursor_CXXBaseSpecifier : uint = 44u;
const CXCursor_TemplateRef : uint = 45u;
const CXCursor_NamespaceRef : uint = 46u;
const CXCursor_MemberRef : uint = 47u;
const CXCursor_LabelRef : uint = 48u;
const CXCursor_OverloadedDeclRef : uint = 49u;
const CXCursor_LastRef : uint = 49u; // CXCursor_OverloadedDeclRef;
const CXCursor_FirstInvalid : uint = 70u;
const CXCursor_InvalidFile : uint = 70u;
const CXCursor_NoDeclFound : uint = 71u;
const CXCursor_NotImplemented : uint = 72u;
const CXCursor_InvalidCode : uint = 73u;
const CXCursor_LastInvalid : uint = 73u; // CXCursor_InvalidCode;
const CXCursor_FirstExpr : uint = 100u;
const CXCursor_UnexposedExpr : uint = 100u;
const CXCursor_DeclRefExpr : uint = 101u;
const CXCursor_MemberRefExpr : uint = 102u;
const CXCursor_CallExpr : uint = 103u;
const CXCursor_ObjCMessageExpr : uint = 104u;
const CXCursor_BlockExpr : uint = 105u;
const CXCursor_IntegerLiteral : uint = 106u;
const CXCursor_FloatingLiteral : uint = 107u;
const CXCursor_ImaginaryLiteral : uint = 108u;
const CXCursor_StringLiteral : uint = 109u;
const CXCursor_CharacterLiteral : uint = 110u;
const CXCursor_ParenExpr : uint = 111u;
const CXCursor_UnaryOperator : uint = 112u;
const CXCursor_ArraySubscriptExpr : uint = 113u;
const CXCursor_BinaryOperator : uint = 114u;
const CXCursor_CompoundAssignOperator : uint = 115u;
const CXCursor_ConditionalOperator : uint = 116u;
const CXCursor_CStyleCastExpr : uint = 117u;
const CXCursor_CompoundLiteralExpr : uint = 118u;
const CXCursor_InitListExpr : uint = 119u;
const CXCursor_AddrLabelExpr : uint = 120u;
const CXCursor_StmtExpr : uint = 121u;
const CXCursor_GenericSelectionExpr : uint = 122u;
const CXCursor_GNUNullExpr : uint = 123u;
const CXCursor_CXXStaticCastExpr : uint = 124u;
const CXCursor_CXXDynamicCastExpr : uint = 125u;
const CXCursor_CXXReinterpretCastExpr : uint = 126u;
const CXCursor_CXXConstCastExpr : uint = 127u;
const CXCursor_CXXFunctionalCastExpr : uint = 128u;
const CXCursor_CXXTypeidExpr : uint = 129u;
const CXCursor_CXXBoolLiteralExpr : uint = 130u;
const CXCursor_CXXNullPtrLiteralExpr : uint = 131u;
const CXCursor_CXXThisExpr : uint = 132u;
const CXCursor_CXXThrowExpr : uint = 133u;
const CXCursor_CXXNewExpr : uint = 134u;
const CXCursor_CXXDeleteExpr : uint = 135u;
const CXCursor_UnaryExpr : uint = 136u;
const CXCursor_ObjCStringLiteral : uint = 137u;
const CXCursor_ObjCEncodeExpr : uint = 138u;
const CXCursor_ObjCSelectorExpr : uint = 139u;
const CXCursor_ObjCProtocolExpr : uint = 140u;
const CXCursor_ObjCBridgedCastExpr : uint = 141u;
const CXCursor_PackExpansionExpr : uint = 142u;
const CXCursor_SizeOfPackExpr : uint = 143u;
const CXCursor_LastExpr : uint = 143u; // CXCursor_SizeOfPackExpr;
const CXCursor_FirstStmt : uint = 200u;
const CXCursor_UnexposedStmt : uint = 200u;
const CXCursor_LabelStmt : uint = 201u;
const CXCursor_CompoundStmt : uint = 202u;
const CXCursor_CaseStmt : uint = 203u;
const CXCursor_DefaultStmt : uint = 204u;
const CXCursor_IfStmt : uint = 205u;
const CXCursor_SwitchStmt : uint = 206u;
const CXCursor_WhileStmt : uint = 207u;
const CXCursor_DoStmt : uint = 208u;
const CXCursor_ForStmt : uint = 209u;
const CXCursor_GotoStmt : uint = 210u;
const CXCursor_IndirectGotoStmt : uint = 211u;
const CXCursor_ContinueStmt : uint = 212u;
const CXCursor_BreakStmt : uint = 213u;
const CXCursor_ReturnStmt : uint = 214u;
const CXCursor_AsmStmt : uint = 215u;
const CXCursor_ObjCAtTryStmt : uint = 216u;
const CXCursor_ObjCAtCatchStmt : uint = 217u;
const CXCursor_ObjCAtFinallyStmt : uint = 218u;
const CXCursor_ObjCAtThrowStmt : uint = 219u;
const CXCursor_ObjCAtSynchronizedStmt : uint = 220u;
const CXCursor_ObjCAutoreleasePoolStmt : uint = 221u;
const CXCursor_ObjCForCollectionStmt : uint = 222u;
const CXCursor_CXXCatchStmt : uint = 223u;
const CXCursor_CXXTryStmt : uint = 224u;
const CXCursor_CXXForRangeStmt : uint = 225u;
const CXCursor_SEHTryStmt : uint = 226u;
const CXCursor_SEHExceptStmt : uint = 227u;
const CXCursor_SEHFinallyStmt : uint = 228u;
const CXCursor_NullStmt : uint = 230u;
const CXCursor_DeclStmt : uint = 231u;
const CXCursor_LastStmt : uint = 231u; // CXCursor_DeclStmt;
const CXCursor_TranslationUnit : uint = 300u;
const CXCursor_FirstAttr : uint = 400u;
const CXCursor_UnexposedAttr : uint = 400u;
const CXCursor_IBActionAttr : uint = 401u;
const CXCursor_IBOutletAttr : uint = 402u;
const CXCursor_IBOutletCollectionAttr : uint = 403u;
const CXCursor_CXXFinalAttr : uint = 404u;
const CXCursor_CXXOverrideAttr : uint = 405u;
const CXCursor_AnnotateAttr : uint = 406u;
const CXCursor_AsmLabelAttr : uint = 407u;
const CXCursor_LastAttr : uint = 407u; // CXCursor_AsmLabelAttr;
const CXCursor_PreprocessingDirective : uint = 500u;
const CXCursor_MacroDefinition : uint = 501u;
const CXCursor_MacroExpansion : uint = 502u;
const CXCursor_MacroInstantiation : uint = 502u; // CXCursor_MacroExpansion;
const CXCursor_InclusionDirective : uint = 503u;
const CXCursor_FirstPreprocessing : uint = 500u; // CXCursor_PreprocessingDirective;
const CXCursor_LastPreprocessing : uint = 503u; // CXCursor_InclusionDirective;
/** \brief This value indicates that no linkage information is available
* for a provided CXCursor. */
const CXLinkage_Invalid : uint = 0u;
/**
* \brief This is the linkage for variables, parameters, and so on that
* have automatic storage. This covers normal (non-extern) local variables.
*/
const CXLinkage_NoLinkage : uint = 1u;
/** \brief This is the linkage for static variables and static functions. */
const CXLinkage_Internal : uint = 2u;
/** \brief This is the linkage for entities with external linkage that live
* in C++ anonymous namespaces.*/
const CXLinkage_UniqueExternal : uint = 3u;
/** \brief This is the linkage for entities with true, external linkage. */
const CXLinkage_External : uint = 4u;
/**
* \brief Describe the "language" of the entity referred to by a cursor.
*/
const CXLanguage_Invalid : uint = 0u;
const CXLanguage_C : uint = 1u;
const CXLanguage_ObjC : uint = 2u;
const CXLanguage_CPlusPlus : uint = 3u;
iface cursor_kind {
fn to_uint() -> uint;
fn spelling() -> string;
fn is_declaration() -> bool;
fn is_reference() -> bool;
fn is_expression() -> bool;
fn is_statement() -> bool;
fn is_attribute() -> bool;
fn is_invalid() -> bool;
fn is_translation_unit() -> bool;
fn is_preprocessing() -> bool;
fn is_unexposed() -> bool;
fn is_exposed() -> bool;
}
impl of cursor_kind for enum {
fn to_uint() -> uint { self as uint }
fn spelling() -> string {
new_string(clang::clang_getCursorKindSpelling(self))
}
fn is_declaration() -> bool {
clang::clang_isDeclaration(self) != 0u as unsigned
}
fn is_reference() -> bool {
clang::clang_isReference(self) != 0u as unsigned
}
fn is_expression() -> bool {
clang::clang_isExpression(self) != 0u as unsigned
}
fn is_statement() -> bool {
clang::clang_isStatement(self) != 0u as unsigned
}
fn is_attribute() -> bool {
clang::clang_isAttribute(self) != 0u as unsigned
}
fn is_invalid() -> bool {
clang::clang_isInvalid(self) != 0u as unsigned
}
fn is_translation_unit() -> bool {
clang::clang_isTranslationUnit(self) != 0u as unsigned
}
fn is_preprocessing() -> bool {
clang::clang_isPreprocessing(self) != 0u as unsigned
}
fn is_unexposed() -> bool {
clang::clang_isUnexposed(self) != 0u as unsigned
}
fn is_exposed() -> bool {
!self.is_unexposed()
}
}
// ---------------------------------------------------------------------------
/**
* Reprents an invalid type (e.g., where no type is available).
*/
const CXType_Invalid : uint = 0u;
/**
* A type whose specific kind is not exposed via this interface.
*/
const CXType_Unexposed : uint = 1u;
/* Builtin types */
const CXType_Void : uint = 2u;
const CXType_Bool : uint = 3u;
const CXType_Char_U : uint = 4u;
const CXType_UChar : uint = 5u;
const CXType_Char16 : uint = 6u;
const CXType_Char32 : uint = 7u;
const CXType_UShort : uint = 8u;
const CXType_UInt : uint = 9u;
const CXType_ULong : uint = 10u;
const CXType_ULongLong : uint = 11u;
const CXType_UInt128 : uint = 12u;
const CXType_Char_S : uint = 13u;
const CXType_SChar : uint = 14u;
const CXType_WChar : uint = 15u;
const CXType_Short : uint = 16u;
const CXType_Int : uint = 17u;
const CXType_Long : uint = 18u;
const CXType_LongLong : uint = 19u;
const CXType_Int128 : uint = 20u;
const CXType_Float : uint = 21u;
const CXType_Double : uint = 22u;
const CXType_LongDouble : uint = 23u;
const CXType_NullPtr : uint = 24u;
const CXType_Overload : uint = 25u;
const CXType_Dependent : uint = 26u;
const CXType_ObjCId : uint = 27u;
const CXType_ObjCClass : uint = 28u;
const CXType_ObjCSel : uint = 29u;
const CXType_FirstBuiltin : uint = 2u; // CXType_Void;
const CXType_LastBuiltin : uint = 29u; // CXType_ObjCSel,
const CXType_Complex : uint = 100u;
const CXType_Pointer : uint = 101u;
const CXType_BlockPointer : uint = 102u;
const CXType_LValueReference : uint = 103u;
const CXType_RValueReference : uint = 104u;
const CXType_Record : uint = 105u;
const CXType_Enum : uint = 106u;
const CXType_Typedef : uint = 107u;
const CXType_ObjCInterface : uint = 108u;
const CXType_ObjCObjectPointer : uint = 109u;
const CXType_FunctionNoProto : uint = 110u;
const CXType_FunctionProto : uint = 111u;
const CXType_ConstantArray : uint = 112u;
const CXType_Vector : uint = 113u;
const CXCallingConv_Default : uint = 0u;
const CXCallingConv_C : uint = 1u;
const CXCallingConv_X86StdCall : uint = 2u;
const CXCallingConv_X86FastCall : uint = 3u;
const CXCallingConv_X86ThisCall : uint = 4u;
const CXCallingConv_X86Pascal : uint = 5u;
const CXCallingConv_AAPCS : uint = 6u;
const CXCallingConv_AAPCS_VFP : uint = 7u;
const CXCallingConv_Invalid : uint = 100u;
const CXCallingConv_Unexposed : uint = 200u;
iface cursor_type_kind {
fn to_uint() -> uint;
fn spelling() -> string;
}
impl of cursor_type_kind for enum {
fn to_uint() -> uint {
self as uint
}
fn spelling() -> string {
new_string(clang::clang_getTypeKindSpelling(self))
}
}
// ---------------------------------------------------------------------------
type CXType = {
kind: enum,
data0: *void,
data1: *void
};
fn empty_cxtype() -> CXType {
{
kind: 0 as enum,
data0: ptr::null(),
data1: ptr::null()
}
}
iface cursor_type {
fn kind() -> cursor_type_kind;
fn canonical_type() -> cursor_type;
fn is_const_qualified() -> bool;
fn is_volatile_qualified() -> bool;
fn is_restrict_qualified() -> bool;
fn pointee_type() -> cursor_type;
fn type_declaration() -> cursor;
fn result_type() -> cursor_type;
fn is_pod_type() -> bool;
fn array_element_type() -> cursor_type;
fn array_size() -> u64;
}
impl of cursor_type for CXType {
fn kind() -> cursor_type_kind {
self.kind as cursor_type_kind
}
fn canonical_type() -> cursor_type {
let out_ty = empty_cxtype();
rustclang::rustclang_getCanonicalType(self, out_ty);
out_ty as cursor_type
}
fn is_const_qualified() -> bool {
rustclang::rustclang_isConstQualified(self) != 0 as unsigned
}
fn is_volatile_qualified() -> bool {
rustclang::rustclang_isVolatileQualified(self) != 0 as unsigned
}
fn is_restrict_qualified() -> bool {
rustclang::rustclang_isRestrictQualified(self) != 0 as unsigned
}
fn pointee_type() -> cursor_type {
let out_ty = empty_cxtype();
rustclang::rustclang_getPointeeType(self, out_ty);
out_ty as cursor_type
}
fn type_declaration() -> cursor {
let cursor = empty_cxcursor();
rustclang::rustclang_getTypeDeclaration(self, cursor);
cursor as cursor
}
fn result_type() -> cursor_type {
let out_ty = empty_cxtype();
rustclang::rustclang_getResultType(self, out_ty);
out_ty as cursor_type
}
fn is_pod_type() -> bool {
rustclang::rustclang_isPODType(self) != 0 as unsigned
}
fn array_element_type() -> cursor_type {
let out_ty = empty_cxtype();
rustclang::rustclang_getArrayElementType(self, out_ty);
out_ty as cursor_type
}
fn array_size() -> u64 {
rustclang::rustclang_getArraySize(self) as u64
}
}
// ---------------------------------------------------------------------------
const CXTranslationUnit_None : uint = 0x0u;
const CXTranslationUnit_DetailedPreprocessingRecord : uint = 0x01u;
const CXTranslationUnit_Incomplete : uint = 0x02u;
const CXTranslationUnit_PrecompiledPreamble : uint = 0x04u;
const CXTranslationUnit_CacheCompletionResults : uint = 0x08u;
const CXTranslationUnit_CXXPrecompiledPreamble : uint = 0x10u;
const CXTranslationUnit_CXXChainedPCH : uint = 0x20u;
const CXTranslationUnit_NestedMacroExpansions : uint = 0x40u;
const CXTranslationUnit_NestedMacroInstantiations : uint = 0x40u;
iface translation_unit {
fn spelling() -> string;
fn inclusions() -> [file_inclusion];
fn cursor() -> cursor;
}
// CXTranslationUnit wrapper.
fn new_translation_unit(tu: clang::CXTranslationUnit) -> translation_unit {
resource translation_unit_res(tu: clang::CXTranslationUnit) {
clang::clang_disposeTranslationUnit(tu);
}
impl of translation_unit for translation_unit_res {
fn spelling() -> string {
new_string(clang::clang_getTranslationUnitSpelling(*self))
}
fn inclusions() -> [file_inclusion] unsafe {
// We can't support the native clang_getInclusions, because it
// needs a callback function which rust doesn't support.
// Instead we'll make a vector in our stub library and copy the
// values from it.
let len = 0u as unsigned;
let inclusions = ptr::null::<_file_inclusion>();
rustclang::rustclang_getInclusions(*self, inclusions, len);
let len = len as uint;
let cv = c_vec::create(
unsafe::reinterpret_cast(inclusions),
len);
let v = vec::init_fn(
{|i| new_file_inclusion(c_vec::get(cv, i)) },
len);
// llvm handles cleaning up the inclusions for us, so we can
// just let them leak.
v
}
fn cursor() -> cursor {
clang::clang_getTranslationUnitCursor(*self) as cursor
}
}
translation_unit_res(tu) as translation_unit
}
// ---------------------------------------------------------------------------
iface index {
fn parse(str, [str], [CXUnsavedFile], uint) -> translation_unit;
}
fn index(excludeDeclsFromPCH: bool, displayDiagnostics: bool) -> index {
let excludeDeclarationsFromPCH = if excludeDeclsFromPCH {
1
} else {
0
};
let displayDiagnostics = if displayDiagnostics {
1
} else {
0
};
let index = clang::clang_createIndex(
excludeDeclarationsFromPCH as c_int,
displayDiagnostics as c_int);
// CXIndex wrapper.
resource index_res(index: clang::CXIndex) {
clang::clang_disposeIndex(index);
}
impl of index for index_res {
fn parse(path: str,
args: [str],
unsaved_files: [CXUnsavedFile],
options: uint) -> translation_unit {
// Work around bug #1400.
let path = @path;
// Note: we need to hold on tho these vector references while we
// hold a pointer to their buffers
let args = vec::map(args, {|arg| @arg });
let argv = vec::map(args, {|arg|
str::as_buf(*arg, { |buf| buf })
});
let tu =
unsafe {
clang::clang_parseTranslationUnit(
*self,
str::as_buf(*path, { |buf| buf }),
vec::to_ptr(argv),
vec::len(argv) as c_int,
vec::to_ptr(unsaved_files),
vec::len(unsaved_files) as unsigned,
options as unsigned)
};
new_translation_unit(tu)
}
};
index_res(index) as index
}
#[cfg(test)]
mod tests {
fn print_children(cursor: cursor) {
fn f(cursor: cursor, depth: uint, counter: @mutable uint) {
let spelling = cursor.spelling().to_str();
let ty = cursor.cursor_type();
let kind = cursor.kind();
if spelling == "" {
spelling = #fmt("$%u$", *counter);
*counter = *counter + 1u;
}
if kind.is_declaration() {
uint::range(0u, depth, { |_i| print(">") });
print(#fmt("> [%s] %s",
kind.spelling().to_str(),
spelling));
if kind.to_uint() == CXCursor_EnumDecl {
println(#fmt(" : <%s [%s] -> %s>",
ty.kind().spelling().to_str(),
cursor.enum_decl_integer_type().kind().spelling().to_str(),
ty.canonical_type().kind().spelling().to_str()));
} else if kind.to_uint() == CXCursor_EnumConstantDecl {
println(#fmt(" : <%s -> %s>",
ty.kind().spelling().to_str(),
ty.canonical_type().kind().spelling().to_str()));
} else if kind.to_uint() == CXCursor_TypedefDecl {
println(#fmt(" : <%s [%s] -> %s>",
ty.kind().spelling().to_str(),
cursor.typedef_decl_underlying_type().kind().spelling().to_str(),
ty.canonical_type().kind().spelling().to_str()));
} else {
println(#fmt(" : <%s -> %s>",
ty.kind().spelling().to_str(),
ty.canonical_type().kind().spelling().to_str()));
}
}
let children = cursor.children();
vec::iter(children, {|cursor| f(cursor, depth + 1u, counter); });
}
f(cursor, 0u, @mutable 0u);
}
#[test]
fn test() unsafe {
let index = index(true, true);
let tu = index.parse("foo.c", [], [], 0u);
println("");
println(#fmt("spelling: %s", tu.spelling().to_str()));
vec::iter(tu.inclusions(), {|inc|
println(#fmt("included_file: %s %s",
inc.included_file.filename().to_str(),
inc.location.to_str()));
});
let cursor = tu.cursor();
println("");
print_children(cursor);
}
}
|
//! Namespace cache.
use backoff::{Backoff, BackoffConfig};
use cache_system::{
backend::policy::{
lru::{LruPolicy, ResourcePool},
refresh::{OptionalValueRefreshDurationProvider, RefreshPolicy},
remove_if::{RemoveIfHandle, RemoveIfPolicy},
ttl::{OptionalValueTtlProvider, TtlPolicy},
PolicyBackend,
},
cache::{driver::CacheDriver, metrics::CacheWithMetrics, Cache},
loader::{metrics::MetricsLoader, FunctionLoader},
resource_consumption::FunctionEstimator,
};
use data_types::{
partition_template::TablePartitionTemplateOverride, Column, ColumnId, Namespace, NamespaceId,
Table, TableId,
};
use iox_catalog::interface::{Catalog, SoftDeletedRows};
use iox_time::TimeProvider;
use schema::{InfluxColumnType, Schema, SchemaBuilder};
use std::{
collections::{HashMap, HashSet},
mem::{size_of, size_of_val},
sync::Arc,
time::Duration,
};
use tokio::runtime::Handle;
use trace::span::Span;
use super::ram::RamSize;
/// Duration to keep existing namespaces.
pub const TTL_EXISTING: Duration = Duration::from_secs(300);
/// When to refresh an existing namespace.
///
/// This policy is chosen to:
/// 1. decorrelate refreshes which smooths out catalog load
/// 2. refresh commonly accessed keys less frequently
pub const REFRESH_EXISTING: BackoffConfig = BackoffConfig {
init_backoff: Duration::from_secs(30),
max_backoff: Duration::MAX,
base: 2.0,
deadline: None,
};
/// Duration to keep non-existing namespaces.
///
/// TODO(marco): Caching non-existing namespaces is virtually disabled until
/// <https://github.com/influxdata/influxdb_iox/issues/4617> is implemented because the flux integration
/// tests fail otherwise, see <https://github.com/influxdata/conductor/issues/997>.
/// The very short duration is only used so that tests can assert easily that non-existing entries have
/// SOME TTL mechanism attached.
/// The TTL is not relevant for prod at the moment because other layers should prevent/filter queries for
/// non-existing namespaces.
pub const TTL_NON_EXISTING: Duration = Duration::from_nanos(1);
const CACHE_ID: &str = "namespace";
type CacheT = Box<
dyn Cache<
K = Arc<str>,
V = Option<Arc<CachedNamespace>>,
GetExtra = ((), Option<Span>),
PeekExtra = ((), Option<Span>),
>,
>;
/// Cache for namespace-related attributes.
#[derive(Debug)]
pub struct NamespaceCache {
cache: CacheT,
remove_if_handle: RemoveIfHandle<Arc<str>, Option<Arc<CachedNamespace>>>,
}
impl NamespaceCache {
/// Create new empty cache.
pub fn new(
catalog: Arc<dyn Catalog>,
backoff_config: BackoffConfig,
time_provider: Arc<dyn TimeProvider>,
metric_registry: &metric::Registry,
ram_pool: Arc<ResourcePool<RamSize>>,
handle: &Handle,
testing: bool,
) -> Self {
let loader = FunctionLoader::new(move |namespace_name: Arc<str>, _extra: ()| {
let catalog = Arc::clone(&catalog);
let backoff_config = backoff_config.clone();
async move {
let namespace = Backoff::new(&backoff_config)
.retry_all_errors("get namespace", || async {
catalog
.repositories()
.await
.namespaces()
.get_by_name(&namespace_name, SoftDeletedRows::ExcludeDeleted)
.await
})
.await
.expect("retry forever")?;
let tables = Backoff::new(&backoff_config)
.retry_all_errors("get namespace tables", || async {
catalog
.repositories()
.await
.tables()
.list_by_namespace_id(namespace.id)
.await
})
.await
.expect("retry forever");
let columns = Backoff::new(&backoff_config)
.retry_all_errors("get namespace columns", || async {
catalog
.repositories()
.await
.columns()
.list_by_namespace_id(namespace.id)
.await
})
.await
.expect("retry forever");
Some(Arc::new(CachedNamespace::new(namespace, tables, columns)))
}
});
let loader = Arc::new(MetricsLoader::new(
loader,
CACHE_ID,
Arc::clone(&time_provider),
metric_registry,
testing,
));
let mut backend = PolicyBackend::hashmap_backed(Arc::clone(&time_provider));
backend.add_policy(TtlPolicy::new(
Arc::new(OptionalValueTtlProvider::new(
Some(TTL_NON_EXISTING),
Some(TTL_EXISTING),
)),
CACHE_ID,
metric_registry,
));
backend.add_policy(RefreshPolicy::new(
Arc::clone(&time_provider),
Arc::new(OptionalValueRefreshDurationProvider::new(
None,
Some(REFRESH_EXISTING),
)),
Arc::clone(&loader) as _,
CACHE_ID,
metric_registry,
handle,
));
let (constructor, remove_if_handle) =
RemoveIfPolicy::create_constructor_and_handle(CACHE_ID, metric_registry);
backend.add_policy(constructor);
backend.add_policy(LruPolicy::new(
Arc::clone(&ram_pool),
CACHE_ID,
Arc::new(FunctionEstimator::new(
|k: &Arc<str>, v: &Option<Arc<CachedNamespace>>| {
RamSize(
size_of_val(k)
+ k.len()
+ size_of_val(v)
+ v.as_ref().map(|v| v.size()).unwrap_or_default(),
)
},
)),
));
let cache = CacheDriver::new(loader, backend);
let cache = Box::new(CacheWithMetrics::new(
cache,
CACHE_ID,
time_provider,
metric_registry,
));
Self {
cache,
remove_if_handle,
}
}
/// Get namespace schema by name.
///
/// Expire namespace if the cached schema does NOT cover the given set of columns. The set is given as a list of
/// pairs of table name and column set.
pub async fn get(
&self,
name: Arc<str>,
should_cover: &[(&str, &HashSet<ColumnId>)],
span: Option<Span>,
) -> Option<Arc<CachedNamespace>> {
self.remove_if_handle
.remove_if_and_get(
&self.cache,
name,
|cached_namespace| {
if let Some(namespace) = cached_namespace.as_ref() {
should_cover.iter().any(|(table_name, columns)| {
if let Some(table) = namespace.tables.get(*table_name) {
columns
.iter()
.any(|col| !table.column_id_map.contains_key(col))
} else {
// table unknown => need to update
true
}
})
} else {
// namespace unknown => need to update if should cover anything
!should_cover.is_empty()
}
},
((), span),
)
.await
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CachedTable {
pub id: TableId,
pub schema: Schema,
pub column_id_map: HashMap<ColumnId, Arc<str>>,
pub column_id_map_rev: HashMap<Arc<str>, ColumnId>,
pub primary_key_column_ids: Box<[ColumnId]>,
pub partition_template: TablePartitionTemplateOverride,
}
impl CachedTable {
fn new(table: Table, mut columns: Vec<Column>) -> Self {
// sort columns by name so that schema is normalized
// Note: `sort_by_key` doesn't work if we don't wanna clone the strings every time
columns.sort_by(|x, y| x.name.cmp(&y.name));
let mut column_id_map: HashMap<ColumnId, Arc<str>> = columns
.iter()
.map(|c| (c.id, Arc::from(c.name.clone())))
.collect();
column_id_map.shrink_to_fit();
let mut column_id_map_rev: HashMap<Arc<str>, ColumnId> = column_id_map
.iter()
.map(|(v, k)| (Arc::clone(k), *v))
.collect();
column_id_map_rev.shrink_to_fit();
let mut builder = SchemaBuilder::new();
for col in columns {
let t = InfluxColumnType::from(col.column_type);
builder.influx_column(col.name, t);
}
let schema = builder.build().expect("catalog schema broken");
let primary_key_column_ids: Box<[ColumnId]> = schema
.primary_key()
.into_iter()
.map(|name| {
*column_id_map_rev
.get(name)
.unwrap_or_else(|| panic!("primary key not known?!: {name}"))
})
.collect();
Self {
id: table.id,
schema,
column_id_map,
column_id_map_rev,
primary_key_column_ids,
partition_template: table.partition_template,
}
}
/// RAM-bytes EXCLUDING `self`.
fn size(&self) -> usize {
self.schema.estimate_size()
+ (self.column_id_map.capacity() * size_of::<(ColumnId, Arc<str>)>())
+ self
.column_id_map
.values()
.map(|name| name.len())
.sum::<usize>()
+ (self.column_id_map_rev.capacity() * size_of::<(Arc<str>, ColumnId)>())
+ self
.column_id_map_rev
.keys()
.map(|name| name.len())
.sum::<usize>()
+ (self.primary_key_column_ids.len() * size_of::<ColumnId>())
+ (self.partition_template.size() - size_of::<TablePartitionTemplateOverride>())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CachedNamespace {
pub id: NamespaceId,
pub retention_period: Option<Duration>,
pub tables: HashMap<Arc<str>, Arc<CachedTable>>,
}
impl CachedNamespace {
pub fn new(namespace: Namespace, tables: Vec<Table>, columns: Vec<Column>) -> Self {
let mut tables_by_id = tables
.into_iter()
.map(|t| (t.id, (t, vec![])))
.collect::<HashMap<_, _>>();
for col in columns {
if let Some((_t, tcols)) = tables_by_id.get_mut(&col.table_id) {
tcols.push(col);
}
}
let mut tables: HashMap<Arc<str>, Arc<CachedTable>> = tables_by_id
.into_iter()
.map(|(_tid, (t, tcols))| {
let name = Arc::from(t.name.clone());
let table = Arc::new(CachedTable::new(t, tcols));
(name, table)
})
.collect();
tables.shrink_to_fit();
let retention_period = namespace
.retention_period_ns
.map(|retention| Duration::from_nanos(retention as u64));
Self {
id: namespace.id,
retention_period,
tables,
}
}
/// RAM-bytes EXCLUDING `self`.
fn size(&self) -> usize {
self.tables.capacity() * size_of::<(Arc<str>, Arc<CachedTable>)>()
+ self
.tables
.iter()
.map(|(name, table)| name.len() + table.size())
.sum::<usize>()
}
}
#[cfg(test)]
mod tests {
use crate::cache::{
ram::test_util::test_ram_pool, test_util::assert_catalog_access_metric_count,
};
use arrow::datatypes::DataType;
use data_types::ColumnType;
use generated_types::influxdata::iox::partition_template::v1::{
template_part::Part, PartitionTemplate, TemplatePart,
};
use iox_tests::TestCatalog;
use schema::SchemaBuilder;
use super::*;
#[tokio::test]
async fn test_schema() {
let catalog = TestCatalog::new();
let ns1 = catalog.create_namespace_1hr_retention("ns1").await;
let ns2 = catalog.create_namespace_1hr_retention("ns2").await;
assert_ne!(ns1.namespace.id, ns2.namespace.id);
let table11 = ns1
.create_table_with_partition_template(
"table1",
Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(Part::TagValue(String::from("col2"))),
}],
}),
)
.await;
let table12 = ns1.create_table("table2").await;
let table21 = ns2.create_table("table1").await;
let col111 = table11.create_column("col1", ColumnType::I64).await;
let col112 = table11.create_column("col2", ColumnType::Tag).await;
let col113 = table11.create_column("time", ColumnType::Time).await;
let col121 = table12.create_column("col1", ColumnType::F64).await;
let col122 = table12.create_column("time", ColumnType::Time).await;
let col211 = table21.create_column("time", ColumnType::Time).await;
let cache = NamespaceCache::new(
catalog.catalog(),
BackoffConfig::default(),
catalog.time_provider(),
&catalog.metric_registry(),
test_ram_pool(),
&Handle::current(),
true,
);
let actual_ns_1_a = cache
.get(Arc::from(String::from("ns1")), &[], None)
.await
.unwrap();
let retention_period = ns1
.namespace
.retention_period_ns
.map(|retention| Duration::from_nanos(retention as u64));
let expected_ns_1 = CachedNamespace {
id: ns1.namespace.id,
retention_period,
tables: HashMap::from([
(
Arc::from("table1"),
Arc::new(CachedTable {
id: table11.table.id,
schema: SchemaBuilder::new()
.field("col1", DataType::Int64)
.unwrap()
.tag("col2")
.timestamp()
.build()
.unwrap(),
column_id_map: HashMap::from([
(col111.column.id, Arc::from(col111.column.name.clone())),
(col112.column.id, Arc::from(col112.column.name.clone())),
(col113.column.id, Arc::from(col113.column.name.clone())),
]),
column_id_map_rev: HashMap::from([
(Arc::from(col111.column.name.clone()), col111.column.id),
(Arc::from(col112.column.name.clone()), col112.column.id),
(Arc::from(col113.column.name.clone()), col113.column.id),
]),
primary_key_column_ids: [col112.column.id, col113.column.id].into(),
partition_template: table11.table.partition_template.clone(),
}),
),
(
Arc::from("table2"),
Arc::new(CachedTable {
id: table12.table.id,
schema: SchemaBuilder::new()
.field("col1", DataType::Float64)
.unwrap()
.timestamp()
.build()
.unwrap(),
column_id_map: HashMap::from([
(col121.column.id, Arc::from(col121.column.name.clone())),
(col122.column.id, Arc::from(col122.column.name.clone())),
]),
column_id_map_rev: HashMap::from([
(Arc::from(col121.column.name.clone()), col121.column.id),
(Arc::from(col122.column.name.clone()), col122.column.id),
]),
primary_key_column_ids: [col122.column.id].into(),
partition_template: TablePartitionTemplateOverride::default(),
}),
),
]),
};
assert_eq!(actual_ns_1_a.as_ref(), &expected_ns_1);
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 1);
let actual_ns_2 = cache
.get(Arc::from(String::from("ns2")), &[], None)
.await
.unwrap();
let retention_period = ns2
.namespace
.retention_period_ns
.map(|retention| Duration::from_nanos(retention as u64));
let expected_ns_2 = CachedNamespace {
id: ns2.namespace.id,
retention_period,
tables: HashMap::from([(
Arc::from("table1"),
Arc::new(CachedTable {
id: table21.table.id,
schema: SchemaBuilder::new().timestamp().build().unwrap(),
column_id_map: HashMap::from([(
col211.column.id,
Arc::from(col211.column.name.clone()),
)]),
column_id_map_rev: HashMap::from([(
Arc::from(col211.column.name.clone()),
col211.column.id,
)]),
primary_key_column_ids: [col211.column.id].into(),
partition_template: TablePartitionTemplateOverride::default(),
}),
)]),
};
assert_eq!(actual_ns_2.as_ref(), &expected_ns_2);
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 2);
let actual_ns_1_b = cache
.get(Arc::from(String::from("ns1")), &[], None)
.await
.unwrap();
assert!(Arc::ptr_eq(&actual_ns_1_a, &actual_ns_1_b));
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 2);
}
#[tokio::test]
async fn test_schema_non_existing() {
let catalog = TestCatalog::new();
let cache = NamespaceCache::new(
catalog.catalog(),
BackoffConfig::default(),
catalog.time_provider(),
&catalog.metric_registry(),
test_ram_pool(),
&Handle::current(),
true,
);
let none = cache.get(Arc::from(String::from("foo")), &[], None).await;
assert!(none.is_none());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 1);
let none = cache.get(Arc::from(String::from("foo")), &[], None).await;
assert!(none.is_none());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 1);
}
#[tokio::test]
async fn test_expiration() {
let catalog = TestCatalog::new();
let cache = NamespaceCache::new(
catalog.catalog(),
BackoffConfig::default(),
catalog.time_provider(),
&catalog.metric_registry(),
test_ram_pool(),
&Handle::current(),
true,
);
// ========== namespace unknown ==========
assert!(cache.get(Arc::from("ns1"), &[], None).await.is_none());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 1);
assert!(cache.get(Arc::from("ns1"), &[], None).await.is_none());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 1);
assert!(cache
.get(Arc::from("ns1"), &[("t1", &HashSet::from([]))], None)
.await
.is_none());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 2);
// ========== table unknown ==========
let ns1 = catalog.create_namespace_1hr_retention("ns1").await;
assert!(cache
.get(Arc::from("ns1"), &[("t1", &HashSet::from([]))], None)
.await
.is_some());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 3);
assert!(cache
.get(Arc::from("ns1"), &[("t1", &HashSet::from([]))], None)
.await
.is_some());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 4);
// ========== no columns ==========
let t1 = ns1.create_table("t1").await;
assert!(cache
.get(Arc::from("ns1"), &[("t1", &HashSet::from([]))], None)
.await
.is_some());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 5);
assert!(cache
.get(Arc::from("ns1"), &[("t1", &HashSet::from([]))], None)
.await
.is_some());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 5);
// ========== some columns ==========
let c1 = t1.create_column("c1", ColumnType::Bool).await;
let c2 = t1.create_column("c2", ColumnType::Bool).await;
assert!(cache
.get(Arc::from("ns1"), &[("t1", &HashSet::from([]))], None)
.await
.is_some());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 5);
assert!(cache
.get(
Arc::from("ns1"),
&[("t1", &HashSet::from([c1.column.id]))],
None
)
.await
.is_some());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 6);
assert!(cache
.get(
Arc::from("ns1"),
&[("t1", &HashSet::from([c2.column.id]))],
None
)
.await
.is_some());
assert_catalog_access_metric_count(&catalog.metric_registry, "namespace_get_by_name", 6);
}
}
|
pub mod console;
pub mod cvar_system;
pub mod event_loop;
pub mod async;
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(rustc_private)]
extern crate serialize;
pub const other: u8 = 1;
pub const f: u8 = 1;
pub const d: u8 = 1;
pub const s: u8 = 1;
pub const state: u8 = 1;
pub const cmp: u8 = 1;
#[derive(Ord,Eq,PartialOrd,PartialEq,Debug,Decodable,Encodable,Hash)]
struct Foo {}
fn main() {
}
|
#![allow(clippy::enum_glob_use)]
use std::fmt::{self, Debug, Display};
use bitflags::bitflags;
use serde::de::{self, Error as SerdeError, MapAccess, Unexpected, Visitor};
use serde::{Deserialize, Deserializer};
use toml::Value as SerdeValue;
use winit::event::MouseButton;
use winit::keyboard::Key::*;
use winit::keyboard::{Key, KeyCode, KeyLocation, ModifiersState};
use winit::platform::scancode::KeyCodeExtScancode;
use alacritty_config_derive::{ConfigDeserialize, SerdeReplace};
use alacritty_terminal::config::Program;
use alacritty_terminal::term::TermMode;
use alacritty_terminal::vi_mode::ViMotion;
use crate::config::ui_config::Hint;
/// Describes a state and action to take in that state.
///
/// This is the shared component of `MouseBinding` and `KeyBinding`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding<T> {
/// Modifier keys required to activate binding.
pub mods: ModifiersState,
/// String to send to PTY if mods and mode match.
pub action: Action,
/// Binding mode required to activate binding.
pub mode: BindingMode,
/// Excluded binding modes where the binding won't be activated.
pub notmode: BindingMode,
/// This property is used as part of the trigger detection code.
///
/// For example, this might be a key like "G", or a mouse button.
pub trigger: T,
}
/// Bindings that are triggered by a keyboard key.
pub type KeyBinding = Binding<BindingKey>;
/// Bindings that are triggered by a mouse button.
pub type MouseBinding = Binding<MouseButton>;
impl<T: Eq> Binding<T> {
#[inline]
pub fn is_triggered_by(&self, mode: BindingMode, mods: ModifiersState, input: &T) -> bool {
// Check input first since bindings are stored in one big list. This is
// the most likely item to fail so prioritizing it here allows more
// checks to be short circuited.
self.trigger == *input
&& self.mods == mods
&& mode.contains(self.mode)
&& !mode.intersects(self.notmode)
}
#[inline]
pub fn triggers_match(&self, binding: &Binding<T>) -> bool {
// Check the binding's key and modifiers.
if self.trigger != binding.trigger || self.mods != binding.mods {
return false;
}
let selfmode = if self.mode.is_empty() { BindingMode::all() } else { self.mode };
let bindingmode = if binding.mode.is_empty() { BindingMode::all() } else { binding.mode };
if !selfmode.intersects(bindingmode) {
return false;
}
// The bindings are never active at the same time when the required modes of one binding
// are part of the forbidden bindings of the other.
if self.mode.intersects(binding.notmode) || binding.mode.intersects(self.notmode) {
return false;
}
true
}
}
#[derive(ConfigDeserialize, Debug, Clone, PartialEq, Eq)]
pub enum Action {
/// Write an escape sequence.
#[config(skip)]
Esc(String),
/// Run given command.
#[config(skip)]
Command(Program),
/// Regex keyboard hints.
#[config(skip)]
Hint(Hint),
/// Move vi mode cursor.
#[config(skip)]
ViMotion(ViMotion),
/// Perform vi mode action.
#[config(skip)]
Vi(ViAction),
/// Perform search mode action.
#[config(skip)]
Search(SearchAction),
/// Perform mouse binding exclusive action.
#[config(skip)]
Mouse(MouseAction),
/// Paste contents of system clipboard.
Paste,
/// Store current selection into clipboard.
Copy,
#[cfg(not(any(target_os = "macos", windows)))]
/// Store current selection into selection buffer.
CopySelection,
/// Paste contents of selection buffer.
PasteSelection,
/// Increase font size.
IncreaseFontSize,
/// Decrease font size.
DecreaseFontSize,
/// Reset font size to the config value.
ResetFontSize,
/// Scroll exactly one page up.
ScrollPageUp,
/// Scroll exactly one page down.
ScrollPageDown,
/// Scroll half a page up.
ScrollHalfPageUp,
/// Scroll half a page down.
ScrollHalfPageDown,
/// Scroll one line up.
ScrollLineUp,
/// Scroll one line down.
ScrollLineDown,
/// Scroll all the way to the top.
ScrollToTop,
/// Scroll all the way to the bottom.
ScrollToBottom,
/// Clear the display buffer(s) to remove history.
ClearHistory,
/// Hide the Alacritty window.
Hide,
/// Hide all windows other than Alacritty on macOS.
#[cfg(target_os = "macos")]
HideOtherApplications,
/// Minimize the Alacritty window.
Minimize,
/// Quit Alacritty.
Quit,
/// Clear warning and error notices.
ClearLogNotice,
/// Spawn a new instance of Alacritty.
SpawnNewInstance,
/// Create a new Alacritty window.
CreateNewWindow,
/// Toggle fullscreen.
ToggleFullscreen,
/// Toggle maximized.
ToggleMaximized,
/// Toggle simple fullscreen on macOS.
#[cfg(target_os = "macos")]
ToggleSimpleFullscreen,
/// Clear active selection.
ClearSelection,
/// Toggle vi mode.
ToggleViMode,
/// Allow receiving char input.
ReceiveChar,
/// Start a forward buffer search.
SearchForward,
/// Start a backward buffer search.
SearchBackward,
/// No action.
None,
}
impl From<&'static str> for Action {
fn from(s: &'static str) -> Action {
Action::Esc(s.into())
}
}
impl From<ViAction> for Action {
fn from(action: ViAction) -> Self {
Self::Vi(action)
}
}
impl From<ViMotion> for Action {
fn from(motion: ViMotion) -> Self {
Self::ViMotion(motion)
}
}
impl From<SearchAction> for Action {
fn from(action: SearchAction) -> Self {
Self::Search(action)
}
}
impl From<MouseAction> for Action {
fn from(action: MouseAction) -> Self {
Self::Mouse(action)
}
}
/// Display trait used for error logging.
impl Display for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Action::ViMotion(motion) => motion.fmt(f),
Action::Vi(action) => action.fmt(f),
Action::Mouse(action) => action.fmt(f),
_ => write!(f, "{:?}", self),
}
}
}
/// Vi mode specific actions.
#[derive(ConfigDeserialize, Debug, Copy, Clone, PartialEq, Eq)]
pub enum ViAction {
/// Toggle normal vi selection.
ToggleNormalSelection,
/// Toggle line vi selection.
ToggleLineSelection,
/// Toggle block vi selection.
ToggleBlockSelection,
/// Toggle semantic vi selection.
ToggleSemanticSelection,
/// Jump to the beginning of the next match.
SearchNext,
/// Jump to the beginning of the previous match.
SearchPrevious,
/// Jump to the next start of a match to the left of the origin.
SearchStart,
/// Jump to the next end of a match to the right of the origin.
SearchEnd,
/// Launch the URL below the vi mode cursor.
Open,
/// Centers the screen around the vi mode cursor.
CenterAroundViCursor,
}
/// Search mode specific actions.
#[allow(clippy::enum_variant_names)]
#[derive(ConfigDeserialize, Debug, Copy, Clone, PartialEq, Eq)]
pub enum SearchAction {
/// Move the focus to the next search match.
SearchFocusNext,
/// Move the focus to the previous search match.
SearchFocusPrevious,
/// Confirm the active search.
SearchConfirm,
/// Cancel the active search.
SearchCancel,
/// Reset the search regex.
SearchClear,
/// Delete the last word in the search regex.
SearchDeleteWord,
/// Go to the previous regex in the search history.
SearchHistoryPrevious,
/// Go to the next regex in the search history.
SearchHistoryNext,
}
/// Mouse binding specific actions.
#[derive(ConfigDeserialize, Debug, Copy, Clone, PartialEq, Eq)]
pub enum MouseAction {
/// Expand the selection to the current mouse cursor position.
ExpandSelection,
}
macro_rules! bindings {
(
$ty:ident;
$(
$key:expr
$(=>$location:expr)?
$(,$mods:expr)*
$(,+$mode:expr)*
$(,~$notmode:expr)*
;$action:expr
);*
$(;)*
) => {{
let mut v = Vec::new();
$(
let mut _mods = ModifiersState::empty();
$(_mods = $mods;)*
let mut _mode = BindingMode::empty();
$(_mode.insert($mode);)*
let mut _notmode = BindingMode::empty();
$(_notmode.insert($notmode);)*
v.push($ty {
trigger: trigger!($ty, $key, $($location)?),
mods: _mods,
mode: _mode,
notmode: _notmode,
action: $action.into(),
});
)*
v
}};
}
macro_rules! trigger {
(KeyBinding, $key:literal, $location:expr) => {{
BindingKey::Keycode { key: Character($key.into()), location: $location }
}};
(KeyBinding, $key:literal,) => {{
BindingKey::Keycode { key: Character($key.into()), location: KeyLocation::Standard }
}};
(KeyBinding, $key:expr,) => {{
BindingKey::Keycode { key: $key, location: KeyLocation::Standard }
}};
($ty:ident, $key:expr,) => {{
$key
}};
}
pub fn default_mouse_bindings() -> Vec<MouseBinding> {
bindings!(
MouseBinding;
MouseButton::Right; MouseAction::ExpandSelection;
MouseButton::Right, ModifiersState::CONTROL; MouseAction::ExpandSelection;
MouseButton::Middle, ~BindingMode::VI; Action::PasteSelection;
)
}
pub fn default_key_bindings() -> Vec<KeyBinding> {
let mut bindings = bindings!(
KeyBinding;
Copy; Action::Copy;
Copy, +BindingMode::VI; Action::ClearSelection;
Paste, ~BindingMode::VI; Action::Paste;
"l", ModifiersState::CONTROL; Action::ClearLogNotice;
"l", ModifiersState::CONTROL, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x0c".into());
Tab, ModifiersState::SHIFT, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[Z".into());
Backspace, ModifiersState::ALT, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b\x7f".into());
Backspace, ModifiersState::SHIFT, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x7f".into());
Home, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollToTop;
End, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollToBottom;
PageUp, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollPageUp;
PageDown, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollPageDown;
Home, ModifiersState::SHIFT, +BindingMode::ALT_SCREEN, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[1;2H".into());
End, ModifiersState::SHIFT, +BindingMode::ALT_SCREEN, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[1;2F".into());
PageUp, ModifiersState::SHIFT, +BindingMode::ALT_SCREEN, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[5;2~".into());
PageDown, ModifiersState::SHIFT, +BindingMode::ALT_SCREEN, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[6;2~".into());
Home, +BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOH".into());
Home, ~BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[H".into());
End, +BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOF".into());
End, ~BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[F".into());
ArrowUp, +BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOA".into());
ArrowUp, ~BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[A".into());
ArrowDown, +BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOB".into());
ArrowDown, ~BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[B".into());
ArrowRight, +BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOC".into());
ArrowRight, ~BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[C".into());
ArrowLeft, +BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOD".into());
ArrowLeft, ~BindingMode::APP_CURSOR, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[D".into());
Backspace, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x7f".into());
Insert, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[2~".into());
Delete, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[3~".into());
PageUp, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[5~".into());
PageDown, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[6~".into());
F1, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOP".into());
F2, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOQ".into());
F3, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOR".into());
F4, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1bOS".into());
F5, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[15~".into());
F6, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[17~".into());
F7, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[18~".into());
F8, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[19~".into());
F9, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[20~".into());
F10, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[21~".into());
F11, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[23~".into());
F12, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[24~".into());
F13, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[25~".into());
F14, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[26~".into());
F15, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[28~".into());
F16, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[29~".into());
F17, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[31~".into());
F18, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[32~".into());
F19, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[33~".into());
F20, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[34~".into());
// Vi mode.
Space, ModifiersState::SHIFT | ModifiersState::CONTROL, ~BindingMode::SEARCH; Action::ToggleViMode;
Space, ModifiersState::SHIFT | ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollToBottom;
Escape, +BindingMode::VI, ~BindingMode::SEARCH; Action::ClearSelection;
"i", +BindingMode::VI, ~BindingMode::SEARCH; Action::ToggleViMode;
"i", +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollToBottom;
"c", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ToggleViMode;
"y", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollLineUp;
"e", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollLineDown;
"g", +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollToTop;
"g", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollToBottom;
"b", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollPageUp;
"f", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollPageDown;
"u", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollHalfPageUp;
"d", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; Action::ScrollHalfPageDown;
"y", +BindingMode::VI, ~BindingMode::SEARCH; Action::Copy;
"y", +BindingMode::VI, ~BindingMode::SEARCH; Action::ClearSelection;
"/", +BindingMode::VI, ~BindingMode::SEARCH; Action::SearchForward;
"/", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; Action::SearchBackward;
"v", +BindingMode::VI, ~BindingMode::SEARCH; ViAction::ToggleNormalSelection;
"v", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViAction::ToggleLineSelection;
"v", ModifiersState::CONTROL, +BindingMode::VI, ~BindingMode::SEARCH; ViAction::ToggleBlockSelection;
"v", ModifiersState::ALT, +BindingMode::VI, ~BindingMode::SEARCH; ViAction::ToggleSemanticSelection;
"n", +BindingMode::VI, ~BindingMode::SEARCH; ViAction::SearchNext;
"n", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViAction::SearchPrevious;
Enter, +BindingMode::VI, ~BindingMode::SEARCH; ViAction::Open;
"z", +BindingMode::VI, ~BindingMode::SEARCH; ViAction::CenterAroundViCursor;
"k", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Up;
"j", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Down;
"h", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Left;
"l", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Right;
ArrowUp, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Up;
ArrowDown, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Down;
ArrowLeft, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Left;
ArrowRight, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Right;
"0", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::First;
"$", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Last;
"^", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::FirstOccupied;
"h", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::High;
"m", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Middle;
"l", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Low;
"b", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::SemanticLeft;
"w", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::SemanticRight;
"e", +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::SemanticRightEnd;
"b", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::WordLeft;
"w", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::WordRight;
"e", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::WordRightEnd;
"%", ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; ViMotion::Bracket;
Enter, +BindingMode::VI, +BindingMode::SEARCH; SearchAction::SearchConfirm;
// Plain search.
Escape, +BindingMode::SEARCH; SearchAction::SearchCancel;
"c", ModifiersState::CONTROL, +BindingMode::SEARCH; SearchAction::SearchCancel;
"u", ModifiersState::CONTROL, +BindingMode::SEARCH; SearchAction::SearchClear;
"w", ModifiersState::CONTROL, +BindingMode::SEARCH; SearchAction::SearchDeleteWord;
"p", ModifiersState::CONTROL, +BindingMode::SEARCH; SearchAction::SearchHistoryPrevious;
"n", ModifiersState::CONTROL, +BindingMode::SEARCH; SearchAction::SearchHistoryNext;
ArrowUp, +BindingMode::SEARCH; SearchAction::SearchHistoryPrevious;
ArrowDown, +BindingMode::SEARCH; SearchAction::SearchHistoryNext;
Enter, +BindingMode::SEARCH, ~BindingMode::VI; SearchAction::SearchFocusNext;
Enter, ModifiersState::SHIFT, +BindingMode::SEARCH, ~BindingMode::VI; SearchAction::SearchFocusPrevious;
);
// Code Modifiers
// ---------+---------------------------
// 2 | Shift
// 3 | Alt
// 4 | Shift + Alt
// 5 | Control
// 6 | Shift + Control
// 7 | Alt + Control
// 8 | Shift + Alt + Control
// ---------+---------------------------
//
// from: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-PC-Style-Function-Keys
let mut modifiers = vec![
ModifiersState::SHIFT,
ModifiersState::ALT,
ModifiersState::SHIFT | ModifiersState::ALT,
ModifiersState::CONTROL,
ModifiersState::SHIFT | ModifiersState::CONTROL,
ModifiersState::ALT | ModifiersState::CONTROL,
ModifiersState::SHIFT | ModifiersState::ALT | ModifiersState::CONTROL,
];
for (index, mods) in modifiers.drain(..).enumerate() {
let modifiers_code = index + 2;
bindings.extend(bindings!(
KeyBinding;
Delete, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[3;{}~", modifiers_code));
ArrowUp, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}A", modifiers_code));
ArrowDown, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}B", modifiers_code));
ArrowRight, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}C", modifiers_code));
ArrowLeft, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}D", modifiers_code));
F1, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}P", modifiers_code));
F2, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}Q", modifiers_code));
F3, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}R", modifiers_code));
F4, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}S", modifiers_code));
F5, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[15;{}~", modifiers_code));
F6, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[17;{}~", modifiers_code));
F7, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[18;{}~", modifiers_code));
F8, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[19;{}~", modifiers_code));
F9, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[20;{}~", modifiers_code));
F10, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[21;{}~", modifiers_code));
F11, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[23;{}~", modifiers_code));
F12, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[24;{}~", modifiers_code));
F13, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[25;{}~", modifiers_code));
F14, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[26;{}~", modifiers_code));
F15, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[28;{}~", modifiers_code));
F16, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[29;{}~", modifiers_code));
F17, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[31;{}~", modifiers_code));
F18, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[32;{}~", modifiers_code));
F19, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[33;{}~", modifiers_code));
F20, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[34;{}~", modifiers_code));
));
// We're adding the following bindings with `Shift` manually above, so skipping them here.
if modifiers_code != 2 {
bindings.extend(bindings!(
KeyBinding;
Insert, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[2;{}~", modifiers_code));
PageUp, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[5;{}~", modifiers_code));
PageDown, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[6;{}~", modifiers_code));
End, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}F", modifiers_code));
Home, mods, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc(format!("\x1b[1;{}H", modifiers_code));
));
}
}
bindings.extend(platform_key_bindings());
bindings
}
#[cfg(not(any(target_os = "macos", test)))]
fn common_keybindings() -> Vec<KeyBinding> {
bindings!(
KeyBinding;
"c", ModifiersState::CONTROL | ModifiersState::SHIFT, +BindingMode::VI, ~BindingMode::SEARCH; Action::ClearSelection;
"v", ModifiersState::CONTROL | ModifiersState::SHIFT, ~BindingMode::VI; Action::Paste;
"f", ModifiersState::CONTROL | ModifiersState::SHIFT, ~BindingMode::SEARCH; Action::SearchForward;
"b", ModifiersState::CONTROL | ModifiersState::SHIFT, ~BindingMode::SEARCH; Action::SearchBackward;
Insert, ModifiersState::SHIFT, ~BindingMode::VI; Action::PasteSelection;
"c", ModifiersState::CONTROL | ModifiersState::SHIFT; Action::Copy;
"0", ModifiersState::CONTROL; Action::ResetFontSize;
"=", ModifiersState::CONTROL; Action::IncreaseFontSize;
"+", ModifiersState::CONTROL; Action::IncreaseFontSize;
"-", ModifiersState::CONTROL; Action::DecreaseFontSize;
"+" => KeyLocation::Numpad, ModifiersState::CONTROL; Action::IncreaseFontSize;
"-" => KeyLocation::Numpad, ModifiersState::CONTROL; Action::DecreaseFontSize;
)
}
#[cfg(not(any(target_os = "macos", target_os = "windows", test)))]
pub fn platform_key_bindings() -> Vec<KeyBinding> {
common_keybindings()
}
#[cfg(all(target_os = "windows", not(test)))]
pub fn platform_key_bindings() -> Vec<KeyBinding> {
let mut bindings = bindings!(
KeyBinding;
Enter, ModifiersState::ALT; Action::ToggleFullscreen;
);
bindings.extend(common_keybindings());
bindings
}
#[cfg(all(target_os = "macos", not(test)))]
pub fn platform_key_bindings() -> Vec<KeyBinding> {
bindings!(
KeyBinding;
"c", ModifiersState::SUPER, +BindingMode::VI, ~BindingMode::SEARCH; Action::ClearSelection;
Insert, ModifiersState::SHIFT, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x1b[2;2~".into());
"0", ModifiersState::SUPER; Action::ResetFontSize;
"=", ModifiersState::SUPER; Action::IncreaseFontSize;
"+", ModifiersState::SUPER; Action::IncreaseFontSize;
"-", ModifiersState::SUPER; Action::DecreaseFontSize;
"k", ModifiersState::SUPER, ~BindingMode::VI, ~BindingMode::SEARCH; Action::Esc("\x0c".into());
"k", ModifiersState::SUPER, ~BindingMode::VI, ~BindingMode::SEARCH; Action::ClearHistory;
"v", ModifiersState::SUPER, ~BindingMode::VI; Action::Paste;
"n", ModifiersState::SUPER; Action::CreateNewWindow;
"f", ModifiersState::CONTROL | ModifiersState::SUPER; Action::ToggleFullscreen;
"c", ModifiersState::SUPER; Action::Copy;
"h", ModifiersState::SUPER; Action::Hide;
"h", ModifiersState::SUPER | ModifiersState::ALT; Action::HideOtherApplications;
"m", ModifiersState::SUPER; Action::Minimize;
"q", ModifiersState::SUPER; Action::Quit;
"w", ModifiersState::SUPER; Action::Quit;
"f", ModifiersState::SUPER, ~BindingMode::SEARCH; Action::SearchForward;
"b", ModifiersState::SUPER, ~BindingMode::SEARCH; Action::SearchBackward;
"+" => KeyLocation::Numpad, ModifiersState::SUPER; Action::IncreaseFontSize;
"-" => KeyLocation::Numpad, ModifiersState::SUPER; Action::DecreaseFontSize;
)
}
// Don't return any bindings for tests since they are commented-out by default.
#[cfg(test)]
pub fn platform_key_bindings() -> Vec<KeyBinding> {
vec![]
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum BindingKey {
Scancode(KeyCode),
Keycode { key: Key, location: KeyLocation },
}
impl<'a> Deserialize<'a> for BindingKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
let value = SerdeValue::deserialize(deserializer)?;
match u32::deserialize(value.clone()) {
Ok(scancode) => Ok(BindingKey::Scancode(KeyCode::from_scancode(scancode))),
Err(_) => {
let keycode = String::deserialize(value.clone()).map_err(D::Error::custom)?;
let (key, location) = if keycode.chars().count() == 1 {
(Key::Character(keycode.to_lowercase().into()), KeyLocation::Standard)
} else {
// Translate legacy winit codes into their modern counterparts.
match keycode.as_str() {
"Up" => (Key::ArrowUp, KeyLocation::Standard),
"Back" => (Key::Backspace, KeyLocation::Standard),
"Down" => (Key::ArrowDown, KeyLocation::Standard),
"Left" => (Key::ArrowLeft, KeyLocation::Standard),
"Right" => (Key::ArrowRight, KeyLocation::Standard),
"At" => (Key::Character("@".into()), KeyLocation::Standard),
"Colon" => (Key::Character(":".into()), KeyLocation::Standard),
"Period" => (Key::Character(".".into()), KeyLocation::Standard),
"Return" => (Key::Enter, KeyLocation::Standard),
"LBracket" => (Key::Character("[".into()), KeyLocation::Standard),
"RBracket" => (Key::Character("]".into()), KeyLocation::Standard),
"Semicolon" => (Key::Character(";".into()), KeyLocation::Standard),
"Backslash" => (Key::Character("\\".into()), KeyLocation::Standard),
"Plus" => (Key::Character("+".into()), KeyLocation::Standard),
"Comma" => (Key::Character(",".into()), KeyLocation::Standard),
"Slash" => (Key::Character("/".into()), KeyLocation::Standard),
"Equals" => (Key::Character("=".into()), KeyLocation::Standard),
"Minus" => (Key::Character("-".into()), KeyLocation::Standard),
"Asterisk" => (Key::Character("*".into()), KeyLocation::Standard),
"Key1" => (Key::Character("1".into()), KeyLocation::Standard),
"Key2" => (Key::Character("2".into()), KeyLocation::Standard),
"Key3" => (Key::Character("3".into()), KeyLocation::Standard),
"Key4" => (Key::Character("4".into()), KeyLocation::Standard),
"Key5" => (Key::Character("5".into()), KeyLocation::Standard),
"Key6" => (Key::Character("6".into()), KeyLocation::Standard),
"Key7" => (Key::Character("7".into()), KeyLocation::Standard),
"Key8" => (Key::Character("8".into()), KeyLocation::Standard),
"Key9" => (Key::Character("9".into()), KeyLocation::Standard),
"Key0" => (Key::Character("0".into()), KeyLocation::Standard),
// Special case numpad.
"NumpadEnter" => (Key::Enter, KeyLocation::Numpad),
"NumpadAdd" => (Key::Character("+".into()), KeyLocation::Numpad),
"NumpadComma" => (Key::Character(",".into()), KeyLocation::Numpad),
"NumpadDivide" => (Key::Character("/".into()), KeyLocation::Numpad),
"NumpadEquals" => (Key::Character("=".into()), KeyLocation::Numpad),
"NumpadSubtract" => (Key::Character("-".into()), KeyLocation::Numpad),
"NumpadMultiply" => (Key::Character("*".into()), KeyLocation::Numpad),
"Numpad1" => (Key::Character("1".into()), KeyLocation::Numpad),
"Numpad2" => (Key::Character("2".into()), KeyLocation::Numpad),
"Numpad3" => (Key::Character("3".into()), KeyLocation::Numpad),
"Numpad4" => (Key::Character("4".into()), KeyLocation::Numpad),
"Numpad5" => (Key::Character("5".into()), KeyLocation::Numpad),
"Numpad6" => (Key::Character("6".into()), KeyLocation::Numpad),
"Numpad7" => (Key::Character("7".into()), KeyLocation::Numpad),
"Numpad8" => (Key::Character("8".into()), KeyLocation::Numpad),
"Numpad9" => (Key::Character("9".into()), KeyLocation::Numpad),
"Numpad0" => (Key::Character("0".into()), KeyLocation::Numpad),
_ => (
Key::deserialize(value).map_err(D::Error::custom)?,
KeyLocation::Standard,
),
}
};
Ok(BindingKey::Keycode { key, location })
},
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ModeWrapper {
pub mode: BindingMode,
pub not_mode: BindingMode,
}
bitflags! {
/// Modes available for key bindings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BindingMode: u8 {
const APP_CURSOR = 0b0000_0001;
const APP_KEYPAD = 0b0000_0010;
const ALT_SCREEN = 0b0000_0100;
const VI = 0b0000_1000;
const SEARCH = 0b0001_0000;
}
}
impl BindingMode {
pub fn new(mode: &TermMode, search: bool) -> BindingMode {
let mut binding_mode = BindingMode::empty();
binding_mode.set(BindingMode::APP_CURSOR, mode.contains(TermMode::APP_CURSOR));
binding_mode.set(BindingMode::APP_KEYPAD, mode.contains(TermMode::APP_KEYPAD));
binding_mode.set(BindingMode::ALT_SCREEN, mode.contains(TermMode::ALT_SCREEN));
binding_mode.set(BindingMode::VI, mode.contains(TermMode::VI));
binding_mode.set(BindingMode::SEARCH, search);
binding_mode
}
}
impl Default for ModeWrapper {
fn default() -> Self {
Self { mode: BindingMode::empty(), not_mode: BindingMode::empty() }
}
}
impl<'a> Deserialize<'a> for ModeWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
struct ModeVisitor;
impl<'a> Visitor<'a> for ModeVisitor {
type Value = ModeWrapper;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(
"a combination of AppCursor | AppKeypad | Alt | Vi, possibly with negation (~)",
)
}
fn visit_str<E>(self, value: &str) -> Result<ModeWrapper, E>
where
E: de::Error,
{
let mut res =
ModeWrapper { mode: BindingMode::empty(), not_mode: BindingMode::empty() };
for modifier in value.split('|') {
match modifier.trim().to_lowercase().as_str() {
"appcursor" => res.mode |= BindingMode::APP_CURSOR,
"~appcursor" => res.not_mode |= BindingMode::APP_CURSOR,
"appkeypad" => res.mode |= BindingMode::APP_KEYPAD,
"~appkeypad" => res.not_mode |= BindingMode::APP_KEYPAD,
"alt" => res.mode |= BindingMode::ALT_SCREEN,
"~alt" => res.not_mode |= BindingMode::ALT_SCREEN,
"vi" => res.mode |= BindingMode::VI,
"~vi" => res.not_mode |= BindingMode::VI,
"search" => res.mode |= BindingMode::SEARCH,
"~search" => res.not_mode |= BindingMode::SEARCH,
_ => return Err(E::invalid_value(Unexpected::Str(modifier), &self)),
}
}
Ok(res)
}
}
deserializer.deserialize_str(ModeVisitor)
}
}
struct MouseButtonWrapper(MouseButton);
impl MouseButtonWrapper {
fn into_inner(self) -> MouseButton {
self.0
}
}
impl<'a> Deserialize<'a> for MouseButtonWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
struct MouseButtonVisitor;
impl<'a> Visitor<'a> for MouseButtonVisitor {
type Value = MouseButtonWrapper;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Left, Right, Middle, or a number from 0 to 65536")
}
fn visit_u64<E>(self, value: u64) -> Result<MouseButtonWrapper, E>
where
E: de::Error,
{
match value {
0..=65536 => Ok(MouseButtonWrapper(MouseButton::Other(value as u16))),
_ => Err(E::invalid_value(Unexpected::Unsigned(value), &self)),
}
}
fn visit_str<E>(self, value: &str) -> Result<MouseButtonWrapper, E>
where
E: de::Error,
{
match value {
"Left" => Ok(MouseButtonWrapper(MouseButton::Left)),
"Right" => Ok(MouseButtonWrapper(MouseButton::Right)),
"Middle" => Ok(MouseButtonWrapper(MouseButton::Middle)),
_ => Err(E::invalid_value(Unexpected::Str(value), &self)),
}
}
}
deserializer.deserialize_any(MouseButtonVisitor)
}
}
/// Bindings are deserialized into a `RawBinding` before being parsed as a
/// `KeyBinding` or `MouseBinding`.
#[derive(PartialEq, Eq)]
struct RawBinding {
key: Option<BindingKey>,
mouse: Option<MouseButton>,
mods: ModifiersState,
mode: BindingMode,
notmode: BindingMode,
action: Action,
}
impl RawBinding {
fn into_mouse_binding(self) -> Result<MouseBinding, Box<Self>> {
if let Some(mouse) = self.mouse {
Ok(Binding {
trigger: mouse,
mods: self.mods,
action: self.action,
mode: self.mode,
notmode: self.notmode,
})
} else {
Err(Box::new(self))
}
}
fn into_key_binding(self) -> Result<KeyBinding, Box<Self>> {
if let Some(key) = self.key {
Ok(KeyBinding {
trigger: key,
mods: self.mods,
action: self.action,
mode: self.mode,
notmode: self.notmode,
})
} else {
Err(Box::new(self))
}
}
}
impl<'a> Deserialize<'a> for RawBinding {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
const FIELDS: &[&str] = &["key", "mods", "mode", "action", "chars", "mouse", "command"];
enum Field {
Key,
Mods,
Mode,
Action,
Chars,
Mouse,
Command,
}
impl<'a> Deserialize<'a> for Field {
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
where
D: Deserializer<'a>,
{
struct FieldVisitor;
impl<'a> Visitor<'a> for FieldVisitor {
type Value = Field;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("binding fields")
}
fn visit_str<E>(self, value: &str) -> Result<Field, E>
where
E: de::Error,
{
match value.to_ascii_lowercase().as_str() {
"key" => Ok(Field::Key),
"mods" => Ok(Field::Mods),
"mode" => Ok(Field::Mode),
"action" => Ok(Field::Action),
"chars" => Ok(Field::Chars),
"mouse" => Ok(Field::Mouse),
"command" => Ok(Field::Command),
_ => Err(E::unknown_field(value, FIELDS)),
}
}
}
deserializer.deserialize_str(FieldVisitor)
}
}
struct RawBindingVisitor;
impl<'a> Visitor<'a> for RawBindingVisitor {
type Value = RawBinding;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("binding specification")
}
fn visit_map<V>(self, mut map: V) -> Result<RawBinding, V::Error>
where
V: MapAccess<'a>,
{
let mut mods: Option<ModifiersState> = None;
let mut key: Option<BindingKey> = None;
let mut chars: Option<String> = None;
let mut action: Option<Action> = None;
let mut mode: Option<BindingMode> = None;
let mut not_mode: Option<BindingMode> = None;
let mut mouse: Option<MouseButton> = None;
let mut command: Option<Program> = None;
use de::Error;
while let Some(struct_key) = map.next_key::<Field>()? {
match struct_key {
Field::Key => {
if key.is_some() {
return Err(<V::Error as Error>::duplicate_field("key"));
}
let value = map.next_value::<SerdeValue>()?;
match value.as_integer() {
Some(scancode) => match u32::try_from(scancode) {
Ok(scancode) => {
key = Some(BindingKey::Scancode(KeyCode::from_scancode(
scancode,
)))
},
Err(_) => {
return Err(<V::Error as Error>::custom(format!(
"Invalid key binding, scancode is too big: {}",
scancode
)));
},
},
None => {
key = Some(
BindingKey::deserialize(value).map_err(V::Error::custom)?,
)
},
}
},
Field::Mods => {
if mods.is_some() {
return Err(<V::Error as Error>::duplicate_field("mods"));
}
mods = Some(map.next_value::<ModsWrapper>()?.into_inner());
},
Field::Mode => {
if mode.is_some() {
return Err(<V::Error as Error>::duplicate_field("mode"));
}
let mode_deserializer = map.next_value::<ModeWrapper>()?;
mode = Some(mode_deserializer.mode);
not_mode = Some(mode_deserializer.not_mode);
},
Field::Action => {
if action.is_some() {
return Err(<V::Error as Error>::duplicate_field("action"));
}
let value = map.next_value::<SerdeValue>()?;
action = if let Ok(vi_action) = ViAction::deserialize(value.clone()) {
Some(vi_action.into())
} else if let Ok(vi_motion) = ViMotion::deserialize(value.clone()) {
Some(vi_motion.into())
} else if let Ok(search_action) =
SearchAction::deserialize(value.clone())
{
Some(search_action.into())
} else if let Ok(mouse_action) = MouseAction::deserialize(value.clone())
{
Some(mouse_action.into())
} else {
match Action::deserialize(value.clone()).map_err(V::Error::custom) {
Ok(action) => Some(action),
Err(err) => {
let value = match value {
SerdeValue::String(string) => string,
_ => return Err(err),
};
return Err(V::Error::custom(format!(
"unknown keyboard action `{}`",
value
)));
},
}
};
},
Field::Chars => {
if chars.is_some() {
return Err(<V::Error as Error>::duplicate_field("chars"));
}
chars = Some(map.next_value()?);
},
Field::Mouse => {
if chars.is_some() {
return Err(<V::Error as Error>::duplicate_field("mouse"));
}
mouse = Some(map.next_value::<MouseButtonWrapper>()?.into_inner());
},
Field::Command => {
if command.is_some() {
return Err(<V::Error as Error>::duplicate_field("command"));
}
command = Some(map.next_value::<Program>()?);
},
}
}
let mode = mode.unwrap_or_else(BindingMode::empty);
let not_mode = not_mode.unwrap_or_else(BindingMode::empty);
let mods = mods.unwrap_or_default();
let action = match (action, chars, command) {
(Some(action @ Action::ViMotion(_)), None, None)
| (Some(action @ Action::Vi(_)), None, None) => action,
(Some(action @ Action::Search(_)), None, None) => action,
(Some(action @ Action::Mouse(_)), None, None) => {
if mouse.is_none() {
return Err(V::Error::custom(format!(
"action `{}` is only available for mouse bindings",
action,
)));
}
action
},
(Some(action), None, None) => action,
(None, Some(chars), None) => Action::Esc(chars),
(None, None, Some(cmd)) => Action::Command(cmd),
_ => {
return Err(V::Error::custom(
"must specify exactly one of chars, action or command",
));
},
};
if mouse.is_none() && key.is_none() {
return Err(V::Error::custom("bindings require mouse button or key"));
}
Ok(RawBinding { mode, notmode: not_mode, action, key, mouse, mods })
}
}
deserializer.deserialize_struct("RawBinding", FIELDS, RawBindingVisitor)
}
}
impl<'a> Deserialize<'a> for MouseBinding {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
let raw = RawBinding::deserialize(deserializer)?;
raw.into_mouse_binding()
.map_err(|_| D::Error::custom("expected mouse binding, got key binding"))
}
}
impl<'a> Deserialize<'a> for KeyBinding {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
let raw = RawBinding::deserialize(deserializer)?;
raw.into_key_binding()
.map_err(|_| D::Error::custom("expected key binding, got mouse binding"))
}
}
/// Newtype for implementing deserialize on winit Mods.
///
/// Our deserialize impl wouldn't be covered by a derive(Deserialize); see the
/// impl below.
#[derive(SerdeReplace, Debug, Copy, Clone, Hash, Default, Eq, PartialEq)]
pub struct ModsWrapper(pub ModifiersState);
impl ModsWrapper {
pub fn into_inner(self) -> ModifiersState {
self.0
}
}
impl<'a> de::Deserialize<'a> for ModsWrapper {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'a>,
{
struct ModsVisitor;
impl<'a> Visitor<'a> for ModsVisitor {
type Value = ModsWrapper;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("None or a subset of Shift|Control|Super|Command|Alt|Option")
}
fn visit_str<E>(self, value: &str) -> Result<ModsWrapper, E>
where
E: de::Error,
{
let mut res = ModifiersState::empty();
for modifier in value.split('|') {
match modifier.trim().to_lowercase().as_str() {
"command" | "super" => res.insert(ModifiersState::SUPER),
"shift" => res.insert(ModifiersState::SHIFT),
"alt" | "option" => res.insert(ModifiersState::ALT),
"control" => res.insert(ModifiersState::CONTROL),
"none" => (),
_ => return Err(E::invalid_value(Unexpected::Str(modifier), &self)),
}
}
Ok(ModsWrapper(res))
}
}
deserializer.deserialize_str(ModsVisitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
use winit::keyboard::ModifiersState;
type MockBinding = Binding<usize>;
impl Default for MockBinding {
fn default() -> Self {
Self {
mods: Default::default(),
action: Action::None,
mode: BindingMode::empty(),
notmode: BindingMode::empty(),
trigger: Default::default(),
}
}
}
#[test]
fn binding_matches_itself() {
let binding = MockBinding::default();
let identical_binding = MockBinding::default();
assert!(binding.triggers_match(&identical_binding));
assert!(identical_binding.triggers_match(&binding));
}
#[test]
fn binding_matches_different_action() {
let binding = MockBinding::default();
let different_action =
MockBinding { action: Action::ClearHistory, ..MockBinding::default() };
assert!(binding.triggers_match(&different_action));
assert!(different_action.triggers_match(&binding));
}
#[test]
fn mods_binding_requires_strict_match() {
let superset_mods = MockBinding { mods: ModifiersState::all(), ..MockBinding::default() };
let subset_mods = MockBinding { mods: ModifiersState::ALT, ..MockBinding::default() };
assert!(!superset_mods.triggers_match(&subset_mods));
assert!(!subset_mods.triggers_match(&superset_mods));
}
#[test]
fn binding_matches_identical_mode() {
let b1 = MockBinding { mode: BindingMode::ALT_SCREEN, ..MockBinding::default() };
let b2 = MockBinding { mode: BindingMode::ALT_SCREEN, ..MockBinding::default() };
assert!(b1.triggers_match(&b2));
assert!(b2.triggers_match(&b1));
}
#[test]
fn binding_without_mode_matches_any_mode() {
let b1 = MockBinding::default();
let b2 = MockBinding {
mode: BindingMode::APP_KEYPAD,
notmode: BindingMode::ALT_SCREEN,
..MockBinding::default()
};
assert!(b1.triggers_match(&b2));
}
#[test]
fn binding_with_mode_matches_empty_mode() {
let b1 = MockBinding {
mode: BindingMode::APP_KEYPAD,
notmode: BindingMode::ALT_SCREEN,
..MockBinding::default()
};
let b2 = MockBinding::default();
assert!(b1.triggers_match(&b2));
assert!(b2.triggers_match(&b1));
}
#[test]
fn binding_matches_modes() {
let b1 = MockBinding {
mode: BindingMode::ALT_SCREEN | BindingMode::APP_KEYPAD,
..MockBinding::default()
};
let b2 = MockBinding { mode: BindingMode::APP_KEYPAD, ..MockBinding::default() };
assert!(b1.triggers_match(&b2));
assert!(b2.triggers_match(&b1));
}
#[test]
fn binding_matches_partial_intersection() {
let b1 = MockBinding {
mode: BindingMode::ALT_SCREEN | BindingMode::APP_KEYPAD,
..MockBinding::default()
};
let b2 = MockBinding {
mode: BindingMode::APP_KEYPAD | BindingMode::APP_CURSOR,
..MockBinding::default()
};
assert!(b1.triggers_match(&b2));
assert!(b2.triggers_match(&b1));
}
#[test]
fn binding_mismatches_notmode() {
let b1 = MockBinding { mode: BindingMode::ALT_SCREEN, ..MockBinding::default() };
let b2 = MockBinding { notmode: BindingMode::ALT_SCREEN, ..MockBinding::default() };
assert!(!b1.triggers_match(&b2));
assert!(!b2.triggers_match(&b1));
}
#[test]
fn binding_mismatches_unrelated() {
let b1 = MockBinding { mode: BindingMode::ALT_SCREEN, ..MockBinding::default() };
let b2 = MockBinding { mode: BindingMode::APP_KEYPAD, ..MockBinding::default() };
assert!(!b1.triggers_match(&b2));
assert!(!b2.triggers_match(&b1));
}
#[test]
fn binding_matches_notmodes() {
let subset_notmodes = MockBinding {
notmode: BindingMode::VI | BindingMode::APP_CURSOR,
..MockBinding::default()
};
let superset_notmodes =
MockBinding { notmode: BindingMode::APP_CURSOR, ..MockBinding::default() };
assert!(subset_notmodes.triggers_match(&superset_notmodes));
assert!(superset_notmodes.triggers_match(&subset_notmodes));
}
#[test]
fn binding_matches_mode_notmode() {
let b1 = MockBinding {
mode: BindingMode::VI,
notmode: BindingMode::APP_CURSOR,
..MockBinding::default()
};
let b2 = MockBinding { notmode: BindingMode::APP_CURSOR, ..MockBinding::default() };
assert!(b1.triggers_match(&b2));
assert!(b2.triggers_match(&b1));
}
#[test]
fn binding_trigger_input() {
let binding = MockBinding { trigger: 13, ..MockBinding::default() };
let mods = binding.mods;
let mode = binding.mode;
assert!(binding.is_triggered_by(mode, mods, &13));
assert!(!binding.is_triggered_by(mode, mods, &32));
}
#[test]
fn binding_trigger_mods() {
let binding = MockBinding {
mods: ModifiersState::ALT | ModifiersState::SUPER,
..MockBinding::default()
};
let superset_mods = ModifiersState::all();
let subset_mods = ModifiersState::empty();
let t = binding.trigger;
let mode = binding.mode;
assert!(binding.is_triggered_by(mode, binding.mods, &t));
assert!(!binding.is_triggered_by(mode, superset_mods, &t));
assert!(!binding.is_triggered_by(mode, subset_mods, &t));
}
#[test]
fn binding_trigger_modes() {
let binding = MockBinding { mode: BindingMode::ALT_SCREEN, ..MockBinding::default() };
let t = binding.trigger;
let mods = binding.mods;
assert!(!binding.is_triggered_by(BindingMode::VI, mods, &t));
assert!(binding.is_triggered_by(BindingMode::ALT_SCREEN, mods, &t));
assert!(binding.is_triggered_by(BindingMode::ALT_SCREEN | BindingMode::VI, mods, &t));
}
#[test]
fn binding_trigger_notmodes() {
let binding = MockBinding { notmode: BindingMode::ALT_SCREEN, ..MockBinding::default() };
let t = binding.trigger;
let mods = binding.mods;
assert!(binding.is_triggered_by(BindingMode::VI, mods, &t));
assert!(!binding.is_triggered_by(BindingMode::ALT_SCREEN, mods, &t));
assert!(!binding.is_triggered_by(BindingMode::ALT_SCREEN | BindingMode::VI, mods, &t));
}
}
|
//! fonctions printing a tree or a path
use {
crate::{
app::*,
display::{DisplayableTree, Screen},
errors::ProgramError,
launchable::Launchable,
skin::{ExtColorMap, PanelSkin, StyleMap},
tree::Tree,
},
crossterm::tty::IsTty,
pathdiff,
std::{
fs::OpenOptions,
io::{self, Write, stdout},
path::Path,
},
};
fn print_string(string: String, con: &AppContext) -> io::Result<CmdResult> {
Ok(
if let Some(ref output_path) = con.launch_args.file_export_path {
// an output path was provided, we write to it
let f = OpenOptions::new()
.create(true)
.append(true)
.open(output_path)?;
writeln!(&f, "{}", string)?;
CmdResult::Quit
} else {
// no output path provided. We write on stdout, but we must
// do it after app closing to have the desired stdout (it may
// be the normal terminal or a file, or other output)
CmdResult::from(Launchable::printer(string))
}
)
}
pub fn print_paths(sel_info: &SelInfo, con: &AppContext) -> io::Result<CmdResult> {
let string = match sel_info {
SelInfo::None => "".to_string(), // better idea ?
SelInfo::One(sel) => sel.path.to_string_lossy().to_string(),
SelInfo::More(stage) => {
let mut string = String::new();
for path in stage.paths().iter() {
string.push_str(&path.to_string_lossy());
string.push('\n');
}
string
}
};
print_string(string, con)
}
fn relativize_path(path: &Path, con: &AppContext) -> io::Result<String> {
let relative_path = match pathdiff::diff_paths(path, &con.launch_args.root) {
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Cannot relativize {:?}", path), // does this happen ? how ?
));
}
Some(p) => p,
};
Ok(
if relative_path.components().next().is_some() {
relative_path.to_string_lossy().to_string()
} else {
".".to_string()
}
)
}
pub fn print_relative_paths(sel_info: &SelInfo, con: &AppContext) -> io::Result<CmdResult> {
let string = match sel_info {
SelInfo::None => "".to_string(),
SelInfo::One(sel) => relativize_path(sel.path, con)?,
SelInfo::More(stage) => {
let mut string = String::new();
for path in stage.paths().iter() {
string.push_str(&relativize_path(path, con)?);
string.push('\n');
}
string
}
};
print_string(string, con)
}
fn print_tree_to_file(
tree: &Tree,
screen: Screen,
file_path: &str,
ext_colors: &ExtColorMap,
) -> Result<CmdResult, ProgramError> {
let no_style_skin = StyleMap::no_term();
let dp = DisplayableTree::out_of_app(
tree,
&no_style_skin,
ext_colors,
screen.width,
(tree.lines.len() as u16).min(screen.height),
);
let mut f = OpenOptions::new()
.create(true)
.append(true)
.open(file_path)?;
dp.write_on(&mut f)?;
Ok(CmdResult::Quit)
}
pub fn print_tree(
tree: &Tree,
screen: Screen,
panel_skin: &PanelSkin,
con: &AppContext,
) -> Result<CmdResult, ProgramError> {
if let Some(ref output_path) = con.launch_args.file_export_path {
// an output path was provided, we write to it
print_tree_to_file(tree, screen, output_path, &con.ext_colors)
} else {
// no output path provided. We write on stdout, but we must
// do it after app closing to have the normal terminal
let show_color = con.launch_args
.color
.unwrap_or_else(|| stdout().is_tty());
let styles = if show_color {
panel_skin.styles.clone()
} else {
StyleMap::no_term()
};
Ok(CmdResult::from(Launchable::tree_printer(
tree,
screen,
styles,
con.ext_colors.clone(),
)))
}
}
|
pub fn square_of_sum(n: usize) -> usize {
(1..=n).fold(0, |a, b| a + b).pow(2)
}
pub fn sum_of_squares(n: usize) -> usize {
(1..=n).map(|a| a.pow(2)).sum()
}
pub fn difference(n: usize) -> usize {
square_of_sum(n) - sum_of_squares(n)
}
|
use std::{
pin::Pin,
task::{Context, Poll},
};
use futures_core::ready;
use pin_project_lite::pin_project;
use crate::{
actor::Actor,
fut::{ActorFuture, ActorStream},
};
pin_project! {
/// Future for the [`finish`](super::ActorStreamExt::finish) method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Finish<S> {
#[pin]
pub(crate) stream: S
}
}
impl<S> Finish<S> {
pub fn new(stream: S) -> Finish<S> {
Finish { stream }
}
}
impl<S, A> ActorFuture<A> for Finish<S>
where
S: ActorStream<A>,
A: Actor,
{
type Output = ();
fn poll(
mut self: Pin<&mut Self>,
act: &mut A,
ctx: &mut A::Context,
task: &mut Context<'_>,
) -> Poll<()> {
let mut this = self.as_mut().project();
while ready!(this.stream.as_mut().poll_next(act, ctx, task)).is_some() {}
Poll::Ready(())
}
}
|
use std::fs;
const NUM_COLS: usize = 31;
const NUM_ROWS: usize = 323;
const SLOPE_X: usize = 1;
const SLOPE_Y: usize = 2;
fn has_tree(map: [[bool; NUM_COLS]; NUM_ROWS], x: usize, y: usize) -> bool {
map[y % NUM_ROWS][x % NUM_COLS]
}
fn main() {
let contents = fs::read_to_string("input.txt")
.expect("Failed to read file");
let mut map = [[false; NUM_COLS]; NUM_ROWS];
for (y, line) in contents.trim().split("\n").enumerate() {
for (x, c) in line.chars().enumerate() {
map[y][x] = c == '#';
}
}
let mut x = 0;
let mut y = 0;
let mut num_trees = 0;
while y < NUM_ROWS {
if has_tree(map, x, y) {
num_trees += 1;
}
x += SLOPE_X;
y += SLOPE_Y;
}
println!("{}", num_trees);
}
|
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::path::Path;
use ahash::{AHashMap, AHashSet};
use crate::data_structures::{Slab, SlabKey};
use crate::fenwick_tree::FenwickTree;
use crate::traits::{CorpusDelta, Pool, SaveToStatsFolder, Stats};
use crate::{CompatibleWithObservations, PoolStorageIndex, ToCSV};
#[derive(Clone, Default)]
pub struct UniqueValuesPoolStats {
pub name: String,
pub size: usize,
}
impl ToCSV for UniqueValuesPoolStats {
#[no_coverage]
fn csv_headers(&self) -> Vec<crate::CSVField> {
vec![]
}
#[no_coverage]
fn to_csv_record(&self) -> Vec<crate::CSVField> {
vec![]
}
}
impl Display for UniqueValuesPoolStats {
#[no_coverage]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
nu_ansi_term::Color::Blue.paint(format!("{}({})", self.name, self.size))
)
}
}
impl Stats for UniqueValuesPoolStats {}
#[derive(Debug)]
struct Input<T>
where
T: Hash + Eq + Clone,
{
best_for_values: AHashSet<(usize, T)>,
data: PoolStorageIndex,
score: f64,
number_times_chosen: usize,
}
/// A pool that stores an input for each different value of each sensor counter
pub struct UniqueValuesPool<T>
where
T: Hash + Eq + Clone,
{
name: String,
complexities: Vec<AHashMap<T, f64>>,
inputs: Slab<Input<T>>,
best_input_for_value: Vec<AHashMap<T, SlabKey<Input<T>>>>,
ranked_inputs: FenwickTree,
stats: UniqueValuesPoolStats,
rng: fastrand::Rng,
}
impl<T> Debug for UniqueValuesPool<T>
where
T: Hash + Eq + Clone + Debug,
{
#[no_coverage]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UniqueValuesPool")
.field("complexities", &self.complexities)
// .field("highest_counts", &self.highest_counts)
.field("inputs", &self.inputs)
// .field("best_input_for_counter", &self.best_input_for_counter)
// .field("cumulative_score_inputs", &self.ranked_inputs)
.finish()
}
}
impl<T> UniqueValuesPool<T>
where
T: Hash + Eq + Clone,
{
#[no_coverage]
pub fn new(name: &str, size: usize) -> Self {
Self {
name: name.to_string(),
complexities: vec![AHashMap::new(); size],
inputs: Slab::new(),
best_input_for_value: vec![AHashMap::new(); size],
ranked_inputs: FenwickTree::new(vec![]),
stats: UniqueValuesPoolStats {
name: name.to_string(),
size: 0,
},
rng: fastrand::Rng::new(),
}
}
}
impl<T> Pool for UniqueValuesPool<T>
where
T: Hash + Eq + Clone,
{
type Stats = UniqueValuesPoolStats;
#[no_coverage]
fn stats(&self) -> Self::Stats {
self.stats.clone()
}
#[no_coverage]
fn get_random_index(&mut self) -> Option<PoolStorageIndex> {
let choice = self.ranked_inputs.sample(&self.rng)?;
let key = self.inputs.get_nth_key(choice);
let input = &mut self.inputs[key];
let old_rank = input.score / (input.number_times_chosen as f64);
input.number_times_chosen += 1;
let new_rank = input.score / (input.number_times_chosen as f64);
let delta = new_rank - old_rank;
self.ranked_inputs.update(choice, delta);
let data = self.inputs[key].data;
Some(data)
}
}
impl<T> SaveToStatsFolder for UniqueValuesPool<T>
where
T: Hash + Eq + Clone,
{
#[no_coverage]
fn save_to_stats_folder(&self) -> Vec<(std::path::PathBuf, Vec<u8>)> {
vec![]
}
}
impl<T> UniqueValuesPool<T>
where
T: Hash + Eq + Clone,
{
#[no_coverage]
fn update_stats(&mut self) {
let inputs = &self.inputs;
let ranked_inputs = self
.inputs
.keys()
.map(
#[no_coverage]
|key| {
let input = &inputs[key];
input.score / (input.number_times_chosen as f64)
},
)
.collect();
self.ranked_inputs = FenwickTree::new(ranked_inputs);
self.stats.size = self.inputs.len();
}
}
impl<T, O> CompatibleWithObservations<O> for UniqueValuesPool<T>
where
for<'a> &'a O: IntoIterator<Item = &'a (usize, T)>,
T: Hash + Eq + Clone + Copy + 'static,
{
#[no_coverage]
fn process(&mut self, input_id: PoolStorageIndex, observations: &O, complexity: f64) -> Vec<CorpusDelta> {
let mut state = vec![];
for &(index, v) in observations.into_iter() {
if let Some(&previous_cplx) = self.complexities[index].get(&v) {
if previous_cplx > complexity {
// already exists but this one is better
state.push((index, v));
}
} else {
state.push((index, v));
}
}
if state.is_empty() {
return vec![];
}
let new_observations = state;
let score = new_observations.len() as f64;
let cplx = complexity;
let input = input_id;
let input = Input {
best_for_values: AHashSet::new(), // fill in later! with new_observations.into_iter().collect(),
data: input,
score,
number_times_chosen: 1,
};
let input_key = self.inputs.insert(input);
let mut removed_keys = vec![];
for (counter, id) in &new_observations {
self.complexities[*counter].insert(*id, cplx);
let previous_best_key = self.best_input_for_value[*counter].get_mut(id);
if let Some(previous_best_key) = previous_best_key {
let previous_best = &mut self.inputs[*previous_best_key];
let was_present_in_set = previous_best.best_for_values.remove(&(*counter, *id));
assert!(was_present_in_set);
previous_best.score = previous_best.best_for_values.len() as f64;
if previous_best.best_for_values.is_empty() {
removed_keys.push(*previous_best_key);
}
*previous_best_key = input_key;
} else {
self.best_input_for_value[*counter].insert(*id, input_key);
}
}
for &removed_key in &removed_keys {
self.inputs.remove(removed_key);
}
let removed_keys = removed_keys
.into_iter()
.map(
#[no_coverage]
|k| self.inputs[k].data,
)
.collect();
self.update_stats();
vec![CorpusDelta {
path: Path::new(&self.name).to_path_buf(),
add: true,
remove: removed_keys,
}]
}
}
|
impl Spanned for ast::Arg {
fn span(&self) -> Span {
aaaaaaaaaatoJson(
balancingCharges.map(|balancingCharge|
halResource(
obj(),
Seq(HalLink("self",
selfEmploymentSummaryTypeIdHref(saUtr, taxYear, seId, BalancingChargesSummaryType, balancingCharge.id.get))))))
}
}
|
use anyhow::{Context, Result};
use rand::Rng;
use serde::Deserialize;
use std::{
fs::File,
io::{stdin, BufRead, BufReader},
};
#[derive(Debug, Deserialize)]
struct Quote {
quotation: String,
speaker: String,
}
fn main() -> Result<()> {
let f = File::open("../datasets/quotes-2019-nytimes.json")
.context("Failed to open main json file,\n
the program expects the dataset to be located at ../datasets/ \n
from where you execute it")?;
let mut rdr = BufReader::new(f);
let mut line = String::new();
let mut quotes = Vec::new();
while rdr.read_line(&mut line).is_ok() {
if line.is_empty() {
break;
}
let quote: Quote =
serde_json::from_str(line.trim()).context("Failed to turn file into vec<Quote>")?;
quotes.push(quote);
line.clear();
}
let mut s = String::new();
let mut rng = rand::thread_rng();
println!("Enter q to quit, Enter any other string for 10 random quotes");
loop {
stdin()
.read_line(&mut s)
.context("Failed to read user input")?;
if s.trim() == "q" {
break;
} else {
(0..10)
.map(|_| rng.gen_range(0..quotes.len()))
.map(|index| ("es[index].quotation, "es[index].speaker))
.for_each(|(quotation, speaker)| {
println!("...");
println!("{} --- {}", quotation, speaker);
});
}
}
Ok(())
}
|
/*
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 22: Channel Management
#[derive(Default, Clone, Debug, PartialEq)]
pub struct ChannelManagement {
/// 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,
/// Channel A number (12 bits).
pub channel_a: u16,
/// Channel B number (12 bits).
pub channel_b: u16,
/// TxRx mode:
/// 0 = TxA/TxB, RxA/RxB (default)
/// 1 = TxA, RxA/RxB
/// 2 = TxB, RxA/RxB
/// 3 = Reserved for future use
pub txrx: u8,
/// Power level to be used:
/// 0 = low,
/// 1 = high
pub power: bool,
/// Northeast latitude to 0.1 minutes.
pub ne_lat: Option<f64>,
/// Northeast longitude to 0.1 minutes.
pub ne_lon: Option<f64>,
/// Southwest latitude to 0.1 minutes.
pub sw_lat: Option<f64>,
/// Southwest longitude to 0.1 minutes.
pub sw_lon: Option<f64>,
/// MMSI of destination 1 (30 bits).
pub dest1_mmsi: Option<u32>,
/// MMSI of destination 2 (30 bits).
pub dest2_mmsi: Option<u32>,
/// Addressed:
/// false = broadcast,
/// true = addressed
pub addressed: bool,
/// Channel A band:
/// false = default,
/// true = 12.5 kHz
pub channel_a_band: bool,
/// Channel B band:
/// false = default,
/// true = 12.5 kHz
pub channel_b_band: bool,
/// Size of transitional zone (3 bits).
pub zonesize: u8,
}
// -------------------------------------------------------------------------------------------------
/// AIS VDM/VDO type 22: Channel Management
pub(crate) fn handle(
bv: &BitVec,
station: Station,
own_vessel: bool,
) -> Result<ParsedMessage, ParseError> {
let addressed = pick_u64(&bv, 139, 1) != 0;
Ok(ParsedMessage::ChannelManagement(ChannelManagement {
own_vessel: { own_vessel },
station: { station },
mmsi: { pick_u64(&bv, 8, 30) as u32 },
channel_a: { pick_u64(&bv, 40, 12) as u16 },
channel_b: { pick_u64(&bv, 52, 12) as u16 },
txrx: { pick_u64(&bv, 64, 4) as u8 },
power: { pick_u64(&bv, 68, 1) != 0 },
ne_lat: {
if !addressed {
Some(pick_i64(&bv, 87, 17) as f64 / 600.0)
} else {
None
}
},
ne_lon: {
if !addressed {
Some(pick_i64(&bv, 69, 18) as f64 / 600.0)
} else {
None
}
},
sw_lat: {
if !addressed {
Some(pick_i64(&bv, 122, 17) as f64 / 600.0)
} else {
None
}
},
sw_lon: {
if !addressed {
Some(pick_i64(&bv, 104, 18) as f64 / 600.0)
} else {
None
}
},
dest1_mmsi: {
if addressed {
Some(pick_u64(&bv, 69, 30) as u32)
} else {
None
}
},
dest2_mmsi: {
if addressed {
Some(pick_u64(&bv, 104, 30) as u32)
} else {
None
}
},
addressed: { pick_u64(&bv, 139, 1) != 0 },
channel_a_band: { pick_u64(&bv, 140, 1) != 0 },
channel_b_band: { pick_u64(&bv, 141, 1) != 0 },
zonesize: { pick_u64(&bv, 142, 3) as u8 },
}))
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_vdm_type22() {
let mut p = NmeaParser::new();
match p.parse_sentence("!AIVDM,1,1,,A,F030ot22N2P6aoQbhe4736L20000,0*1A") {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::ChannelManagement(cm) => {
assert_eq!(cm.mmsi, 3160048);
assert_eq!(cm.channel_a, 2087);
assert_eq!(cm.channel_b, 2088);
assert_eq!(cm.txrx, 0);
assert_eq!(cm.power, false);
assert::close(cm.ne_lat.unwrap_or(0.0), 45.55, 0.01);
assert::close(cm.ne_lon.unwrap_or(0.0), -73.50, 0.01);
assert::close(cm.sw_lat.unwrap_or(0.0), 42.33, 0.01);
assert::close(cm.sw_lon.unwrap_or(0.0), -80.17, 0.01);
assert_eq!(cm.addressed, false);
assert_eq!(cm.channel_a_band, false);
assert_eq!(cm.channel_b_band, false);
assert_eq!(cm.zonesize, 4);
}
ParsedMessage::Incomplete => {
assert!(false);
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
}
}
|
use datafusion::common::tree_node::Transformed;
use datafusion::error::Result as DataFusionResult;
use datafusion::prelude::{lit, Column, Expr};
use super::MEASUREMENT_COLUMN_NAME;
/// Rewrites all references to the [MEASUREMENT_COLUMN_NAME] column
/// with the actual table name
pub(crate) fn rewrite_measurement_references(
table_name: &str,
expr: Expr,
) -> DataFusionResult<Transformed<Expr>> {
Ok(match expr {
// rewrite col("_measurement") --> "table_name"
Expr::Column(Column { relation, name }) if name == MEASUREMENT_COLUMN_NAME => {
// should not have a qualified foo._measurement
// reference
assert!(relation.is_none());
Transformed::Yes(lit(table_name))
}
// no rewrite needed
_ => Transformed::No(expr),
})
}
|
use std::{thread, time};
use std::path::{Path};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use log::{debug, info, warn, error};
use serde_derive::Deserialize;
use signal_hook;
mod amdgpu;
mod control;
use control::ControlCurve;
fn main() {
env_logger::from_env(
env_logger::Env::default().default_filter_or("info")
).init();
match run() {
Err(err) => {
error!("Exited with error: {}", err);
std::process::exit(1)
},
Ok(_) => std::process::exit(0),
}
}
fn run() -> Result<(), Error> {
let config_files = vec![
"amdgpu-fan.toml",
"/etc/amdgpu-fan.toml",
];
let config = load_config(config_files.iter())?;
info!("Card: {}", config.control.card_path.display());
info!("Poll: {}ms", config.control.poll_interval_millis);
let mut hwmons = amdgpu::Hwmon::for_device(config.control.card_path)?;
let mut device = hwmons.pop().ok_or(Error::CouldNotFindDevice)?;
let exit = Arc::new(AtomicBool::new(false));
signal_hook::flag::register(signal_hook::SIGTERM, Arc::clone(&exit))?;
signal_hook::flag::register(signal_hook::SIGINT, Arc::clone(&exit))?;
device.set_pwm_mode(amdgpu::PwmMode::Manual)?;
info!("Native fan control disabled");
let curve = config.curve.to_curve();
let poll_interval = time::Duration::from_millis(config.control.poll_interval_millis);
let result = control_loop(&mut device, poll_interval, &curve, exit);
if let Err(_) = &result {
info!("Control loop aborted");
} else {
info!("Control loop stopped");
}
if let Err(err) = device.set_pwm_mode(amdgpu::PwmMode::Automatic) {
error!("Could not restore native fan control: {}", err);
} else {
info!("Native fan control restored");
}
result.map_err(Into::into)
}
fn control_loop(device: &mut amdgpu::Hwmon, poll_interval: time::Duration, curve: &ControlCurve, exit_var: Arc<AtomicBool>) -> Result<(), amdgpu::GpuError> {
while !exit_var.load(Ordering::Relaxed) {
let temperature_celcius = device.get_temperature()?.as_celcius();
let fan_speed_relative = curve.control(temperature_celcius);
let fan_speed_pwm = amdgpu::Pwm::from_percentage(device.get_pwm_min(), device.get_pwm_max(), fan_speed_relative)?;
debug!("T_cur={: >5.1}°C\tV_rel={: >5.1}%\tV_pwm={: >3}", temperature_celcius, fan_speed_relative * 100.0, fan_speed_pwm.as_raw());
device.set_pwm(fan_speed_pwm)?;
thread::sleep(poll_interval);
}
Ok(())
}
pub enum Error {
ConfigParse(toml::de::Error),
ConfigIo(std::io::Error),
Control(amdgpu::GpuError),
ConfigurationMissing,
InvalidCurve,
CouldNotFindDevice,
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
Error::ConfigIo(err)
}
}
impl From<toml::de::Error> for Error {
fn from(err: toml::de::Error) -> Error {
Error::ConfigParse(err)
}
}
impl From<amdgpu::GpuError> for Error {
fn from(err: amdgpu::GpuError) -> Error {
Error::Control(err)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self {
&Error::ConfigIo(err) => write!(f, "{}", err),
&Error::ConfigParse(err) => write!(f, "{}", err),
&Error::Control(err) => write!(f, "{}", err),
&Error::InvalidCurve => write!(f, "Curve definition must contain at least one entry, and an equal number of temperatures and fan speeds."),
&Error::ConfigurationMissing => write!(f, "No valid configuration file found"),
&Error::CouldNotFindDevice => write!(f, "No HWMON entry found for the selected card"),
}
}
}
#[derive(Debug, Deserialize)]
struct Config {
curve: CurveConfig,
control: ControlConfig,
}
#[derive(Debug, Deserialize)]
struct CurveConfig {
temperatures: Vec<f64>,
fan_speeds: Vec<f64>,
}
impl CurveConfig {
fn to_curve(&self) -> ControlCurve {
ControlCurve::new(
self.temperatures.iter().cloned()
.zip(self.fan_speeds.iter().cloned())
.collect::<Vec<_>>()
)
}
}
#[derive(Debug, Deserialize)]
struct ControlConfig {
card_path: std::path::PathBuf,
poll_interval_millis: u64,
}
fn load_config<I, P>(paths_to_check: I) -> Result<Config, Error> where
I: Iterator<Item=P>,
P: AsRef<Path>
{
paths_to_check
.map(|path| {
let cfg_result = load_config_file(path.as_ref());
(path, cfg_result)
})
.find_map(|(path, cfg)| match cfg {
Ok(cfg) => {
info!("{}: loaded", path.as_ref().display());
Some(cfg)
},
Err(Error::ConfigIo(ref io_err)) if io_err.kind() == std::io::ErrorKind::NotFound => {
info!("{}: {}", path.as_ref().display(), io_err);
None
},
Err(cfg_err) => {
warn!("{}: {}", path.as_ref().display(), cfg_err);
None
}
})
.ok_or(Error::ConfigurationMissing)
}
fn load_config_file(path: &Path) -> Result<Config, Error> {
let contents = std::fs::read_to_string(path)?;
let config = toml::from_str::<Config>(contents.as_ref())?;
if config.curve.temperatures.len() != config.curve.fan_speeds.len()
|| config.curve.temperatures.is_empty() {
Err(Error::InvalidCurve)
} else {
Ok(config)
}
} |
fn main() {
#[derive(Debug, PartialEq)]
struct Foo {
lorem: &'static str,
ipsum: u32,
dolor: Result<String, String>,
}
let x = Some(Foo {
lorem: "Hello World!",
ipsum: 42,
dolor: Ok("hey".to_string()),
});
let y = Some(Foo {
lorem: "Hello Wrold!",
ipsum: 42,
dolor: Ok("hey ho!".to_string()),
});
assert_eq!(x, y);
}
|
use crate::graph::JsGraph;
use js_sys::{Array, Function};
use std::collections::HashMap;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(js_name = coarsen)]
pub fn js_coarsen(
graph: &JsGraph,
groups: &Function,
shrink_node: &Function,
shrink_edge: &Function,
) -> Result<JsValue, JsValue> {
let graph = graph.graph();
let mut group_map = HashMap::new();
for u in graph.node_indices() {
let group = groups
.call1(&JsValue::null(), &JsValue::from_f64(u.index() as f64))?
.as_f64()
.ok_or_else(|| format!("group[{}] is not a number", u.index()))?
as usize;
group_map.insert(u, group);
}
let (coarsened_graph, group_ids) = petgraph_clustering::coarsen(
graph,
&mut |_, u| {
let u = JsValue::from_f64(u.index() as f64);
groups
.call1(&JsValue::null(), &u)
.unwrap()
.as_f64()
.unwrap() as usize
},
&mut |_, node_ids| {
let node_ids = node_ids
.iter()
.map(|u| JsValue::from_f64(u.index() as f64))
.collect::<Array>();
shrink_node.call1(&JsValue::null(), &node_ids).unwrap()
},
&mut |_, edge_ids| {
let edge_ids = edge_ids
.iter()
.map(|u| JsValue::from_f64(u.index() as f64))
.collect::<Array>();
shrink_edge.call1(&JsValue::null(), &edge_ids).unwrap()
},
);
let group_ids = group_ids
.into_iter()
.map(|(group, node_id)| (group, node_id.index()))
.collect::<HashMap<_, _>>();
let result = Array::new();
result.push(&JsGraph::new_from_graph(coarsened_graph).into());
result.push(&serde_wasm_bindgen::to_value(&group_ids).unwrap());
Ok(result.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.
use std::ops::Deref;
trait PointerFamily<U> {
type Pointer<T>: Deref<Target = T>;
//~^ ERROR generic associated types are unstable
type Pointer2<T>: Deref<Target = T> where T: Clone, U: Clone;
//~^ ERROR generic associated types are unstable
//~| ERROR where clauses on associated types are unstable
}
struct Foo;
impl PointerFamily<u32> for Foo {
type Pointer<usize> = Box<usize>;
//~^ ERROR generic associated types are unstable
type Pointer2<u32> = Box<u32>;
//~^ ERROR generic associated types are unstable
}
trait Bar {
type Assoc where Self: Sized;
//~^ ERROR where clauses on associated types are unstable
}
fn main() {}
|
// An attribute to hide warnings for unused code.
#![allow(dead_code)]
// c-type struct
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
// A unit struct
struct Unit;
// A tuple struct
struct Pair(i32, f32);
// A struct with two fields
#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
// Structs can be reused as fields of another struct
#[derive(Debug)]
struct Rectangle {
// A rectangle can be specified by where the top left and bottom right
// corners are in space.
top_left: Point,
bottom_right: Point,
}
fn rect_area(rect:Rectangle) -> f32{
println!("rectangle: {rect:?}");
let Rectangle{top_left: Point{x: x1, y: y1},bottom_right: Point{x: x2, y: y2}} = rect;
(x2-x1) * (y1-y2)
}
// point p is moved into the rectangle.
fn square(p:Point, size:f32)-> Rectangle {
let p2 = Point{x: p.x+size, y:p.y-size};
Rectangle{top_left: p, bottom_right: p2}
}
fn main(){
let rex = Rectangle{top_left: Point{x:1.0, y:1.0}, bottom_right: Point{x:1.0, y:1.0}};
println!("{:?}",rex);
let name = String::from("Tito");
let age = 8u8;
let dude = Person{name, age};
println!("{dude:?}");
println!("point coordinates: ({}, {})", rex.top_left.x, rex.top_left.y);
// ..rex.bottom_right is a bit of rust magic,
// https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
// it uses the fields from another object to fill the values not explicitly specified.
let bottom_right = Point{x:5.2, ..rex.bottom_right};
println!("br {bottom_right:?}");
// Destructure the point using a `let` binding
let Point { x: left_edge, y: top_edge } = bottom_right;
println!("le:{left_edge}, te:{top_edge}");
let mut rectangle = Rectangle {
// struct instantiation is an expression too
top_left: Point { x: left_edge, y: top_edge },
bottom_right,
};
rectangle.top_left.x = 0.0;
rectangle.top_left.y = 4.0;
// Instantiate a unit struct
let _unit = Unit;
// Instantiate a tuple struct
let pair = Pair(1, 0.1);
// Access the fields of a tuple struct
println!("pair contains {:?} and {:?}", pair.0, pair.1);
// Destructure a tuple struct, uses () instead of {} for destructuring a struct.
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
println!("area: {:.5}", rect_area(rectangle));
println!("square: {:?}", square(Point{x:0.0, y:0.0}, 5.0));
} |
//! All this crate does is make bit masking
//! operations a bit prettier.
use std::ops::{
BitOrAssign,
BitXorAssign,
BitAndAssign,
Not,
BitAnd,
};
/// The trait describing things which can have
/// bit masks applied to them. All integer types
/// (and `bool`) implement this trait.
pub trait BitMaskable
where Self: Copy +
BitOrAssign +
BitXorAssign +
BitAndAssign +
Not<Output = Self> +
BitAnd<Self, Output = Self> +
Eq,
{
/// Applies a bit mask.
fn mask(&mut self, mask: Self);
/// Flips the value of a bit mask.
fn flip(&mut self, mask: Self);
/// Removes a bit mask.
fn unmask(&mut self, mask: Self);
/// Checks whether a certain mask is currently applied.
fn masked(self, mask: Self) -> bool;
}
impl <B> BitMaskable for B
where B: Copy +
BitOrAssign +
BitXorAssign +
BitAndAssign +
Not<Output = B> +
BitAnd<B, Output = B> +
Eq,
{
#[inline(always)]
fn mask(&mut self, mask: B) {
*self |= mask;
}
#[inline(always)]
fn flip(&mut self, mask: B) {
*self ^= mask;
}
#[inline(always)]
fn unmask(&mut self, mask: B) {
*self &= !mask;
}
#[inline(always)]
fn masked(self, mask: B) -> bool {
self & mask == mask
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mask_works() {
let mut m: u32 = 0;
m.mask(128);
assert!(m.masked(128));
m.unmask(128);
assert!(!m.masked(128));
}
#[test]
fn flip_works() {
let mut m: u32 = 0;
m.flip(128);
assert!(m.masked(128));
m.flip(128);
assert!(!m.masked(128));
}
#[test]
fn multi_masks_work() {
let mut m: u32 = 0;
m.mask(1|2|4);
assert!(m.masked(1|2|4));
assert!(m.masked(2|4));
assert!(!m.masked(1|2|4|8));
m.unmask(2|4|8);
assert!(m.masked(1));
}
}
|
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use crate::lexer::preprocessor::context::PreprocContext;
use crate::lexer::{Lexer, LocToken, Token};
use crate::parser::expression::{Parameters, ParametersParser};
pub type ListInitialization = Parameters;
pub struct ListInitializationParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> ListInitializationParser<'a, 'b, PC> {
pub(crate) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(crate) fn parse(
self,
tok: Option<LocToken>,
) -> (Option<LocToken>, Option<ListInitialization>) {
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
if tok.tok != Token::LeftBrace {
return (Some(tok), None);
}
let pp = ParametersParser::new(self.lexer, Token::RightBrace);
pp.parse(None, None)
}
}
|
// 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.
//! The network manager allows clients to manage router device properties.
#![deny(missing_docs)]
#![deny(unreachable_patterns)]
extern crate fuchsia_syslog as syslog;
#[macro_use]
extern crate log;
mod event;
mod event_worker;
mod eventloop;
mod fidl_worker;
mod overnet_worker;
use crate::eventloop::EventLoop;
fn main() -> Result<(), failure::Error> {
syslog::init().expect("failed to initialize logger");
// Severity is set to debug during development.
fuchsia_syslog::set_severity(-2);
info!("Starting Network Manager!");
let mut executor = fuchsia_async::Executor::new()?;
let eventloop = EventLoop::new()?;
let r = executor.run_singlethreaded(eventloop.run());
warn!("Network Manager ended: {:?}", r);
r
}
|
#![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 AccessoryNotificationType(pub u32);
impl AccessoryNotificationType {
pub const None: Self = Self(0u32);
pub const Phone: Self = Self(1u32);
pub const Email: Self = Self(2u32);
pub const Reminder: Self = Self(4u32);
pub const Alarm: Self = Self(8u32);
pub const Toast: Self = Self(16u32);
pub const AppUninstalled: Self = Self(32u32);
pub const Dnd: Self = Self(64u32);
pub const DrivingMode: Self = Self(128u32);
pub const BatterySaver: Self = Self(256u32);
pub const Media: Self = Self(512u32);
pub const CortanaTile: Self = Self(1024u32);
pub const ToastCleared: Self = Self(2048u32);
pub const CalendarChanged: Self = Self(4096u32);
pub const VolumeChanged: Self = Self(8192u32);
pub const EmailReadStatusChanged: Self = Self(16384u32);
}
impl ::core::marker::Copy for AccessoryNotificationType {}
impl ::core::clone::Clone for AccessoryNotificationType {
fn clone(&self) -> Self {
*self
}
}
pub type AlarmNotificationTriggerDetails = *mut ::core::ffi::c_void;
pub type AppNotificationInfo = *mut ::core::ffi::c_void;
pub type BinaryId = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CalendarChangedEvent(pub i32);
impl CalendarChangedEvent {
pub const LostEvents: Self = Self(0i32);
pub const AppointmentAdded: Self = Self(1i32);
pub const AppointmentChanged: Self = Self(2i32);
pub const AppointmentDeleted: Self = Self(3i32);
pub const CalendarAdded: Self = Self(4i32);
pub const CalendarChanged: Self = Self(5i32);
pub const CalendarDeleted: Self = Self(6i32);
}
impl ::core::marker::Copy for CalendarChangedEvent {}
impl ::core::clone::Clone for CalendarChangedEvent {
fn clone(&self) -> Self {
*self
}
}
pub type CalendarChangedNotificationTriggerDetails = *mut ::core::ffi::c_void;
pub type CortanaTileNotificationTriggerDetails = *mut ::core::ffi::c_void;
pub type EmailAccountInfo = *mut ::core::ffi::c_void;
pub type EmailFolderInfo = *mut ::core::ffi::c_void;
pub type EmailNotificationTriggerDetails = *mut ::core::ffi::c_void;
pub type EmailReadNotificationTriggerDetails = *mut ::core::ffi::c_void;
pub type IAccessoryNotificationTriggerDetails = *mut ::core::ffi::c_void;
pub type MediaControlsTriggerDetails = *mut ::core::ffi::c_void;
pub type MediaMetadata = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallAudioEndpoint(pub i32);
impl PhoneCallAudioEndpoint {
pub const Default: Self = Self(0i32);
pub const Speaker: Self = Self(1i32);
pub const Handsfree: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneCallAudioEndpoint {}
impl ::core::clone::Clone for PhoneCallAudioEndpoint {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneCallDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneCallDirection(pub i32);
impl PhoneCallDirection {
pub const Incoming: Self = Self(0i32);
pub const Outgoing: Self = Self(1i32);
}
impl ::core::marker::Copy for PhoneCallDirection {}
impl ::core::clone::Clone for PhoneCallDirection {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneCallState(pub i32);
impl PhoneCallState {
pub const Unknown: Self = Self(0i32);
pub const Ringing: Self = Self(1i32);
pub const Talking: Self = Self(2i32);
pub const Held: Self = Self(3i32);
pub const Ended: Self = Self(4i32);
}
impl ::core::marker::Copy for PhoneCallState {}
impl ::core::clone::Clone for PhoneCallState {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneCallTransport(pub i32);
impl PhoneCallTransport {
pub const Cellular: Self = Self(0i32);
pub const Voip: Self = Self(1i32);
}
impl ::core::marker::Copy for PhoneCallTransport {}
impl ::core::clone::Clone for PhoneCallTransport {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneLineDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneLineRegistrationState(pub i32);
impl PhoneLineRegistrationState {
pub const Disconnected: Self = Self(0i32);
pub const Home: Self = Self(1i32);
pub const Roaming: Self = Self(2i32);
}
impl ::core::marker::Copy for PhoneLineRegistrationState {}
impl ::core::clone::Clone for PhoneLineRegistrationState {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhoneMediaType(pub i32);
impl PhoneMediaType {
pub const AudioOnly: Self = Self(0i32);
pub const AudioVideo: Self = Self(1i32);
}
impl ::core::marker::Copy for PhoneMediaType {}
impl ::core::clone::Clone for PhoneMediaType {
fn clone(&self) -> Self {
*self
}
}
pub type PhoneNotificationTriggerDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhoneNotificationType(pub i32);
impl PhoneNotificationType {
pub const NewCall: Self = Self(0i32);
pub const CallChanged: Self = Self(1i32);
pub const LineChanged: Self = Self(2i32);
pub const PhoneCallAudioEndpointChanged: Self = Self(3i32);
pub const PhoneMuteChanged: Self = Self(4i32);
}
impl ::core::marker::Copy for PhoneNotificationType {}
impl ::core::clone::Clone for PhoneNotificationType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PlaybackCapability(pub u32);
impl PlaybackCapability {
pub const None: Self = Self(0u32);
pub const Play: Self = Self(1u32);
pub const Pause: Self = Self(2u32);
pub const Stop: Self = Self(4u32);
pub const Record: Self = Self(8u32);
pub const FastForward: Self = Self(16u32);
pub const Rewind: Self = Self(32u32);
pub const Next: Self = Self(64u32);
pub const Previous: Self = Self(128u32);
pub const ChannelUp: Self = Self(256u32);
pub const ChannelDown: Self = Self(512u32);
}
impl ::core::marker::Copy for PlaybackCapability {}
impl ::core::clone::Clone for PlaybackCapability {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PlaybackCommand(pub i32);
impl PlaybackCommand {
pub const Play: Self = Self(0i32);
pub const Pause: Self = Self(1i32);
pub const Stop: Self = Self(2i32);
pub const Record: Self = Self(3i32);
pub const FastForward: Self = Self(4i32);
pub const Rewind: Self = Self(5i32);
pub const Next: Self = Self(6i32);
pub const Previous: Self = Self(7i32);
pub const ChannelUp: Self = Self(8i32);
pub const ChannelDown: Self = Self(9i32);
}
impl ::core::marker::Copy for PlaybackCommand {}
impl ::core::clone::Clone for PlaybackCommand {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PlaybackStatus(pub i32);
impl PlaybackStatus {
pub const None: Self = Self(0i32);
pub const TrackChanged: Self = Self(1i32);
pub const Stopped: Self = Self(2i32);
pub const Playing: Self = Self(3i32);
pub const Paused: Self = Self(4i32);
}
impl ::core::marker::Copy for PlaybackStatus {}
impl ::core::clone::Clone for PlaybackStatus {
fn clone(&self) -> Self {
*self
}
}
pub type ReminderNotificationTriggerDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct ReminderState(pub i32);
impl ReminderState {
pub const Active: Self = Self(0i32);
pub const Snoozed: Self = Self(1i32);
pub const Dismissed: Self = Self(2i32);
}
impl ::core::marker::Copy for ReminderState {}
impl ::core::clone::Clone for ReminderState {
fn clone(&self) -> Self {
*self
}
}
pub type SpeedDialEntry = *mut ::core::ffi::c_void;
pub type TextResponse = *mut ::core::ffi::c_void;
pub type ToastNotificationTriggerDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct VibrateState(pub i32);
impl VibrateState {
pub const RingerOffVibrateOff: Self = Self(0i32);
pub const RingerOffVibrateOn: Self = Self(1i32);
pub const RingerOnVibrateOff: Self = Self(2i32);
pub const RingerOnVibrateOn: Self = Self(3i32);
}
impl ::core::marker::Copy for VibrateState {}
impl ::core::clone::Clone for VibrateState {
fn clone(&self) -> Self {
*self
}
}
pub type VolumeInfo = *mut ::core::ffi::c_void;
|
// Copyright 2018 by caixw, All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
// @api GET /users 获取用户列表
// @apitags t1,t2
// @apiservers admin
// @apiquery page int default desc
// @apiquery size int default desc
// @apiquery state array.string [normal,lock] 状态码
//
// @apirequest object * 通用的请求主体
// @apiheader name optional desc
// @apiheader name1 optional desc
// @apiparam count int optional desc
// @apiparam list array.string optional desc
// @apiparam list.id int optional desc
// @apiparam list.name int reqiured desc
// @apiparam list.groups array.string optional.xxxx desc markdown enum:
// - xx1 xxxxx
// - xx2 xxxxx
// @apiexample application/json summary
// {
// count: 5,
// list: [
// {id:1, name: 'name1', 'groups': [1,2]},
// {id:2, name: 'name2', 'groups': [1,2]}
// ]
// }
//
// @apirequest object application/xml 特定的请求主体
//
// @apiresponse 200 array.object * 通用的返回内容定义
// @apiheader string required desc
// @apiparam id int reqiured desc
// @apiparam name string reqiured desc
// @apiparam group object reqiured desc
// @apiparam group.id int reqiured desc
//
// @apiresponse 404 object application/json 错误的返回内容
// @apiheader string required desc38G
// @apiparam code int reqiured desc
// @apiparam message string reqiured desc
// @apiparam detail array.object reqiured desc
// @apiparam detail.id string reqiured desc
// @apiparam detail.message string reqiured desc
//
// @apiCallback GET 回调内容
// @apirequest object application/xml 特定的请求主体
// @apiresponse 404 object application/json 错误的返回内容
fn users() {}
// @api GET /users/{id} 获取用户详情
// @apitags t1,t2
// @apiservers admin
// @apiParam id int required 用户 ID
//
// @apirequest object * 通用的请求主体
// @apiheader name2 optional desc
// @apiheader name1 optional markdown desc
// @apiparam id int optional desc
// @apiparam name int reqiured desc
// @apiparam groups array.string optional.xxxx desc markdown enum:
// - xx1 xxxxx
// - xx2 xxxxx
// @apiexample application/json summary
// {
// count: 5,
// list: [
// {id:1, name: 'name1', 'groups': [1,2]},
// {id:2, name: 'name2', 'groups': [1,2]}
// ]
// }
//
// @apirequest object application/xml 特定的请求主体
//
// @apiresponse 200 array.object * 通用的返回内容定义
// @apiheader string required desc
// @apiparam id int reqiured desc
// @apiparam name string reqiured desc
// @apiparam group object reqiured desc
// @apiparam group.id int reqiured desc
//
// @apiresponse 404 object application/json 错误的返回内容
// @apiheader string required desc38G
// @apiparam code int reqiured desc
// @apiparam message string reqiured desc
// @apiparam detail array.object reqiured desc
// @apiparam detail.id string reqiured desc
// @apiparam detail.message string reqiured desc
//
// @apiCallback GET 回调内容
// @apirequest object application/xml 特定的请求主体
// @apiresponse 404 object application/json 错误的返回内容
fn user() {}
|
#[doc = "Reader of register COMP7_CSR"]
pub type R = crate::R<u32, super::COMP7_CSR>;
#[doc = "Writer for register COMP7_CSR"]
pub type W = crate::W<u32, super::COMP7_CSR>;
#[doc = "Register COMP7_CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::COMP7_CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `COMP7EN`"]
pub type COMP7EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `COMP7EN`"]
pub struct COMP7EN_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7EN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `COMP7MODE`"]
pub type COMP7MODE_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `COMP7MODE`"]
pub struct COMP7MODE_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7MODE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 2)) | (((value as u32) & 0x03) << 2);
self.w
}
}
#[doc = "Reader of field `COMP7INMSEL`"]
pub type COMP7INMSEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `COMP7INMSEL`"]
pub struct COMP7INMSEL_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7INMSEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 4)) | (((value as u32) & 0x07) << 4);
self.w
}
}
#[doc = "Reader of field `COMP7INPSEL`"]
pub type COMP7INPSEL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `COMP7INPSEL`"]
pub struct COMP7INPSEL_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7INPSEL_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 `COMP7OUTSEL`"]
pub type COMP7OUTSEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `COMP7OUTSEL`"]
pub struct COMP7OUTSEL_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7OUTSEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 10)) | (((value as u32) & 0x0f) << 10);
self.w
}
}
#[doc = "Reader of field `COMP7POL`"]
pub type COMP7POL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `COMP7POL`"]
pub struct COMP7POL_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7POL_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `COMP7HYST`"]
pub type COMP7HYST_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `COMP7HYST`"]
pub struct COMP7HYST_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7HYST_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16);
self.w
}
}
#[doc = "Reader of field `COMP7_BLANKING`"]
pub type COMP7_BLANKING_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `COMP7_BLANKING`"]
pub struct COMP7_BLANKING_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7_BLANKING_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 18)) | (((value as u32) & 0x07) << 18);
self.w
}
}
#[doc = "Reader of field `COMP7OUT`"]
pub type COMP7OUT_R = crate::R<bool, bool>;
#[doc = "Reader of field `COMP7LOCK`"]
pub type COMP7LOCK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `COMP7LOCK`"]
pub struct COMP7LOCK_W<'a> {
w: &'a mut W,
}
impl<'a> COMP7LOCK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bit 0 - Comparator 7 enable"]
#[inline(always)]
pub fn comp7en(&self) -> COMP7EN_R {
COMP7EN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 2:3 - Comparator 7 mode"]
#[inline(always)]
pub fn comp7mode(&self) -> COMP7MODE_R {
COMP7MODE_R::new(((self.bits >> 2) & 0x03) as u8)
}
#[doc = "Bits 4:6 - Comparator 7 inverting input selection"]
#[inline(always)]
pub fn comp7inmsel(&self) -> COMP7INMSEL_R {
COMP7INMSEL_R::new(((self.bits >> 4) & 0x07) as u8)
}
#[doc = "Bit 7 - Comparator 7 non inverted input"]
#[inline(always)]
pub fn comp7inpsel(&self) -> COMP7INPSEL_R {
COMP7INPSEL_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bits 10:13 - Comparator 7 output selection"]
#[inline(always)]
pub fn comp7outsel(&self) -> COMP7OUTSEL_R {
COMP7OUTSEL_R::new(((self.bits >> 10) & 0x0f) as u8)
}
#[doc = "Bit 15 - Comparator 7 output polarity"]
#[inline(always)]
pub fn comp7pol(&self) -> COMP7POL_R {
COMP7POL_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bits 16:17 - Comparator 7 hysteresis"]
#[inline(always)]
pub fn comp7hyst(&self) -> COMP7HYST_R {
COMP7HYST_R::new(((self.bits >> 16) & 0x03) as u8)
}
#[doc = "Bits 18:20 - Comparator 7 blanking source"]
#[inline(always)]
pub fn comp7_blanking(&self) -> COMP7_BLANKING_R {
COMP7_BLANKING_R::new(((self.bits >> 18) & 0x07) as u8)
}
#[doc = "Bit 30 - Comparator 7 output"]
#[inline(always)]
pub fn comp7out(&self) -> COMP7OUT_R {
COMP7OUT_R::new(((self.bits >> 30) & 0x01) != 0)
}
#[doc = "Bit 31 - Comparator 7 lock"]
#[inline(always)]
pub fn comp7lock(&self) -> COMP7LOCK_R {
COMP7LOCK_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Comparator 7 enable"]
#[inline(always)]
pub fn comp7en(&mut self) -> COMP7EN_W {
COMP7EN_W { w: self }
}
#[doc = "Bits 2:3 - Comparator 7 mode"]
#[inline(always)]
pub fn comp7mode(&mut self) -> COMP7MODE_W {
COMP7MODE_W { w: self }
}
#[doc = "Bits 4:6 - Comparator 7 inverting input selection"]
#[inline(always)]
pub fn comp7inmsel(&mut self) -> COMP7INMSEL_W {
COMP7INMSEL_W { w: self }
}
#[doc = "Bit 7 - Comparator 7 non inverted input"]
#[inline(always)]
pub fn comp7inpsel(&mut self) -> COMP7INPSEL_W {
COMP7INPSEL_W { w: self }
}
#[doc = "Bits 10:13 - Comparator 7 output selection"]
#[inline(always)]
pub fn comp7outsel(&mut self) -> COMP7OUTSEL_W {
COMP7OUTSEL_W { w: self }
}
#[doc = "Bit 15 - Comparator 7 output polarity"]
#[inline(always)]
pub fn comp7pol(&mut self) -> COMP7POL_W {
COMP7POL_W { w: self }
}
#[doc = "Bits 16:17 - Comparator 7 hysteresis"]
#[inline(always)]
pub fn comp7hyst(&mut self) -> COMP7HYST_W {
COMP7HYST_W { w: self }
}
#[doc = "Bits 18:20 - Comparator 7 blanking source"]
#[inline(always)]
pub fn comp7_blanking(&mut self) -> COMP7_BLANKING_W {
COMP7_BLANKING_W { w: self }
}
#[doc = "Bit 31 - Comparator 7 lock"]
#[inline(always)]
pub fn comp7lock(&mut self) -> COMP7LOCK_W {
COMP7LOCK_W { w: self }
}
}
|
use hal::{
format::Format,
window::{
AcquireError, CreationError, Suboptimal, SurfaceCapabilities, SwapImageIndex,
SwapchainConfig,
},
};
use crate::Backend;
#[derive(Debug)]
pub struct Surface;
impl hal::window::Surface<Backend> for Surface {
fn supports_queue_family(&self, _family: &crate::QueueFamily) -> bool {
todo!()
}
fn capabilities(&self, _physical_device: &crate::PhysicalDevice) -> SurfaceCapabilities {
todo!()
}
fn supported_formats(&self, _physical_device: &crate::PhysicalDevice) -> Option<Vec<Format>> {
todo!()
}
}
impl hal::window::PresentationSurface<Backend> for Surface {
type SwapchainImage = ();
unsafe fn configure_swapchain(
&mut self,
_device: &crate::Device,
_config: SwapchainConfig,
) -> Result<(), CreationError> {
todo!()
}
unsafe fn unconfigure_swapchain(&mut self, _device: &crate::Device) {
todo!()
}
unsafe fn acquire_image(
&mut self,
_timeout_ns: u64,
) -> Result<(Self::SwapchainImage, Option<Suboptimal>), AcquireError> {
todo!()
}
}
|
use std::collections::HashMap;
use crate::error::ParameterError;
use crate::error::{PolarError, PolarResult};
pub use super::bindings::Bindings;
use super::counter::Counter;
use super::rules::*;
use super::sources::*;
use super::sugar::Namespaces;
use super::terms::*;
use std::sync::Arc;
enum RuleParamMatch {
True,
False(String),
}
impl RuleParamMatch {
#[cfg(test)]
fn is_true(&self) -> bool {
matches!(self, RuleParamMatch::True)
}
}
#[derive(Default)]
pub struct KnowledgeBase {
/// A map of bindings: variable name → value. The VM uses a stack internally,
/// but can translate to and from this type.
pub constants: Bindings,
/// Map of class name -> MRO list where the MRO list is a list of class instance IDs
mro: HashMap<Symbol, Vec<u64>>,
/// Map from loaded files to the source ID
pub loaded_files: HashMap<String, u64>,
/// Map from source code loaded to the filename it was loaded as
pub loaded_content: HashMap<String, String>,
rules: HashMap<Symbol, GenericRule>,
rule_prototypes: HashMap<Symbol, Vec<Rule>>,
pub sources: Sources,
/// For symbols returned from gensym.
gensym_counter: Counter,
/// For call IDs, instance IDs, symbols, etc.
id_counter: Counter,
pub inline_queries: Vec<Term>,
/// Namespace Bookkeeping
pub namespaces: Namespaces,
}
impl KnowledgeBase {
pub fn new() -> Self {
Self {
constants: HashMap::new(),
mro: HashMap::new(),
loaded_files: Default::default(),
loaded_content: Default::default(),
rules: HashMap::new(),
rule_prototypes: HashMap::new(),
sources: Sources::default(),
id_counter: Counter::default(),
gensym_counter: Counter::default(),
inline_queries: vec![],
namespaces: Namespaces::new(),
}
}
/// Return a monotonically increasing integer ID.
///
/// Wraps around at 52 bits of precision so that it can be safely
/// coerced to an IEEE-754 double-float (f64).
pub fn new_id(&self) -> u64 {
self.id_counter.next()
}
pub fn id_counter(&self) -> Counter {
self.id_counter.clone()
}
/// Generate a temporary variable prefix from a variable name.
pub fn temp_prefix(name: &str) -> String {
match name {
"_" => String::from(name),
_ => format!("_{}_", name),
}
}
/// Generate a new symbol.
pub fn gensym(&self, prefix: &str) -> Symbol {
let next = self.gensym_counter.next();
Symbol(format!("{}{}", Self::temp_prefix(prefix), next))
}
/// Add a generic rule to the knowledge base.
#[cfg(test)]
pub fn add_generic_rule(&mut self, rule: GenericRule) {
self.rules.insert(rule.name.clone(), rule);
}
pub fn add_rule(&mut self, rule: Rule) {
let generic_rule = self
.rules
.entry(rule.name.clone())
.or_insert_with(|| GenericRule::new(rule.name.clone(), vec![]));
generic_rule.add_rule(Arc::new(rule));
}
/// Validate that all rules loaded into the knowledge base are valid based on rule prototypes.
pub fn validate_rules(&self) -> PolarResult<()> {
for (rule_name, generic_rule) in &self.rules {
if let Some(prototypes) = self.rule_prototypes.get(rule_name) {
// If a prototype with the same name exists, then the parameters must match for each rule
for rule in generic_rule.rules.values() {
let mut msg = "Must match one of the following rule prototypes:\n".to_owned();
let found_match = prototypes
.iter()
.map(|prototype| {
self.rule_params_match(rule.as_ref(), prototype)
.map(|result| (result, prototype))
})
.collect::<PolarResult<Vec<(RuleParamMatch, &Rule)>>>()
.map(|results| {
results.iter().any(|(result, prototype)| match result {
RuleParamMatch::True => true,
RuleParamMatch::False(message) => {
msg.push_str(&format!(
"\n{}\n\tFailed to match because: {}\n",
prototype.to_polar(),
message
));
false
}
})
})?;
if !found_match {
return Err(self.set_error_context(
&rule.body,
error::ValidationError::InvalidRule {
rule: rule.to_polar(),
msg,
},
));
}
}
}
}
Ok(())
}
/// Determine whether the fields of a rule parameter specializer match the fields of a prototype parameter specializer.
/// Rule fields match if they are a superset of prototype fields and all field values are equal.
// TODO: once field-level specializers are working this should be updated so
// that it recursively checks all fields match, rather than checking for
// equality
fn param_fields_match(&self, prototype_fields: &Dictionary, rule_fields: &Dictionary) -> bool {
return prototype_fields
.fields
.iter()
.map(|(k, prototype_value)| {
rule_fields
.fields
.get(k)
.map(|rule_value| rule_value == prototype_value)
.unwrap_or_else(|| false)
})
.all(|v| v);
}
/// Check that a rule parameter that has a pattern specializer matches a prototype parameter that has a pattern specializer.
fn check_pattern_param(
&self,
index: usize,
rule_pattern: &Pattern,
prototype_pattern: &Pattern,
) -> PolarResult<RuleParamMatch> {
Ok(match (prototype_pattern, rule_pattern) {
(Pattern::Instance(prototype_instance), Pattern::Instance(rule_instance)) => {
// if tags match, all prototype fields must match those in rule fields, otherwise false
if prototype_instance.tag == rule_instance.tag {
if self.param_fields_match(
&prototype_instance.fields,
&rule_instance.fields,
) {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!("Rule specializer {} on parameter {} did not match prototype specializer {} because the specializer fields did not match.", rule_instance.to_polar(), index, prototype_instance.to_polar()))
}
// If tags don't match, then rule specializer must be a subclass of prototype specializer
} else if let Some(Value::ExternalInstance(ExternalInstance {
instance_id,
..
})) = self
.constants
.get(&prototype_instance.tag)
.map(|t| t.value())
{
if let Some(rule_mro) = self.mro.get(&rule_instance.tag) {
if !rule_mro.contains(instance_id) {
RuleParamMatch::False(format!("Rule specializer {} on parameter {} must be a subclass of prototype specializer {}", rule_instance.tag,index, prototype_instance.tag))
} else if !self.param_fields_match(
&prototype_instance.fields,
&rule_instance.fields,
)
{
RuleParamMatch::False(format!("Rule specializer {} on parameter {} did not match prototype specializer {} because the specializer fields did not match.", rule_instance.to_polar(), index, prototype_instance.to_polar()))
} else {
RuleParamMatch::True
}
} else {
return Err(error::OperationalError::InvalidState(format!(
"All registered classes must have a registered MRO. Class {} does not have a registered MRO.",
&rule_instance.tag
)).into());
}
} else {
unreachable!("Unregistered specializer classes should be caught before this point.");
}
}
(Pattern::Dictionary(prototype_fields), Pattern::Dictionary(rule_fields))
| (
Pattern::Dictionary(prototype_fields),
Pattern::Instance(InstanceLiteral {
tag: _,
fields: rule_fields,
}),
) => {
if self.param_fields_match(prototype_fields, rule_fields) {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!("Specializer mismatch on parameter {}. Rule specializer fields {:#?} do not match prototype specializer fields {:#?}.", index, rule_fields, prototype_fields))
}
}
(
Pattern::Instance(InstanceLiteral {
tag,
fields: prototype_fields,
}),
Pattern::Dictionary(rule_fields),
) if tag == &sym!("Dictionary") => {
if self.param_fields_match(prototype_fields, rule_fields) {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!("Specializer mismatch on parameter {}. Rule specializer fields {:#?} do not match prototype specializer fields {:#?}.", index, rule_fields, prototype_fields))
}
}
(_, _) => {
RuleParamMatch::False(format!("Mismatch on parameter {}. Rule parameter {:#?} does not match prototype parameter {:#?}.", index, prototype_pattern, rule_pattern))
}
})
}
/// Check that a rule parameter that is a value matches a prototype parameter that is a value
fn check_value_param(
&self,
index: usize,
rule_value: &Value,
prototype_value: &Value,
) -> PolarResult<RuleParamMatch> {
Ok(match (prototype_value, rule_value) {
(Value::List(prototype_list), Value::List(rule_list)) => {
if prototype_list.iter().all(|t| rule_list.contains(t)) {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!(
"Invalid parameter {}. Rule prototype expected list {:#?}, got list {:#?}.",
index, prototype_list, rule_list
))
}
}
(Value::Dictionary(prototype_fields), Value::Dictionary(rule_fields)) => {
if self.param_fields_match(prototype_fields, rule_fields) {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!("Invalid parameter {}. Rule prototype expected Dictionary with fields {:#?}, got Dictionary with fields {:#?}", index, prototype_fields, rule_fields
))
}
}
(_, _) => {
if prototype_value == rule_value {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!(
"Invalid parameter {}. Rule value {} != prototype value {}",
index, rule_value, prototype_value
))
}
}
})
}
/// Check a single rule parameter against a prototype parameter.
fn check_param(
&self,
index: usize,
rule_param: &Parameter,
prototype_param: &Parameter,
) -> PolarResult<RuleParamMatch> {
Ok(
match (
prototype_param.parameter.value(),
prototype_param.specializer.as_ref().map(Term::value),
rule_param.parameter.value(),
rule_param.specializer.as_ref().map(Term::value),
) {
// Rule and prototype both have pattern specializers
(
Value::Variable(_),
Some(Value::Pattern(prototype_spec)),
Value::Variable(_),
Some(Value::Pattern(rule_spec)),
) => self.check_pattern_param(index, rule_spec, prototype_spec)?,
// Prototype has specializer but rule doesn't
(Value::Variable(_), Some(prototype_spec), Value::Variable(_), None) => {
RuleParamMatch::False(format!(
"Invalid rule parameter {}. Rule prototype expected {}",
index,
prototype_spec.to_polar()
))
}
// Rule has value or value specializer, prototype has pattern specializer
(
Value::Variable(_),
Some(Value::Pattern(prototype_spec)),
Value::Variable(_),
Some(rule_value),
)
| (Value::Variable(_), Some(Value::Pattern(prototype_spec)), rule_value, None) => {
match prototype_spec {
// Prototype specializer is an instance pattern
Pattern::Instance(InstanceLiteral {
tag,
fields: prototype_fields,
}) => {
if match rule_value {
Value::String(_) => tag == &sym!("String"),
Value::Number(Numeric::Integer(_)) => tag == &sym!("Integer"),
Value::Number(Numeric::Float(_)) => tag == &sym!("Float"),
Value::Boolean(_) => tag == &sym!("Boolean"),
Value::List(_) => tag == &sym!("List"),
Value::Dictionary(rule_fields) => {
tag == &sym!("Dictionary")
&& self.param_fields_match(prototype_fields, rule_fields)
}
_ => {
unreachable!(
"Value variant {} cannot be a specializer",
rule_value
)
}
} {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!(
"Invalid parameter {}. Rule prototype expected {}, got {}. ",
index,
tag.to_polar(),
rule_value.to_polar()
))
}
}
// Prototype specializer is a dictionary pattern
Pattern::Dictionary(prototype_fields) => {
if let Value::Dictionary(rule_fields) = rule_value {
if self.param_fields_match(prototype_fields, rule_fields) {
RuleParamMatch::True
} else {
RuleParamMatch::False(format!("Invalid parameter {}. Rule prototype expected Dictionary with fields {}, got dictionary with fields {}.", index, prototype_fields.to_polar(), rule_fields.to_polar()))
}
} else {
RuleParamMatch::False(format!("Invalid parameter {}. Rule prototype expected Dictionary, got {}.", index, rule_value.to_polar()))
}
}
}
}
// Prototype has no specializer
(Value::Variable(_), None, _, _) => RuleParamMatch::True,
// Rule has value or value specializer, prototype has value specializer |
// rule has value, prototype has value
(
Value::Variable(_),
Some(prototype_value),
Value::Variable(_),
Some(rule_value),
)
| (Value::Variable(_), Some(prototype_value), rule_value, None)
| (prototype_value, None, rule_value, None) => {
self.check_value_param(index, rule_value, prototype_value)?
}
_ => RuleParamMatch::False(format!(
"Invalid parameter {}. Rule parameter {} does not match prototype parameter {}",
index,
rule_param.to_polar(),
prototype_param.to_polar()
)),
},
)
}
/// Determine whether a rule matches a rule prototype based on its parameters.
fn rule_params_match(&self, rule: &Rule, prototype: &Rule) -> PolarResult<RuleParamMatch> {
if rule.params.len() != prototype.params.len() {
return Ok(RuleParamMatch::False(format!(
"Different number of parameters. Rule has {} parameter(s) but prototype has {}.",
rule.params.len(),
prototype.params.len()
)));
}
let mut failure_message = "".to_owned();
rule.params
.iter()
.zip(prototype.params.iter())
.enumerate()
.map(|(i, (rule_param, prototype_param))| {
self.check_param(i + 1, rule_param, prototype_param)
})
.collect::<PolarResult<Vec<RuleParamMatch>>>()
.map(|results| {
results.iter().all(|r| {
if let RuleParamMatch::False(msg) = r {
failure_message = msg.to_owned();
false
} else {
true
}
})
})
.map(|matched| {
if matched {
RuleParamMatch::True
} else {
RuleParamMatch::False(failure_message)
}
})
}
pub fn get_rules(&self) -> &HashMap<Symbol, GenericRule> {
&self.rules
}
pub fn get_generic_rule(&self, name: &Symbol) -> Option<&GenericRule> {
self.rules.get(name)
}
pub fn add_rule_prototype(&mut self, prototype: Rule) {
let name = prototype.name.clone();
// get rule prototypes
let prototypes = self.rule_prototypes.entry(name).or_insert_with(Vec::new);
prototypes.push(prototype);
}
/// Define a constant variable.
pub fn constant(&mut self, name: Symbol, value: Term) {
self.constants.insert(name, value);
}
/// Add the Method Resolution Order (MRO) list for a registered class.
/// The `mro` argument is a list of the `instance_id` associated with a registered class.
pub fn add_mro(&mut self, name: Symbol, mro: Vec<u64>) -> PolarResult<()> {
// Confirm name is a registered class
self.constants.get(&name).ok_or_else(|| {
ParameterError(format!("Cannot add MRO for unregistered class {}", name))
})?;
self.mro.insert(name, mro);
Ok(())
}
/// Return true if a constant with the given name has been defined.
pub fn is_constant(&self, name: &Symbol) -> bool {
self.constants.contains_key(name)
}
pub fn add_source(&mut self, source: Source) -> PolarResult<u64> {
let src_id = self.new_id();
if let Some(ref filename) = source.filename {
self.check_file(&source.src, filename)?;
self.loaded_content
.insert(source.src.clone(), filename.to_string());
self.loaded_files.insert(filename.to_string(), src_id);
}
self.sources.add_source(source, src_id);
Ok(src_id)
}
pub fn clear_rules(&mut self) {
self.rules.clear();
self.rule_prototypes.clear();
self.sources = Sources::default();
self.inline_queries.clear();
self.loaded_content.clear();
self.loaded_files.clear();
}
/// Removes a file from the knowledge base by finding the associated
/// `Source` and removing all rules for that source, and
/// removes the file from loaded files.
///
/// Optionally return the source for the file, returning `None`
/// if the file was not in the loaded files.
pub fn remove_file(&mut self, filename: &str) -> Option<String> {
self.loaded_files
.get(filename)
.cloned()
.map(|src_id| self.remove_source(src_id))
}
/// Removes a source from the knowledge base by finding the associated
/// `Source` and removing all rules for that source. Will
/// also remove the loaded files if the source was loaded from a file.
pub fn remove_source(&mut self, source_id: u64) -> String {
// remove from rules
self.rules.retain(|_, gr| {
let to_remove: Vec<u64> = gr.rules.iter().filter_map(|(idx, rule)| {
if matches!(rule.source_info, SourceInfo::Parser { src_id, ..} if src_id == source_id) {
Some(*idx)
} else {
None
}
}).collect();
for idx in to_remove {
gr.remove_rule(idx);
}
!gr.rules.is_empty()
});
// remove from sources
let source = self
.sources
.remove_source(source_id)
.expect("source doesn't exist in KB");
let filename = source.filename;
// remove queries
self.inline_queries
.retain(|q| q.get_source_id() != Some(source_id));
// remove from files
if let Some(filename) = filename {
self.loaded_files.remove(&filename);
self.loaded_content.retain(|_, f| f != &filename);
}
source.src
}
fn check_file(&self, src: &str, filename: &str) -> PolarResult<()> {
match (
self.loaded_content.get(src),
self.loaded_files.get(filename).is_some(),
) {
(Some(other_file), true) if other_file == filename => {
return Err(error::RuntimeError::FileLoading {
msg: format!("File {} has already been loaded.", filename),
}
.into())
}
(_, true) => {
return Err(error::RuntimeError::FileLoading {
msg: format!(
"A file with the name {}, but different contents has already been loaded.",
filename
),
}
.into());
}
(Some(other_file), _) => {
return Err(error::RuntimeError::FileLoading {
msg: format!(
"A file with the same contents as {} named {} has already been loaded.",
filename, other_file
),
}
.into());
}
_ => {}
}
Ok(())
}
pub fn set_error_context(&self, term: &Term, error: impl Into<PolarError>) -> PolarError {
let source = term
.get_source_id()
.and_then(|id| self.sources.get_source(id));
let error: PolarError = error.into();
error.set_context(source.as_ref(), Some(term))
}
pub fn rewrite_implications(&mut self) -> PolarResult<()> {
let mut errors = vec![];
errors.append(&mut super::sugar::check_all_relation_types_have_been_registered(self));
// TODO(gj): Emit all errors instead of just the first.
if !errors.is_empty() {
self.namespaces.clear();
return Err(errors[0].clone());
}
let mut rules = vec![];
for (namespace, implications) in &self.namespaces.implications {
for implication in implications {
match implication.as_rule(namespace, &self.namespaces) {
Ok(rule) => rules.push(rule),
Err(error) => errors.push(error),
}
}
}
// If we've reached this point, we're all done with the namespaces.
self.namespaces.clear();
// TODO(gj): Emit all errors instead of just the first.
if !errors.is_empty() {
return Err(errors[0].clone());
}
// Add the rewritten rules to the KB.
for rule in rules {
self.add_rule(rule);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::*;
#[test]
fn test_rule_params_match() {
let mut kb = KnowledgeBase::new();
kb.constant(
sym!("Fruit"),
term!(Value::ExternalInstance(ExternalInstance {
instance_id: 1,
constructor: None,
repr: None
})),
);
kb.constant(
sym!("Citrus"),
term!(Value::ExternalInstance(ExternalInstance {
instance_id: 2,
constructor: None,
repr: None
})),
);
kb.constant(
sym!("Orange"),
term!(Value::ExternalInstance(ExternalInstance {
instance_id: 3,
constructor: None,
repr: None
})),
);
kb.add_mro(sym!("Fruit"), vec![1]).unwrap();
// Citrus is a subclass of Fruit
kb.add_mro(sym!("Citrus"), vec![2, 1]).unwrap();
// Orange is a subclass of Citrus
kb.add_mro(sym!("Orange"), vec![3, 2, 1]).unwrap();
// BOTH PATTERN SPEC
// rule: f(x: Foo), prototype: f(x: Foo) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; instance!(sym!("Fruit"))]),
&rule!("f", ["x"; instance!(sym!("Fruit"))])
)
.unwrap()
.is_true());
// rule: f(x: Foo), prototype: f(x: Bar) => FAIL if Foo is not subclass of Bar
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; instance!(sym!("Fruit"))]),
&rule!("f", ["x"; instance!(sym!("Citrus"))])
)
.unwrap()
.is_true());
// rule: f(x: Foo), prototype: f(x: Bar) => PASS if Foo is subclass of Bar
assert!(kb
.rule_params_match(
&rule!("f", ["x"; instance!(sym!("Citrus"))]),
&rule!("f", ["x"; instance!(sym!("Fruit"))])
)
.unwrap()
.is_true());
assert!(kb
.rule_params_match(
&rule!("f", ["x"; instance!(sym!("Orange"))]),
&rule!("f", ["x"; instance!(sym!("Fruit"))])
)
.unwrap()
.is_true());
// rule: f(x: Foo), prototype: f(x: {id: 1}) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; instance!(sym!("Foo"))]),
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}])
)
.unwrap()
.is_true());
// rule: f(x: Foo{id: 1}), prototype: f(x: {id: 1}) => PASS
assert!(kb
.rule_params_match(
&rule!(
"f",
["x"; instance!(sym!("Foo"), btreemap! {sym!("id") => term!(1)})]
),
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}])
)
.unwrap()
.is_true());
// rule: f(x: {id: 1}), prototype: f(x: Foo{id: 1}) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}]),
&rule!(
"f",
["x"; instance!(sym!("Foo"), btreemap! {sym!("id") => term!(1)})]
)
)
.unwrap()
.is_true());
// rule: f(x: {id: 1}), prototype: f(x: {id: 1}) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}]),
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}])
)
.unwrap()
.is_true());
// RULE VALUE SPEC, TEMPLATE PATTERN SPEC
// rule: f(x: 6), prototype: f(x: Integer) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!(6)]),
&rule!("f", ["x"; instance!(sym!("Integer"))])
)
.unwrap()
.is_true());
// rule: f(x: 6), prototype: f(x: Foo) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!(6)]),
&rule!("f", ["x"; instance!(sym!("Foo"))])
)
.unwrap()
.is_true());
// rule: f(x: 6.0), prototype: f(x: Float) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!(6.0)]),
&rule!("f", ["x"; instance!(sym!("Float"))])
)
.unwrap()
.is_true());
// rule: f(x: 6.0), prototype: f(x: Foo) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!(6.0)]),
&rule!("f", ["x"; instance!(sym!("Foo"))])
)
.unwrap()
.is_true());
// rule: f(x: "hi"), prototype: f(x: String) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!("hi")]),
&rule!("f", ["x"; instance!(sym!("String"))])
)
.unwrap()
.is_true());
// rule: f(x: "hi"), prototype: f(x: Foo) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!("hi")]),
&rule!("f", ["x"; instance!(sym!("Foo"))])
)
.unwrap()
.is_true());
// rule: f(x: true), prototype: f(x: Boolean) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!(true)]),
&rule!("f", ["x"; instance!(sym!("Boolean"))])
)
.unwrap()
.is_true());
// rule: f(x: true), prototype: f(x: Foo) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!(true)]),
&rule!("f", ["x"; instance!(sym!("Foo"))])
)
.unwrap()
.is_true());
// rule: f(x: [1, 2]), prototype: f(x: List) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!([1, 2])]),
&rule!("f", ["x"; instance!(sym!("List"))])
)
.unwrap()
.is_true());
// rule: f(x: [1, 2]), prototype: f(x: Foo) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!([1, 2])]),
&rule!("f", ["x"; instance!(sym!("Foo"))])
)
.unwrap()
.is_true());
// rule: f(x: {id: 1}), prototype: f(x: Dictionary) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}]),
&rule!("f", ["x"; instance!(sym!("Dictionary"))])
)
.unwrap()
.is_true());
// rule: f(x: {id: 1}), prototype: f(x: Foo) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}]),
&rule!("f", ["x"; instance!(sym!("Foo"))])
)
.unwrap()
.is_true());
// rule: f(x: {id: 1}), prototype: f(x: Dictionary{id: 1}) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}]),
&rule!(
"f",
["x"; instance!(sym!("Dictionary"), btreemap! {sym!("id") => term!(1)})]
)
)
.unwrap()
.is_true());
// RULE PATTERN SPEC, TEMPLATE VALUE SPEC
// always => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; btreemap!(sym!("1") => term!(1))]),
&rule!("f", ["x"; value!(1)])
)
.unwrap()
.is_true());
// BOTH VALUE SPEC
// Integer, String, Boolean: must be equal
// rule: f(x: 1), prototype: f(x: 1) => PASS
assert!(kb
.rule_params_match(&rule!("f", ["x"; value!(1)]), &rule!("f", ["x"; value!(1)]))
.unwrap()
.is_true());
// rule: f(x: 1), prototype: f(x: 2) => FAIL
assert!(!kb
.rule_params_match(&rule!("f", ["x"; value!(1)]), &rule!("f", ["x"; value!(2)]))
.unwrap()
.is_true());
// rule: f(x: 1.0), prototype: f(x: 1.0) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!(1.0)]),
&rule!("f", ["x"; value!(1.0)])
)
.unwrap()
.is_true());
// rule: f(x: 1.0), prototype: f(x: 2.0) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!(1.0)]),
&rule!("f", ["x"; value!(2.0)])
)
.unwrap()
.is_true());
// rule: f(x: "hi"), prototype: f(x: "hi") => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!("hi")]),
&rule!("f", ["x"; value!("hi")])
)
.unwrap()
.is_true());
// rule: f(x: "hi"), prototype: f(x: "hello") => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!("hi")]),
&rule!("f", ["x"; value!("hello")])
)
.unwrap()
.is_true());
// rule: f(x: true), prototype: f(x: true) => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!(true)]),
&rule!("f", ["x"; value!(true)])
)
.unwrap()
.is_true());
// rule: f(x: true), prototype: f(x: false) => PASS
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!(true)]),
&rule!("f", ["x"; value!(false)])
)
.unwrap()
.is_true());
// List: rule must be more specific than (superset of) prototype
// rule: f(x: [1,2,3]), prototype: f(x: [1,2]) => PASS
// TODO: I'm not sure this logic actually makes sense--it feels like
// they should have to be an exact match
assert!(kb
.rule_params_match(
&rule!("f", ["x"; value!([1, 2, 3])]),
&rule!("f", ["x"; value!([1, 2])])
)
.unwrap()
.is_true());
// rule: f(x: [1,2]), prototype: f(x: [1,2,3]) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; value!([1, 2])]),
&rule!("f", ["x"; value!([1, 2, 3])])
)
.unwrap()
.is_true());
// Dict: rule must be more specific than (superset of) prototype
// rule: f(x: {"id": 1, "name": "Dave"}), prototype: f(x: {"id": 1}) => PASS
assert!(kb
.rule_params_match(
&rule!(
"f",
["x"; btreemap! {sym!("id") => term!(1), sym!("name") => term!(sym!("Dave"))}]
),
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}]),
)
.unwrap()
.is_true());
// rule: f(x: {"id": 1}), prototype: f(x: {"id": 1, "name": "Dave"}) => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", ["x"; btreemap! {sym!("id") => term!(1)}]),
&rule!(
"f",
["x"; btreemap! {sym!("id") => term!(1), sym!("name") => term!(sym!("Dave"))}]
)
)
.unwrap()
.is_true());
// RULE None SPEC TEMPLATE Some SPEC
// always => FAIL
assert!(!kb
.rule_params_match(
&rule!("f", [sym!("x")]),
&rule!("f", ["x"; instance!(sym!("Foo"))])
)
.unwrap()
.is_true());
// RULE Some SPEC TEMPLATE None SPEC
// always => PASS
assert!(kb
.rule_params_match(
&rule!("f", ["x"; instance!(sym!("Foo"))]),
&rule!("f", [sym!("x")]),
)
.unwrap()
.is_true());
}
#[test]
fn test_validate_rules() {
let mut kb = KnowledgeBase::new();
kb.constant(
sym!("Fruit"),
term!(Value::ExternalInstance(ExternalInstance {
instance_id: 1,
constructor: None,
repr: None
})),
);
kb.constant(
sym!("Citrus"),
term!(Value::ExternalInstance(ExternalInstance {
instance_id: 2,
constructor: None,
repr: None
})),
);
kb.constant(
sym!("Orange"),
term!(Value::ExternalInstance(ExternalInstance {
instance_id: 3,
constructor: None,
repr: None
})),
);
kb.add_mro(sym!("Fruit"), vec![1]).unwrap();
// Citrus is a subclass of Fruit
kb.add_mro(sym!("Citrus"), vec![2, 1]).unwrap();
// Orange is a subclass of Citrus
kb.add_mro(sym!("Orange"), vec![3, 2, 1]).unwrap();
// Prototype applies if it has the same name as a rule
kb.add_rule_prototype(rule!("f", ["x"; instance!(sym!("Orange"))]));
kb.add_rule(rule!("f", ["x"; instance!(sym!("Orange"))]));
kb.add_rule(rule!("f", ["x"; instance!(sym!("Fruit"))]));
assert!(matches!(
kb.validate_rules().err().unwrap(),
PolarError {
kind: ErrorKind::Validation(ValidationError::InvalidRule { .. }),
..
}
));
// Prototype does not apply if it doesn't have the same name as a rule
kb.clear_rules();
kb.add_rule_prototype(rule!("f", ["x"; instance!(sym!("Orange"))]));
kb.add_rule(rule!("f", ["x"; instance!(sym!("Orange"))]));
kb.add_rule(rule!("g", ["x"; instance!(sym!("Fruit"))]));
kb.validate_rules().unwrap();
// Prototype does apply if it has the same name as a rule even if different arity
kb.clear_rules();
kb.add_rule_prototype(rule!("f", ["x"; instance!(sym!("Orange")), value!(1)]));
kb.add_rule(rule!("f", ["x"; instance!(sym!("Orange"))]));
assert!(matches!(
kb.validate_rules().err().unwrap(),
PolarError {
kind: ErrorKind::Validation(ValidationError::InvalidRule { .. }),
..
}
));
// Multiple templates can exist for the same name but only one needs to match
kb.clear_rules();
kb.add_rule_prototype(rule!("f", ["x"; instance!(sym!("Orange"))]));
kb.add_rule_prototype(rule!("f", ["x"; instance!(sym!("Orange")), value!(1)]));
kb.add_rule_prototype(rule!("f", ["x"; instance!(sym!("Fruit"))]));
kb.add_rule(rule!("f", ["x"; instance!(sym!("Fruit"))]));
}
}
|
pub struct Solution;
impl Solution {
pub fn reconstruct_queue(people: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
use std::cmp::Reverse;
let mut people = people;
people.sort_unstable_by_key(|p| (Reverse(p[0]), p[1]));
let mut res = Vec::with_capacity(people.len());
for p in people {
res.insert(p[1] as usize, p);
}
res
}
}
#[test]
fn test0406() {
fn case(people: Vec<[i32; 2]>, want: Vec<[i32; 2]>) {
let people = people.iter().map(|a| a.to_vec()).collect();
let want = want.iter().map(|a| a.to_vec()).collect::<Vec<_>>();
let got = Solution::reconstruct_queue(people);
assert_eq!(got, want);
}
case(
vec![[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]],
vec![[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]],
)
}
|
// 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::message::{Message, MessageReturn};
use crate::node::Node;
use async_trait::async_trait;
use failure::{format_err, Error};
use fuchsia_async as fasync;
use fuchsia_syslog::{fx_log_err, fx_log_info};
use fuchsia_zircon as zx;
use futures::future::join;
use futures::prelude::*;
use std::rc::Rc;
/// Node: ThermalPolicy
///
/// Summary: implements the closed loop thermal control policy for the system
///
/// Message Inputs: N/A
///
/// Message Outputs:
/// - ReadTemperature
/// - GetCpuIdlePct
///
/// FIDL: N/A
#[allow(dead_code)]
pub struct ThermalPolicy {
config: ThermalConfig,
temperature_node: Rc<dyn Node>,
cpu_stats_node: Rc<dyn Node>,
cpu_control_node: Rc<dyn Node>,
}
pub struct ThermalConfig {
pub temperature_driver: String,
pub poll_interval_ms: i32,
}
impl ThermalPolicy {
pub fn new(
config: ThermalConfig,
temperature_node: Rc<dyn Node>,
cpu_stats_node: Rc<dyn Node>,
cpu_control_node: Rc<dyn Node>,
) -> Rc<Self> {
Rc::new(Self { config, temperature_node, cpu_stats_node, cpu_control_node })
}
fn setup_poll_timer(self: Rc<Self>) -> Result<(), Error> {
let mut periodic_timer =
fasync::Interval::new(zx::Duration::from_millis(self.config.poll_interval_ms.into()));
let s = self.clone();
fasync::spawn_local(async move {
while let Some(()) = (periodic_timer.next()).await {
if let Err(e) = s.tick().await {
fx_log_err!("{}", e);
}
}
});
Ok(())
}
async fn tick(&self) -> Result<(), Error> {
let get_temperature_message = Message::ReadTemperature(&self.config.temperature_driver);
let get_temperature_future =
self.send_message(&self.temperature_node, &get_temperature_message);
let get_cpu_load_message = Message::GetCpuIdlePct;
let get_cpu_load_future = self.send_message(&self.cpu_stats_node, &get_cpu_load_message);
let (temperature, load) = join(get_temperature_future, get_cpu_load_future).await;
let temperature = match temperature {
Ok(MessageReturn::ReadTemperature(t)) => t,
Ok(r) => Err(format_err!("ReadTemperature had unexpected return value: {:?}", r))?,
Err(e) => Err(format_err!("ReadTemperature failed: {:?}", e))?,
};
let load = match load {
Ok(MessageReturn::GetCpuIdlePct(l)) => l,
Ok(r) => Err(format_err!("GetCpuIdlePct had unexpected return value: {:?}", r))?,
Err(e) => Err(format_err!("GetCpuIdlePct failed: {:?}", e))?,
};
fx_log_info!("temperature={}; load={}", temperature.0, load);
Ok(())
}
}
#[async_trait(?Send)]
impl Node for ThermalPolicy {
fn name(&self) -> &'static str {
"ThermalPolicy"
}
fn init(self: Rc<Self>) -> Result<(), Error> {
self.setup_poll_timer()?;
Ok(())
}
async fn handle_message(&self, msg: &Message<'_>) -> Result<MessageReturn, Error> {
match msg {
_ => Err(format_err!("Unsupported message: {:?}", msg)),
}
}
}
|
use clap;
use std::fs;
use std::io;
use std::io::Write;
use std::path::PathBuf;
use std::process;
use std::rc::Rc;
pub enum Command {
Dedupe,
PrintExtents,
}
pub struct Arguments {
pub command: Command,
pub database_path: Option <PathBuf>,
pub minimum_file_size: u64,
pub content_hash_batch_size: u64,
pub extent_hash_batch_size: u64,
pub dedupe_batch_size: u64,
pub root_paths: Vec <Rc <PathBuf>>,
}
pub fn parse_arguments (
) -> Arguments {
let application = (
clap::App::new ("Btrfs Dedupe")
.about (
"Deduplicates identical files on BTRFS file systems.\n\nPlease \
visit https://btrfs-dedupe.com for more information.")
.author (
"James Pharaoh <james@pharaoh.uk>")
.subcommand (
clap::SubCommand::with_name ("dedupe")
.about ("Automatically runs all deduplication steps (default)")
.arg (
clap::Arg::with_name ("database")
.long ("database")
.value_name ("PATH")
.help ("Database path to store metadata and hashes")
)
.arg (
clap::Arg::with_name ("minimum-file-size")
.long ("minimum-file-size")
.value_name ("SIZE")
.default_value ("1KiB")
.help ("Minimum file size to consider for deduplication")
)
.arg (
clap::Arg::with_name ("content-hash-batch-size")
.long ("content-hash-batch-size")
.value_name ("SIZE")
.default_value ("2GiB")
.help ("Amount of file contents data to hash before \
writing database")
)
.arg (
clap::Arg::with_name ("extent-hash-batch-size")
.long ("extent-hash-batch-size")
.value_name ("SIZE")
.default_value ("512GiB")
.help ("Amount of file extent data to hash before writing \
database")
)
.arg (
clap::Arg::with_name ("dedupe-batch-size")
.long ("dedupe-batch-size")
.value_name ("SIZE")
.default_value ("64GiB")
.help ("Amount of file data to deduplicate before writing \
database")
)
.arg (
clap::Arg::with_name ("root-path")
.multiple (true)
.value_name ("PATH")
.help ("Root path to scan for files")
)
)
.subcommand (
clap::SubCommand::with_name ("print-extents")
.about ("Prints file extent information for a given file")
.arg (
clap::Arg::with_name ("file-path")
.multiple (true)
.value_name ("PATH")
.help ("Path to file")
)
)
);
let argument_matches =
application.clone ().get_matches ();
if let Some (dedupe_matches) =
argument_matches.subcommand_matches ("dedupe") {
let database_path =
dedupe_matches.value_of_os (
"database",
).map (
|os_value|
PathBuf::from (
os_value)
);
let content_hash_batch_size = (
parse_size (
dedupe_matches.value_of (
"content-hash-batch-size",
).unwrap ()
)
).map_err (
|error|
clap::Error {
message:
format! (
"Can't parse --content-hash-batch-size: {}",
error),
kind:
clap::ErrorKind::InvalidValue,
info:
None,
}.exit ()
).unwrap ();
let extent_hash_batch_size = (
parse_size (
dedupe_matches.value_of (
"extent-hash-batch-size",
).unwrap ()
)
).map_err (
|error|
clap::Error {
message:
format! (
"Can't parse --extent-hash-batch-size: {}",
error),
kind:
clap::ErrorKind::InvalidValue,
info:
None,
}.exit ()
).unwrap ();
let dedupe_batch_size = (
parse_size (
dedupe_matches.value_of (
"dedupe-batch-size",
).unwrap ()
)
).map_err (
|error|
clap::Error {
message:
format! (
"Can't parse --dedupe-batch-size: {}",
error),
kind:
clap::ErrorKind::InvalidValue,
info:
None,
}.exit ()
).unwrap ();
let minimum_file_size = (
parse_size (
dedupe_matches.value_of (
"minimum-file-size",
).unwrap ()
)
).map_err (
|error|
clap::Error {
message:
format! (
"Can't parse --minimum-file-size: {}",
error),
kind:
clap::ErrorKind::InvalidValue,
info:
None,
}.exit ()
).unwrap ();
let mut root_paths = (
dedupe_matches.values_of_os (
"root-path",
)
).map (
|os_values|
os_values.map (
|os_value|
Rc::new (
fs::canonicalize (
PathBuf::from (
os_value),
).unwrap ()
)
).collect ()
).unwrap_or (
Vec::new (),
);
root_paths.sort ();
Arguments {
command: Command::Dedupe,
database_path: database_path,
minimum_file_size: minimum_file_size,
content_hash_batch_size: content_hash_batch_size,
extent_hash_batch_size: extent_hash_batch_size,
dedupe_batch_size: dedupe_batch_size,
root_paths: root_paths,
}
} else if let Some (print_extents_matches) =
argument_matches.subcommand_matches ("print-extents") {
let paths = (
print_extents_matches.values_of_os (
"file-path",
)
).map (
|os_values|
os_values.map (
|os_value|
Rc::new (
fs::canonicalize (
PathBuf::from (
os_value),
).unwrap ()
)
).collect ()
).unwrap_or (
Vec::new (),
);
Arguments {
command: Command::PrintExtents,
database_path: None,
minimum_file_size: 0,
content_hash_batch_size: 0,
extent_hash_batch_size: 0,
dedupe_batch_size: 0,
root_paths: paths,
}
} else {
let stderr =
io::stderr ();
let mut stderr_lock =
stderr.lock ();
stderr_lock.write (
b"\n",
).unwrap ();
application.write_help (
& mut stderr_lock,
).unwrap ();
stderr_lock.write (
b"\n\n",
).unwrap ();
process::exit (0);
}
}
pub fn parse_size (
size_string: & str,
) -> Result <u64, String> {
let (multiplier, suffix_length) =
if size_string.ends_with ("KiB") {
(1024, 3)
} else if size_string.ends_with ("MiB") {
(1024 * 1024, 3)
} else if size_string.ends_with ("GiB") {
(1024 * 1024 * 1024, 3)
} else if size_string.ends_with ("TiB") {
(1024 * 1024 * 1024 * 1024, 3)
} else if size_string.ends_with ("KB") {
(1000, 2)
} else if size_string.ends_with ("MB") {
(1000 * 1000, 2)
} else if size_string.ends_with ("GB") {
(1000 * 1000 * 1000, 2)
} else if size_string.ends_with ("TB") {
(1000 * 1000 * 1000 * 1000, 2)
} else if size_string.ends_with ("K") {
(1024, 1)
} else if size_string.ends_with ("M") {
(1024 * 1024, 1)
} else if size_string.ends_with ("G") {
(1024 * 1024 * 1024, 1)
} else if size_string.ends_with ("T") {
(1024 * 1024 * 1024 * 1024, 1)
} else if size_string.ends_with ("B") {
(1, 1)
} else {
return Err (
"Units not specified or recognised".to_owned ());
};
let quantity_string =
& size_string [
0 ..
size_string.len () - suffix_length];
let quantity_integer =
try! (
quantity_string.parse::<u64> (
).map_err (
|_|
"Unable to parse integer value".to_owned ()
));
Ok (
multiplier * quantity_integer
)
}
// ex: noet ts=4 filetype=rust
|
extern crate gl;
use core::ops::Add;
use core::ops::Div;
use core::ops::Mul;
use core::ops::Neg;
use core::ops::Sub;
#[derive(Copy, Clone)]
pub struct Vec1<T> {
pub x: T,
}
#[allow(dead_code)]
pub type Vec1f = Vec1<f32>;
#[allow(dead_code)]
pub type Vec1u = Vec1<u32>;
#[allow(dead_code)]
pub type Vec1i = Vec1<i16>;
impl<T> Vec1<T>
where
T: From<u16>,
{
pub fn new(x: T) -> Vec1<T> {
Vec1 { x }
}
#[allow(dead_code)]
pub fn null() -> Vec1<T> {
Vec1::<T> { x: T::from(0) }
}
}
#[derive(Copy, Clone)]
pub struct Vec2<T> {
pub x: T,
pub y: T,
}
#[allow(dead_code)]
pub type Vec2f = Vec2<f32>;
#[allow(dead_code)]
pub type Vec2u = Vec2<u32>;
#[allow(dead_code)]
pub type Vec2i = Vec2<i16>;
impl<T> Vec2<T>
where
T: From<u16>,
{
pub fn new(x: T, y: T) -> Vec2<T> {
Vec2 { x, y }
}
#[allow(dead_code)]
pub fn null() -> Vec2<T> {
Vec2::<T> {
x: T::from(0),
y: T::from(0),
}
}
}
#[derive(Copy, Clone)]
pub struct Vec3<T> {
pub x: T,
pub y: T,
pub z: T,
}
#[allow(dead_code)]
pub type Vec3f = Vec3<f32>;
#[allow(dead_code)]
pub type Vec3u = Vec3<u32>;
#[allow(dead_code)]
pub type Vec3i = Vec3<i16>;
impl<T> Vec3<T>
where
T: From<u16>,
{
pub fn new(x: T, y: T, z: T) -> Vec3<T> {
Vec3 { x, y, z }
}
#[allow(dead_code)]
pub fn null() -> Vec3<T> {
Vec3::<T> {
x: T::from(0),
y: T::from(0),
z: T::from(0),
}
}
}
#[derive(Copy, Clone)]
pub struct Vec4<T> {
pub x: T,
pub y: T,
pub z: T,
pub w: T,
}
#[allow(dead_code)]
pub type Vec4f = Vec4<f32>;
#[allow(dead_code)]
pub type Vec4u = Vec4<u32>;
#[allow(dead_code)]
pub type Vec4i = Vec4<i16>;
impl<T> Vec4<T>
where
T: From<u16>,
{
pub fn new(x: T, y: T, z: T, w: T) -> Vec4<T> {
Vec4 { x, y, z, w }
}
#[allow(dead_code)]
pub fn null() -> Vec4<T> {
Vec4::<T> {
x: T::from(0),
y: T::from(0),
z: T::from(0),
w: T::from(0),
}
}
}
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub struct Mat3x3<T> {
pub r1: Vec3<T>,
pub r2: Vec3<T>,
pub r3: Vec3<T>,
}
#[allow(dead_code)]
pub type Mat3x3f = Mat3x3<f32>;
#[allow(dead_code)]
pub type Mat3x3u = Mat3x3<u32>;
#[allow(dead_code)]
pub type Mat3x3i = Mat3x3<i16>;
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub struct Mat4x4<T> {
pub r1: Vec4<T>,
pub r2: Vec4<T>,
pub r3: Vec4<T>,
pub r4: Vec4<T>,
}
#[allow(dead_code)]
pub type Mat4x4f = Mat4x4<f32>;
#[allow(dead_code)]
pub type Mat4x4u = Mat4x4<u32>;
#[allow(dead_code)]
pub type Mat4x4i = Mat4x4<i16>;
impl<T> Mat4x4<T>
where
T: From<u16>,
{
pub fn identity() -> Mat4x4<T> {
Mat4x4::<T> {
r1: Vec4::<T>::new(T::from(1), T::from(0), T::from(0), T::from(0)),
r2: Vec4::<T>::new(T::from(0), T::from(1), T::from(0), T::from(0)),
r3: Vec4::<T>::new(T::from(0), T::from(0), T::from(1), T::from(0)),
r4: Vec4::<T>::new(T::from(0), T::from(0), T::from(0), T::from(1)),
}
}
#[allow(dead_code)]
pub fn null() -> Mat4x4<T>
where
T: From<u16>,
{
Mat4x4::<T> {
r1: Vec4::<T>::new(T::from(0), T::from(0), T::from(0), T::from(0)),
r2: Vec4::<T>::new(T::from(0), T::from(0), T::from(0), T::from(0)),
r3: Vec4::<T>::new(T::from(0), T::from(0), T::from(0), T::from(0)),
r4: Vec4::<T>::new(T::from(0), T::from(0), T::from(0), T::from(0)),
}
}
}
impl<T> Add for Vec1<T>
where
T: Add<Output = T>,
{
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
x: self.x + other.x,
}
}
}
impl<T> Add for Vec2<T>
where
T: Add<Output = T>,
{
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl<T> Add for Vec3<T>
where
T: Add<Output = T>,
{
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}
impl<T> Add for Vec4<T>
where
T: Add<Output = T>,
{
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
w: self.w + other.w,
}
}
}
impl<T> Sub for Vec1<T>
where
T: Sub<Output = T>,
{
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
x: self.x - other.x,
}
}
}
impl<T> Sub for Vec2<T>
where
T: Sub<Output = T>,
{
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl<T> Sub for Vec3<T>
where
T: Sub<Output = T>,
{
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
}
}
}
impl<T> Sub for Vec4<T>
where
T: Sub<Output = T>,
{
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
w: self.w - other.w,
}
}
}
impl<T> Div<T> for Vec1<T>
where
T: Div<Output = T> + Copy,
{
type Output = Self;
fn div(self, other: T) -> Self::Output {
Self { x: self.x / other }
}
}
impl<T> Div<T> for Vec2<T>
where
T: Div<Output = T> + Copy,
{
type Output = Self;
fn div(self, other: T) -> Self::Output {
Self {
x: self.x / other,
y: self.y / other,
}
}
}
impl<T> Div<T> for Vec3<T>
where
T: Div<Output = T> + Copy,
{
type Output = Self;
fn div(self, other: T) -> Self::Output {
Self::Output {
x: self.x / other,
y: self.y / other,
z: self.z / other,
}
}
}
impl<T> Div<T> for Vec4<T>
where
T: Div<Output = T> + Copy,
{
type Output = Self;
fn div(self, other: T) -> Self::Output {
Self {
x: self.x / other,
y: self.y / other,
z: self.z / other,
w: self.w / other,
}
}
}
impl<T> Mul<T> for Vec1<T>
where
T: Mul<Output = T> + Copy,
{
type Output = Self;
fn mul(self, other: T) -> Self::Output {
Self { x: self.x * other }
}
}
impl<T> Mul<T> for Vec2<T>
where
T: Mul<Output = T> + Copy,
{
type Output = Self;
fn mul(self, other: T) -> Self::Output {
Self {
x: self.x * other,
y: self.y * other,
}
}
}
impl<T> Mul<T> for Vec3<T>
where
T: Mul<Output = T> + Copy,
{
type Output = Self;
fn mul(self, other: T) -> Self::Output {
Self::Output {
x: self.x * other,
y: self.y * other,
z: self.z * other,
}
}
}
impl<T> Mul<T> for Vec4<T>
where
T: Mul<Output = T> + Copy,
{
type Output = Self;
fn mul(self, other: T) -> Self::Output {
Self {
x: self.x * other,
y: self.y * other,
z: self.z * other,
w: self.w * other,
}
}
}
impl<T> Neg for Vec1<T>
where
T: Neg<Output = T> + Copy,
{
type Output = Self;
fn neg(self) -> Self::Output {
Vec1::<T> { x: -self.x }
}
}
impl<T> Neg for Vec2<T>
where
T: Neg<Output = T> + Copy,
{
type Output = Self;
fn neg(self) -> Self::Output {
Vec2::<T> {
x: -self.x,
y: -self.y,
}
}
}
impl<T> Neg for Vec3<T>
where
T: Neg<Output = T> + Copy,
{
type Output = Self;
fn neg(self) -> Self::Output {
Vec3::<T> {
x: -self.x,
y: -self.y,
z: -self.z,
}
}
}
impl<T> Neg for Vec4<T>
where
T: Neg<Output = T> + Copy,
{
type Output = Self;
fn neg(self) -> Self::Output {
Vec4::<T> {
x: -self.x,
y: -self.y,
z: -self.z,
w: -self.w,
}
}
}
#[allow(dead_code)]
pub fn dot_vec1<T>(a: Vec1<T>, b: Vec1<T>) -> T
where
T: Mul<Output = T> + Copy,
{
a.x * b.x
}
#[allow(dead_code)]
pub fn dot_vec2<T>(a: Vec2<T>, b: Vec2<T>) -> T
where
T: Mul<Output = T> + Add<Output = T> + Copy,
{
a.x * b.x + a.y * b.y
}
#[allow(dead_code)]
pub fn dot_vec3<T>(a: Vec3<T>, b: Vec3<T>) -> T
where
T: Mul<Output = T> + Add<Output = T> + Copy,
{
a.x * b.x + a.y * b.y + a.z * b.z
}
#[allow(dead_code)]
pub fn dot_vec4<T>(a: Vec4<T>, b: Vec4<T>) -> T
where
T: Mul<Output = T> + Add<Output = T> + Copy,
{
a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w
}
#[allow(dead_code)]
pub fn cross<T>(a: Vec3<T>, b: Vec3<T>) -> Vec3<T>
where
T: Mul<Output = T> + Sub<Output = T> + Copy,
{
Vec3::<T> {
x: a.y * b.z - a.z * b.y,
y: a.z * b.x - a.x * b.z,
z: a.x * b.y - a.y * b.x,
}
}
#[allow(dead_code)]
pub fn length_squared_vec1(a: Vec1f) -> f32 {
dot_vec1(a, a)
}
#[allow(dead_code)]
pub fn length_squared_vec2(a: Vec2f) -> f32 {
dot_vec2(a, a)
}
#[allow(dead_code)]
pub fn length_squared_vec3(a: Vec3f) -> f32 {
dot_vec3(a, a)
}
#[allow(dead_code)]
pub fn length_squared_vec4(a: Vec4f) -> f32 {
dot_vec4(a, a)
}
#[allow(dead_code)]
pub fn length_vec1(a: Vec1f) -> f32 {
length_squared_vec1(a).sqrt()
}
#[allow(dead_code)]
pub fn length_vec2(a: Vec2f) -> f32 {
length_squared_vec2(a).sqrt()
}
#[allow(dead_code)]
pub fn length_vec3(a: Vec3f) -> f32 {
length_squared_vec3(a).sqrt()
}
#[allow(dead_code)]
pub fn length_vec4(a: Vec4f) -> f32 {
length_squared_vec4(a).sqrt()
}
#[allow(dead_code)]
pub fn normalize_vec1(a: Vec1f) -> Vec1f {
a / length_vec1(a)
}
#[allow(dead_code)]
pub fn normalize_vec2(a: Vec2f) -> Vec2f {
a / length_vec2(a)
}
#[allow(dead_code)]
pub fn normalize_vec3(a: Vec3f) -> Vec3f {
a / length_vec3(a)
}
#[allow(dead_code)]
pub fn normalize_vec4(a: Vec4f) -> Vec4f {
a / length_vec4(a)
}
#[allow(dead_code)]
pub fn zero_vec1<T>() -> Vec1<T>
where
T: From<i16>,
{
Vec1::<T> { x: T::from(0) }
}
#[allow(dead_code)]
pub fn zero_vec2<T>() -> Vec2<T>
where
T: From<i16>,
{
Vec2::<T> {
x: T::from(0),
y: T::from(0),
}
}
#[allow(dead_code)]
pub fn zero_vec3<T>() -> Vec3<T>
where
T: From<i16>,
{
Vec3::<T> {
x: T::from(0),
y: T::from(0),
z: T::from(0),
}
}
#[allow(dead_code)]
pub fn zero_vec4<T>() -> Vec4<T>
where
T: From<i16>,
{
Vec4::<T> {
x: T::from(0),
y: T::from(0),
z: T::from(0),
w: T::from(0),
}
}
pub trait VecDimensions<T> {
const DIMENSIONS: u32;
}
impl<T> VecDimensions<T> for Vec1f {
const DIMENSIONS: u32 = 1;
}
impl<T> VecDimensions<T> for Vec1i {
const DIMENSIONS: u32 = 1;
}
impl<T> VecDimensions<T> for Vec1u {
const DIMENSIONS: u32 = 1;
}
impl<T> VecDimensions<T> for Vec2f {
const DIMENSIONS: u32 = 2;
}
impl<T> VecDimensions<T> for Vec2i {
const DIMENSIONS: u32 = 2;
}
impl<T> VecDimensions<T> for Vec2u {
const DIMENSIONS: u32 = 2;
}
impl<T> VecDimensions<T> for Vec3f {
const DIMENSIONS: u32 = 3;
}
impl<T> VecDimensions<T> for Vec3i {
const DIMENSIONS: u32 = 3;
}
impl<T> VecDimensions<T> for Vec3u {
const DIMENSIONS: u32 = 3;
}
impl<T> VecDimensions<T> for Vec4f {
const DIMENSIONS: u32 = 4;
}
impl<T> VecDimensions<T> for Vec4i {
const DIMENSIONS: u32 = 4;
}
impl<T> VecDimensions<T> for Vec4u {
const DIMENSIONS: u32 = 4;
}
pub trait VecGLTypeValue {
const GL_VALUE: u32;
}
pub trait VecGLTypeTrait {
const GL_TYPE: u32;
}
impl<T: VecGLTypeValue> VecGLTypeTrait for Vec1<T> {
const GL_TYPE: u32 = T::GL_VALUE;
}
impl<T: VecGLTypeValue> VecGLTypeTrait for Vec2<T> {
const GL_TYPE: u32 = T::GL_VALUE;
}
impl<T: VecGLTypeValue> VecGLTypeTrait for Vec3<T> {
const GL_TYPE: u32 = T::GL_VALUE;
}
impl<T: VecGLTypeValue> VecGLTypeTrait for Vec4<T> {
const GL_TYPE: u32 = T::GL_VALUE;
}
impl VecGLTypeValue for i16 {
const GL_VALUE: u32 = gl::INT;
}
impl VecGLTypeValue for u32 {
const GL_VALUE: u32 = gl::UNSIGNED_INT;
}
impl VecGLTypeValue for f32 {
const GL_VALUE: u32 = gl::FLOAT;
}
impl<T> Mul<Vec3<T>> for Mat3x3<T>
where
T: Mul<Output = T> + Add<Output = T> + Copy,
{
type Output = Vec3<T>;
fn mul(self, other: Vec3<T>) -> Self::Output {
Self::Output {
x: dot_vec3(self.r1, other),
y: dot_vec3(self.r2, other),
z: dot_vec3(self.r3, other),
}
}
}
impl<T> Mul<Vec4<T>> for Mat4x4<T>
where
T: Mul<Output = T> + Add<Output = T> + Copy,
{
type Output = Vec4<T>;
fn mul(self, other: Vec4<T>) -> Self::Output {
Self::Output {
x: dot_vec4(self.r1, other),
y: dot_vec4(self.r2, other),
z: dot_vec4(self.r3, other),
w: dot_vec4(self.r4, other),
}
}
}
impl<T> Mul<Mat3x3<T>> for Mat3x3<T>
where
T: Mul<Output = T> + Add<Output = T> + Copy + From<u16>,
{
type Output = Mat3x3<T>;
fn mul(self, other: Mat3x3<T>) -> Self::Output {
Mat3x3::<T> {
r1: Vec3::<T> {
x: dot_vec3(self.r1, Vec3::<T>::new(other.r1.x, other.r2.x, other.r3.x)),
y: dot_vec3(self.r1, Vec3::<T>::new(other.r1.y, other.r2.y, other.r3.y)),
z: dot_vec3(self.r1, Vec3::<T>::new(other.r1.z, other.r2.z, other.r3.z)),
},
r2: Vec3::<T> {
x: dot_vec3(self.r2, Vec3::<T>::new(other.r1.x, other.r2.x, other.r3.x)),
y: dot_vec3(self.r2, Vec3::<T>::new(other.r1.y, other.r2.y, other.r3.y)),
z: dot_vec3(self.r2, Vec3::<T>::new(other.r1.z, other.r2.z, other.r3.z)),
},
r3: Vec3::<T> {
x: dot_vec3(self.r3, Vec3::<T>::new(other.r1.x, other.r2.x, other.r3.x)),
y: dot_vec3(self.r3, Vec3::<T>::new(other.r1.y, other.r2.y, other.r3.y)),
z: dot_vec3(self.r3, Vec3::<T>::new(other.r1.z, other.r2.z, other.r3.z)),
},
}
}
}
impl<T> Mul<Mat4x4<T>> for Mat4x4<T>
where
T: Mul<Output = T> + Add<Output = T> + Copy + From<u16>,
{
type Output = Mat4x4<T>;
fn mul(self, other: Mat4x4<T>) -> Self::Output {
Mat4x4::<T> {
r1: Vec4::<T> {
x: dot_vec4(
self.r1,
Vec4::<T>::new(other.r1.x, other.r2.x, other.r3.x, other.r4.x),
),
y: dot_vec4(
self.r1,
Vec4::<T>::new(other.r1.y, other.r2.y, other.r3.y, other.r4.y),
),
z: dot_vec4(
self.r1,
Vec4::<T>::new(other.r1.z, other.r2.z, other.r3.z, other.r4.z),
),
w: dot_vec4(
self.r1,
Vec4::<T>::new(other.r1.w, other.r2.w, other.r3.w, other.r4.w),
),
},
r2: Vec4::<T> {
x: dot_vec4(
self.r2,
Vec4::<T>::new(other.r1.x, other.r2.x, other.r3.x, other.r4.x),
),
y: dot_vec4(
self.r2,
Vec4::<T>::new(other.r1.y, other.r2.y, other.r3.y, other.r4.y),
),
z: dot_vec4(
self.r2,
Vec4::<T>::new(other.r1.z, other.r2.z, other.r3.z, other.r4.z),
),
w: dot_vec4(
self.r2,
Vec4::<T>::new(other.r1.w, other.r2.w, other.r3.w, other.r4.w),
),
},
r3: Vec4::<T> {
x: dot_vec4(
self.r3,
Vec4::<T>::new(other.r1.x, other.r2.x, other.r3.x, other.r4.x),
),
y: dot_vec4(
self.r3,
Vec4::<T>::new(other.r1.y, other.r2.y, other.r3.y, other.r4.y),
),
z: dot_vec4(
self.r3,
Vec4::<T>::new(other.r1.z, other.r2.z, other.r3.z, other.r4.z),
),
w: dot_vec4(
self.r3,
Vec4::<T>::new(other.r1.w, other.r2.w, other.r3.w, other.r4.w),
),
},
r4: Vec4::<T> {
x: dot_vec4(
self.r4,
Vec4::<T>::new(other.r1.x, other.r2.x, other.r3.x, other.r4.x),
),
y: dot_vec4(
self.r4,
Vec4::<T>::new(other.r1.y, other.r2.y, other.r3.y, other.r4.y),
),
z: dot_vec4(
self.r4,
Vec4::<T>::new(other.r1.z, other.r2.z, other.r3.z, other.r4.z),
),
w: dot_vec4(
self.r4,
Vec4::<T>::new(other.r1.w, other.r2.w, other.r3.w, other.r4.w),
),
},
}
}
}
impl<T> From<Mat3x3<T>> for Mat4x4<T>
where
T: From<u16>,
{
fn from(src: Mat3x3<T>) -> Mat4x4<T> {
Mat4x4::<T> {
r1: Vec4::<T>::new(src.r1.x, src.r1.y, src.r1.z, T::from(0)),
r2: Vec4::<T>::new(src.r2.x, src.r2.y, src.r2.z, T::from(0)),
r3: Vec4::<T>::new(src.r3.x, src.r3.y, src.r3.z, T::from(0)),
r4: Vec4::<T>::new(T::from(0), T::from(0), T::from(0), T::from(1)),
}
}
}
#[allow(dead_code)]
pub fn null_mat3x3<T>() -> Mat3x3<T>
where
T: From<u16>,
{
Mat3x3::<T> {
r1: Vec3::<T>::new(T::from(0), T::from(0), T::from(0)),
r2: Vec3::<T>::new(T::from(0), T::from(0), T::from(0)),
r3: Vec3::<T>::new(T::from(0), T::from(0), T::from(0)),
}
}
#[allow(dead_code)]
pub fn identity_mat3x3<T>() -> Mat3x3<T>
where
T: From<u16>,
{
Mat3x3::<T> {
r1: Vec3::<T>::new(T::from(1), T::from(0), T::from(0)),
r2: Vec3::<T>::new(T::from(0), T::from(1), T::from(0)),
r3: Vec3::<T>::new(T::from(0), T::from(0), T::from(1)),
}
}
#[allow(dead_code)]
pub fn x_rotation_mat3x3(angle: f32) -> Mat3x3f {
Mat3x3f {
r1: Vec3f::new(1., 0., 0.),
r2: Vec3f::new(0., angle.cos(), -angle.sin()),
r3: Vec3f::new(0., angle.sin(), angle.cos()),
}
}
#[allow(dead_code)]
pub fn y_rotation_mat3x3(angle: f32) -> Mat3x3f {
Mat3x3f {
r1: Vec3f::new(angle.cos(), 0., angle.sin()),
r2: Vec3f::new(0., 1., 0.),
r3: Vec3f::new(-angle.sin(), 0., angle.cos()),
}
}
#[allow(dead_code)]
pub fn z_rotation_mat3x3(angle: f32) -> Mat3x3f {
Mat3x3f {
r1: Vec3f::new(angle.cos(), -angle.sin(), 0.),
r2: Vec3f::new(angle.sin(), angle.cos(), 0.),
r3: Vec3f::new(0., 0., 1.),
}
}
#[allow(dead_code)]
pub fn x_rotation_mat4x4(angle: f32) -> Mat4x4f {
Mat4x4f::from(x_rotation_mat3x3(angle))
}
#[allow(dead_code)]
pub fn y_rotation_mat4x4(angle: f32) -> Mat4x4f {
Mat4x4f::from(y_rotation_mat3x3(angle))
}
#[allow(dead_code)]
pub fn z_rotation_mat4x4(angle: f32) -> Mat4x4f {
Mat4x4f::from(z_rotation_mat3x3(angle))
}
#[allow(dead_code)]
pub fn scale_mat3x3(scale: Vec3f) -> Mat3x3f {
let mut mat = identity_mat3x3();
mat.r1.x = scale.x;
mat.r2.y = scale.y;
mat.r3.z = scale.z;
mat
}
#[allow(dead_code)]
pub fn scale_uniform_mat3x3(scale: f32) -> Mat3x3f {
scale_mat3x3(Vec3f {
x: scale,
y: scale,
z: scale,
})
}
#[allow(dead_code)]
pub fn scale_mat4x4(scale: Vec3f) -> Mat4x4f {
Mat4x4f::from(scale_mat3x3(scale))
}
#[allow(dead_code)]
pub fn scale_uniform_mat4x4(scale: f32) -> Mat4x4f {
Mat4x4::from(scale_uniform_mat3x3(scale))
}
#[allow(dead_code)]
pub fn tranlation_mat4x4(offset: Vec3f) -> Mat4x4f {
let mut mat = Mat4x4f::identity();
mat.r1.w = offset.x;
mat.r2.w = offset.y;
mat.r3.w = offset.z;
mat
}
#[allow(dead_code)]
pub fn orthographics_projection_planes_mat4x4(
left: f32,
right: f32,
bottom: f32,
top: f32,
near: f32,
far: f32,
) -> Mat4x4f {
let mut proj = Mat4x4f::identity();
proj.r1.x = 2_f32 / (right - left);
proj.r1.w = -(right + left) / (right - left);
proj.r2.y = 2_f32 / (top - bottom);
proj.r2.w = -(top + bottom) / (top - bottom);
proj.r3.z = 2_f32 / (far - near);
proj.r3.w = -(far + near) / (far - near);
proj
}
#[allow(dead_code)]
pub fn perspective_projection_planes_mat4x4(
left: f32,
right: f32,
bottom: f32,
top: f32,
near: f32,
far: f32,
) -> Mat4x4f {
let mut proj = Mat4x4f::null();
proj.r1.x = 2_f32 * near / (right - left);
proj.r1.z = (right + left) / (right - left);
proj.r2.y = 2_f32 * near / (top - bottom);
proj.r2.z = (top + bottom) / (top - bottom);
proj.r3.z = -(far + near) / (far - near);
proj.r3.w = -2_f32 * far * near / (far - near);
proj.r4.z = -1_f32;
proj
}
#[allow(dead_code)]
pub fn perspective_projection_mat4x4(vfov: f32, aspect: f32, near: f32, far: f32) -> Mat4x4f {
let c = 1_f32 / (vfov / 2_f32).tan();
let mut proj = Mat4x4f::null();
proj.r1.x = c / aspect;
proj.r2.y = c;
proj.r3.z = -(far + near) / (far - near);
proj.r3.w = -(2_f32 * far * near) / (far - near);
proj.r4.z = -1_f32;
proj
}
#[allow(dead_code)]
pub fn create_camera_mat4x4(pos: Vec3f, yaw: f32, pitch: f32) -> Mat4x4f {
tranlation_mat4x4(pos) * y_rotation_mat4x4(yaw) * x_rotation_mat4x4(pitch)
}
#[allow(dead_code)]
pub fn create_view_mat4x4(pos: Vec3f, yaw: f32, pitch: f32) -> Mat4x4f {
x_rotation_mat4x4(-pitch) * y_rotation_mat4x4(-yaw) * tranlation_mat4x4(-pos)
}
|
// 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 fidl_fuchsia_ui_input::{self as input, KeyboardEvent, KeyboardEventPhase};
const HID_USAGE_KEY_ENTER: u32 = 0x28;
const HID_USAGE_KEY_ESC: u32 = 0x29;
const HID_USAGE_KEY_BACKSPACE: u32 = 0x2a;
const HID_USAGE_KEY_TAB: u32 = 0x2b;
const HID_USAGE_KEY_INSERT: u32 = 0x49;
const HID_USAGE_KEY_HOME: u32 = 0x4a;
const HID_USAGE_KEY_PAGEUP: u32 = 0x4b;
const HID_USAGE_KEY_DELETE: u32 = 0x4c;
const HID_USAGE_KEY_END: u32 = 0x4d;
const HID_USAGE_KEY_PAGEDOWN: u32 = 0x4e;
const HID_USAGE_KEY_RIGHT: u32 = 0x4f;
const HID_USAGE_KEY_LEFT: u32 = 0x50;
const HID_USAGE_KEY_DOWN: u32 = 0x51;
const HID_USAGE_KEY_UP: u32 = 0x52;
const NON_CONTROL_MODIFIER: u32 =
(input::MODIFIER_SUPER | input::MODIFIER_ALT | input::MODIFIER_SHIFT);
/// Converts the given keyboard event into a String suitable to send to the shell.
/// If the conversion fails for any reason None is returned instead of an Error
/// to promote performance since we do not need to handle all errors for keyboard
/// events which are not supported.
pub fn get_input_sequence_for_key_event(event: &KeyboardEvent) -> Option<String> {
match event.phase {
KeyboardEventPhase::Pressed | KeyboardEventPhase::Repeat => match event.code_point {
0 => HidUsage(event.hid_usage).into(),
_ => CodePoint { code_point: event.code_point, modifiers: event.modifiers }.into(),
},
_ => None,
}
}
/// A trait which can be used to determine if a value indicates that it
/// represents a control key modifier
trait ControlModifier {
/// Returns true if self should be represented as a control only modifier.
fn is_control_only(&self) -> bool;
}
impl ControlModifier for u32 {
fn is_control_only(&self) -> bool {
self & input::MODIFIER_CONTROL != 0 && self & NON_CONTROL_MODIFIER == 0
}
}
/// A struct which can be used to convert a code point
/// and key modifiers to a String
struct CodePoint {
code_point: u32,
modifiers: u32,
}
impl From<CodePoint> for Option<String> {
fn from(item: CodePoint) -> Self {
// We currently don't support higher code points.
if item.code_point > 128 {
return None;
}
let mut code_point = item.code_point;
// Convert to a control code if we are holding ctrl
if item.modifiers.is_control_only() {
if let Some(c) = std::char::from_u32(item.code_point) {
match c {
'a'..='z' => code_point = code_point - 96,
'A'..='Z' => code_point = code_point - 64,
_ => (),
};
}
}
String::from_utf8(vec![code_point as u8]).ok()
}
}
/// A struct which can be used to convert a keyboard event's hid_usage
/// to a suitable string.
struct HidUsage(u32);
impl From<HidUsage> for Option<String> {
fn from(item: HidUsage) -> Self {
let esc: char = 0x1b_u8.into();
macro_rules! escape_string {
($x:expr) => {{
Some(format!("{}{}", esc, $x))
}};
}
match item.0 {
HID_USAGE_KEY_BACKSPACE => Some(String::from("\x7f")),
HID_USAGE_KEY_ESC => escape_string!(""),
HID_USAGE_KEY_PAGEDOWN => escape_string!("[6~"),
HID_USAGE_KEY_PAGEUP => escape_string!("[5~"),
HID_USAGE_KEY_END => escape_string!("[F"),
HID_USAGE_KEY_HOME => escape_string!("[H"),
HID_USAGE_KEY_LEFT => escape_string!("[D"),
HID_USAGE_KEY_UP => escape_string!("[A"),
HID_USAGE_KEY_RIGHT => escape_string!("[C"),
HID_USAGE_KEY_DOWN => escape_string!("[B"),
HID_USAGE_KEY_INSERT => escape_string!("[2~"),
HID_USAGE_KEY_DELETE => escape_string!("[3~"),
HID_USAGE_KEY_ENTER => Some(String::from("\n")),
HID_USAGE_KEY_TAB => Some(String::from("\t")),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_control_only_true_for_left_control() {
assert!(input::MODIFIER_LEFT_CONTROL.is_control_only());
}
#[test]
fn is_control_only_true_for_right_control() {
assert!(input::MODIFIER_RIGHT_CONTROL.is_control_only());
}
#[test]
fn is_control_only_true_for_left_and_right_control() {
assert!(input::MODIFIER_CONTROL.is_control_only());
}
#[test]
fn is_control_only_false() {
assert!(input::MODIFIER_NONE.is_control_only() == false);
assert!(input::MODIFIER_SHIFT.is_control_only() == false);
assert!(input::MODIFIER_CAPS_LOCK.is_control_only() == false);
assert!(input::MODIFIER_ALT.is_control_only() == false);
assert!(input::MODIFIER_SUPER.is_control_only() == false);
}
#[test]
fn convert_from_code_point_unsupported_values() {
assert!(Option::<String>::from(CodePoint { code_point: 129, modifiers: 0 }).is_none());
}
#[test]
fn convert_from_code_point_shifts_when_control_pressed_lowercase() {
let mut i = 0;
for c in (b'a'..=b'z').map(char::from) {
i = i + 1;
let result = Option::<String>::from(CodePoint {
code_point: c as u32,
modifiers: input::MODIFIER_CONTROL,
})
.unwrap();
let expected = String::from_utf8(vec![i]).unwrap();
assert_eq!(result, expected);
}
}
#[test]
fn convert_from_code_point_shifts_when_control_pressed_uppercase() {
let mut i = 0;
for c in (b'A'..=b'Z').map(char::from) {
i = i + 1;
let result = Option::<String>::from(CodePoint {
code_point: c as u32,
modifiers: input::MODIFIER_CONTROL,
})
.unwrap();
let expected = String::from_utf8(vec![i]).unwrap();
assert_eq!(result, expected);
}
}
}
|
/*
* Copyright (c) 2022, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The RACE - Runtime for Airspace Concept Evaluation platform is licensed
* under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
mod models;
mod routes;
mod handlers;
use structopt::StructOpt;
use std::net::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};
use socket2::{Domain, Protocol, SockAddr, Socket, Type};
use std::fs::File;
use std::cell::Cell;
use std::sync::Arc;
use tokio::sync::Mutex;
use warp::Filter;
/// command line options
#[derive(Clone,Debug,StructOpt)]
pub struct CliOpt {
#[structopt(short,long)]
pub in_host: String,
#[structopt(long,default_value="20002")]
pub in_port: u16,
#[structopt(short,long,help=" [e.g. 224.0.0.222 for LAN]")]
pub mc_ip: Option<String>, // e.g. 224.0.0.111
#[structopt(long,default_value="20022")]
pub mc_port: u16,
#[structopt(short,long)]
pub verbose: bool,
#[structopt(short,long)]
pub log_file: Option<String>,
}
/// what we pass into handlers to determine what to do with valid GPS packets received
pub struct SrvOpts {
//--- multicast data
pub mc_addr: Option<SockAddr>,
pub mc_sock: Option<Socket>,
pub verbose: bool,
//--- log file
pub log_file: Option<Cell<File>>,
}
pub type ArcMxSrvOpts = Arc<Mutex<SrvOpts>>;
#[tokio::main]
async fn main() {
let cli_opts = CliOpt::from_args();
let srv = create_server_opts(&cli_opts);
if let Some(socket_addr) = get_gps_addr(&cli_opts) {
println!("listening on {:?}/gps", socket_addr);
if srv.mc_addr.is_some() { println!("multicasting to {}:{}", cli_opts.mc_ip.unwrap(), cli_opts.mc_port) }
if let Some(ref log_file) = cli_opts.log_file { println!("writing to log file: {}", log_file) }
println!("terminate with Ctrl-C ..");
let aso = Arc::new(Mutex::new(srv));
if cli_opts.verbose {
println!("verbose logging enabled");
let log = warp::log::custom(|info| { println!("{} {} -> {}", info.method(), info.path(), info.status()) });
warp::serve( routes::gps_route(aso).with(log) ).run(socket_addr).await
} else {
warp::serve( routes::gps_route(aso)).run(socket_addr).await
}
}
}
fn create_server_opts( cli_opts: &CliOpt) -> SrvOpts {
let sock_addr = get_mc_addr(cli_opts);
let mc_addr = sock_addr.map( |addr| SockAddr::from(addr));
let mc_sock = sock_addr.and_then( |ref addr| get_mc_socket(addr));
let log_file = cli_opts.log_file.as_ref().and_then( |ref path| get_log_file(path));
SrvOpts {
mc_addr: mc_addr,
mc_sock: mc_sock,
verbose: cli_opts.verbose,
log_file: log_file,
}
}
fn get_mc_addr(cli_opt: &CliOpt) -> Option<SocketAddr> {
let ip_addr: Option<IpAddr> = cli_opt.mc_ip.as_ref().and_then( |ref ip_spec| match ip_spec.parse::<IpAddr>() {
Ok(addr) => {
if addr.is_multicast() {
Some(addr)
} else {
eprintln!("not a multicast address: {}", ip_spec);
None
}
},
Err(e) => {
eprintln!("invalid multicast address: {}", e);
None
}
});
let port: u16 = cli_opt.mc_port;
ip_addr.map( |addr| SocketAddr::new(addr,port))
}
fn get_mc_socket(socket_addr: &SocketAddr) -> Option<Socket> {
let domain = if socket_addr.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 };
let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP)).ok()?;
//socket.set_read_timeout(Some(Duration::from_millis(100)))?;
socket.set_reuse_port(true).ok()?;
if socket_addr.is_ipv4() {
socket.bind(&SockAddr::from(SocketAddr::new( Ipv4Addr::new(0, 0, 0, 0).into(), 0,))).ok()?;
} else {
socket.bind(&SockAddr::from(SocketAddr::new( Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).into(), 0,))).ok()?;
}
Some(socket)
}
fn get_log_file (path: &String) -> Option<Cell<File>> {
match File::create(path) {
Ok(file) => Some(Cell::new(file)),
Err(e) => {
eprintln!("failed to open log file: {}", e);
None
}
}
}
fn get_gps_addr (cli_opt: &CliOpt)-> Option<SocketAddr> {
let in_addr = format!("{}:{}", &cli_opt.in_host, cli_opt.in_port);
match in_addr.parse::<SocketAddr>() {
Ok(socket_addr) => Some(socket_addr),
Err(e) => { eprintln!("invalid server address: {}", e); None }
}
} |
use super::{Error, SassFunction};
use css::Value;
use num_rational::Rational;
use num_traits::{One, Zero};
use std::collections::BTreeMap;
use value::{Number, Unit};
use variablescope::Scope;
pub fn register(f: &mut BTreeMap<&'static str, SassFunction>) {
def!(f, hsl(hue, saturation, lightness), |s: &Scope| Ok(
Value::hsla(
to_rational(s.get("hue"))?,
to_rational_percent(s.get("saturation"))?,
to_rational_percent(s.get("lightness"))?,
Rational::one()
)
));
def!(f, hsla(hue, saturation, lightness, alpha), |s: &Scope| Ok(
Value::hsla(
to_rational(s.get("hue"))?,
to_rational_percent(s.get("saturation"))?,
to_rational_percent(s.get("lightness"))?,
to_rational(s.get("alpha"))?
)
));
def!(f, adjust_hue(color, degrees), |s: &Scope| match (
s.get("color"),
s.get("degrees"),
) {
(c @ Value::Color(..), Value::Null) => Ok(c),
(Value::Color(rgba, _), Value::Numeric(v, ..)) => {
let (h, s, l, alpha) = rgba.to_hsla();
Ok(Value::hsla(h + v.value, s, l, alpha))
}
(c, v) => Err(Error::badargs(&["color", "number"], &[&c, &v])),
});
def!(f, complement(color), |s: &Scope| match &s.get("color") {
&Value::Color(ref rgba, _) => {
let (h, s, l, alpha) = rgba.to_hsla();
Ok(Value::hsla(h + 180, s, l, alpha))
}
v => Err(Error::badarg("color", v)),
});
def!(f, saturate(color, amount), |s: &Scope| match (
s.get("color"),
s.get("amount")
) {
(Value::Color(c, _), Value::Null) => Ok(Value::Color(c, None)),
(Value::Color(rgba, _), Value::Numeric(v, u, _)) => {
let (h, s, l, alpha) = rgba.to_hsla();
let v = v.value;
let v = if u == Unit::Percent { v / 100 } else { v };
Ok(Value::hsla(h, s + v, l, alpha))
}
(c, v) => Err(Error::badargs(&["color", "number"], &[&c, &v])),
});
def!(
f,
lighten(color, amount),
|args: &Scope| match &args.get("color") {
&Value::Color(ref rgba, _) => {
let (h, s, l, alpha) = rgba.to_hsla();
let amount = to_rational_percent(args.get("amount"))?;
Ok(Value::hsla(h, s, l + amount, alpha))
}
v => Err(Error::badarg("color", v)),
}
);
def!(
f,
darken(color, amount),
|args: &Scope| match &args.get("color") {
&Value::Color(ref rgba, _) => {
let (h, s, l, alpha) = rgba.to_hsla();
let amount = to_rational_percent(args.get("amount"))?;
Ok(Value::hsla(h, s, l - amount, alpha))
}
v => Err(Error::badarg("color", v)),
}
);
def!(f, hue(color), |args: &Scope| match &args.get("color") {
&Value::Color(ref rgba, _) => {
let (h, _s, _l, _a) = rgba.to_hsla();
Ok(Value::Numeric(Number::from(h), Unit::Deg, true))
}
v => Err(Error::badarg("color", v)),
});
def!(f, saturation(color), |args| match &args.get("color") {
&Value::Color(ref rgba, _) => {
let (_h, s, _l, _a) = rgba.to_hsla();
Ok(percentage(s))
}
v => Err(Error::badarg("color", v)),
});
def!(f, lightness(color), |args| match &args.get("color") {
&Value::Color(ref rgba, _) => {
let (_h, _s, l, _a) = rgba.to_hsla();
Ok(percentage(l))
}
v => Err(Error::badarg("color", v)),
});
def!(
f,
desaturate(color, amount),
|args: &Scope| match &args.get("color") {
&Value::Color(ref rgba, _) => {
let (h, s, l, alpha) = rgba.to_hsla();
let amount = to_rational_percent(args.get("amount"))?;
Ok(Value::hsla(h, s - amount, l, alpha))
}
v => Err(Error::badarg("color", v)),
}
);
}
fn percentage(v: Rational) -> Value {
Value::Numeric(Number::from(v * 100), Unit::Percent, true)
}
fn to_rational(v: Value) -> Result<Rational, Error> {
match v {
Value::Numeric(v, ..) => Ok(v.value),
v => Err(Error::badarg("number", &v)),
}
}
/// Gets a percentage as a fraction 0 .. 1.
/// If v is not a percentage, keep it as it is.
fn to_rational_percent(v: Value) -> Result<Rational, Error> {
match v {
Value::Null => Ok(Rational::zero()),
Value::Numeric(v, Unit::Percent, _) => Ok(v.value / 100),
Value::Numeric(v, ..) => {
let v = v.value;
Ok(if v <= Rational::one() { v } else { v / 100 })
}
v => Err(Error::badarg("number", &v)),
}
}
#[test]
fn test_hsl_black() {
assert_eq!("black", do_evaluate(&[], b"hsl(17, 32%, 0%);"))
}
#[test]
fn test_hsl_white() {
assert_eq!("white", do_evaluate(&[], b"hsl(300, 82%, 100%);"))
}
#[test]
fn test_hsl_gray() {
assert_eq!("gray", do_evaluate(&[], b"hsl(300, 0%, 50%);"))
}
#[test]
fn test_hsl_red() {
assert_eq!("#f7c9c9", do_evaluate(&[], b"hsl(0, 75%, 88%);"))
}
#[test]
fn test_hsl_yellow() {
assert_eq!("#ffff42", do_evaluate(&[], b"hsl(60, 100%, 63%);"))
}
#[test]
fn test_hsl_blue_magenta() {
assert_eq!("#6118aa", do_evaluate(&[], b"hsl(270, 75%, 38%);"))
}
#[cfg(test)]
use super::super::variablescope::test::do_evaluate;
|
use reqwest::header::{AsHeaderName, HeaderValue};
use reqwest::Response;
#[derive(Debug)]
pub enum Error {
Reqwest(reqwest::Error),
Url(url::ParseError),
InvalidHeaderValue,
}
impl From<reqwest::Error> for Error {
fn from(value: reqwest::Error) -> Self {
Error::Reqwest(value)
}
}
impl From<url::ParseError> for Error {
fn from(value: url::ParseError) -> Self {
Error::Url(value)
}
}
impl Error {
pub fn check_header(
response: Response,
key: impl AsHeaderName,
val: &'static str,
) -> Result<Response, Self> {
if response.headers().get(key) != Some(&HeaderValue::from_static(val)) {
return Err(Error::InvalidHeaderValue);
}
Ok(response)
}
}
|
use lexer::{self, Token};
use std::iter::Peekable;
use value::Value;
struct Parser<I: Iterator<Item=Token>> {
tokens: Peekable<I>
}
struct ParseError {
msg: String
}
macro_rules! parse_error {
($($arg:tt)*) => (
return Err(ParseError{msg: format!($($arg)*)})
)
}
impl<I: Iterator<Item=Token>> Parser<I> {
pub fn new(tokens: I) -> Self {
Parser {tokens: tokens.peekable()}
}
pub fn parse_all(&mut self) -> Result<Vec<Value>, ParseError> {
let mut values = Vec::new();
loop {
match try!(self.parse_value()) {
Some(v) => values.push(v),
None => return Ok(values)
}
}
}
pub fn parse_value(&mut self) -> Result<Option<Value>, ParseError> {
match self.tokens.next() {
Some(Token::Identifier(s)) => Ok(Some(Value::Symbol(s))),
Some(Token::String(s)) => Ok(Some(Value::String(s))),
Some(Token::Character(c)) => Ok(Some(Value::Character(c))),
Some(Token::Number(n)) => Ok(Some(Value::Number(n))),
Some(Token::Boolean(b)) => Ok(Some(Value::Boolean(b))),
Some(Token::OpenParen) => Ok(Some(try!(self.parse_list()))),
Some(Token::CloseParen) => parse_error!("Unexpected closing paren"),
Some(_) => unimplemented!(),
None => Ok(None)
}
}
fn parse_list(&mut self) -> Result<Value, ParseError> {
match self.tokens.peek() {
Some(&Token::CloseParen) => {
// Consume closing paren.
self.tokens.next();
Ok(Value::Nil)
},
Some(_) => {
let car = try!(self.parse_value()).unwrap();
let cdr = try!(self.parse_list());
Ok(Value::Pair(Box::new(car), Box::new(cdr)))
},
None => parse_error!("Expected closing paren")
}
}
}
|
pub fn iter_map_collect<F, T, U>(entities: &Vec<T>, mapper: F) -> Vec<U>
where
F: FnMut(&T) -> U,
{
entities.iter().map(mapper).collect()
}
pub fn clear_console() {
print!("{}[2J", 27 as char);
}
pub fn replace_item<T>(index: &usize, entities: &mut Vec<T>, new_item: T) {
let index = index.clone();
entities.remove(index);
entities.insert(index, new_item);
}
|
#![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 PhotoImportAccessMode(pub i32);
impl PhotoImportAccessMode {
pub const ReadWrite: Self = Self(0i32);
pub const ReadOnly: Self = Self(1i32);
pub const ReadAndDelete: Self = Self(2i32);
}
impl ::core::marker::Copy for PhotoImportAccessMode {}
impl ::core::clone::Clone for PhotoImportAccessMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhotoImportConnectionTransport(pub i32);
impl PhotoImportConnectionTransport {
pub const Unknown: Self = Self(0i32);
pub const Usb: Self = Self(1i32);
pub const IP: Self = Self(2i32);
pub const Bluetooth: Self = Self(3i32);
}
impl ::core::marker::Copy for PhotoImportConnectionTransport {}
impl ::core::clone::Clone for PhotoImportConnectionTransport {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhotoImportContentType(pub i32);
impl PhotoImportContentType {
pub const Unknown: Self = Self(0i32);
pub const Image: Self = Self(1i32);
pub const Video: Self = Self(2i32);
}
impl ::core::marker::Copy for PhotoImportContentType {}
impl ::core::clone::Clone for PhotoImportContentType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhotoImportContentTypeFilter(pub i32);
impl PhotoImportContentTypeFilter {
pub const OnlyImages: Self = Self(0i32);
pub const OnlyVideos: Self = Self(1i32);
pub const ImagesAndVideos: Self = Self(2i32);
pub const ImagesAndVideosFromCameraRoll: Self = Self(3i32);
}
impl ::core::marker::Copy for PhotoImportContentTypeFilter {}
impl ::core::clone::Clone for PhotoImportContentTypeFilter {
fn clone(&self) -> Self {
*self
}
}
pub type PhotoImportDeleteImportedItemsFromSourceResult = *mut ::core::ffi::c_void;
pub type PhotoImportFindItemsResult = *mut ::core::ffi::c_void;
pub type PhotoImportImportItemsResult = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhotoImportImportMode(pub i32);
impl PhotoImportImportMode {
pub const ImportEverything: Self = Self(0i32);
pub const IgnoreSidecars: Self = Self(1i32);
pub const IgnoreSiblings: Self = Self(2i32);
pub const IgnoreSidecarsAndSiblings: Self = Self(3i32);
}
impl ::core::marker::Copy for PhotoImportImportMode {}
impl ::core::clone::Clone for PhotoImportImportMode {
fn clone(&self) -> Self {
*self
}
}
pub type PhotoImportItem = *mut ::core::ffi::c_void;
pub type PhotoImportItemImportedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhotoImportItemSelectionMode(pub i32);
impl PhotoImportItemSelectionMode {
pub const SelectAll: Self = Self(0i32);
pub const SelectNone: Self = Self(1i32);
pub const SelectNew: Self = Self(2i32);
}
impl ::core::marker::Copy for PhotoImportItemSelectionMode {}
impl ::core::clone::Clone for PhotoImportItemSelectionMode {
fn clone(&self) -> Self {
*self
}
}
pub type PhotoImportOperation = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhotoImportPowerSource(pub i32);
impl PhotoImportPowerSource {
pub const Unknown: Self = Self(0i32);
pub const Battery: Self = Self(1i32);
pub const External: Self = Self(2i32);
}
impl ::core::marker::Copy for PhotoImportPowerSource {}
impl ::core::clone::Clone for PhotoImportPowerSource {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct PhotoImportProgress {
pub ItemsImported: u32,
pub TotalItemsToImport: u32,
pub BytesImported: u64,
pub TotalBytesToImport: u64,
pub ImportProgress: f64,
}
impl ::core::marker::Copy for PhotoImportProgress {}
impl ::core::clone::Clone for PhotoImportProgress {
fn clone(&self) -> Self {
*self
}
}
pub type PhotoImportSelectionChangedEventArgs = *mut ::core::ffi::c_void;
pub type PhotoImportSession = *mut ::core::ffi::c_void;
pub type PhotoImportSidecar = *mut ::core::ffi::c_void;
pub type PhotoImportSource = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhotoImportSourceType(pub i32);
impl PhotoImportSourceType {
pub const Generic: Self = Self(0i32);
pub const Camera: Self = Self(1i32);
pub const MediaPlayer: Self = Self(2i32);
pub const Phone: Self = Self(3i32);
pub const Video: Self = Self(4i32);
pub const PersonalInfoManager: Self = Self(5i32);
pub const AudioRecorder: Self = Self(6i32);
}
impl ::core::marker::Copy for PhotoImportSourceType {}
impl ::core::clone::Clone for PhotoImportSourceType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhotoImportStage(pub i32);
impl PhotoImportStage {
pub const NotStarted: Self = Self(0i32);
pub const FindingItems: Self = Self(1i32);
pub const ImportingItems: Self = Self(2i32);
pub const DeletingImportedItemsFromSource: Self = Self(3i32);
}
impl ::core::marker::Copy for PhotoImportStage {}
impl ::core::clone::Clone for PhotoImportStage {
fn clone(&self) -> Self {
*self
}
}
pub type PhotoImportStorageMedium = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct PhotoImportStorageMediumType(pub i32);
impl PhotoImportStorageMediumType {
pub const Undefined: Self = Self(0i32);
pub const Fixed: Self = Self(1i32);
pub const Removable: Self = Self(2i32);
}
impl ::core::marker::Copy for PhotoImportStorageMediumType {}
impl ::core::clone::Clone for PhotoImportStorageMediumType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhotoImportSubfolderCreationMode(pub i32);
impl PhotoImportSubfolderCreationMode {
pub const DoNotCreateSubfolders: Self = Self(0i32);
pub const CreateSubfoldersFromFileDate: Self = Self(1i32);
pub const CreateSubfoldersFromExifDate: Self = Self(2i32);
pub const KeepOriginalFolderStructure: Self = Self(3i32);
}
impl ::core::marker::Copy for PhotoImportSubfolderCreationMode {}
impl ::core::clone::Clone for PhotoImportSubfolderCreationMode {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct PhotoImportSubfolderDateFormat(pub i32);
impl PhotoImportSubfolderDateFormat {
pub const Year: Self = Self(0i32);
pub const YearMonth: Self = Self(1i32);
pub const YearMonthDay: Self = Self(2i32);
}
impl ::core::marker::Copy for PhotoImportSubfolderDateFormat {}
impl ::core::clone::Clone for PhotoImportSubfolderDateFormat {
fn clone(&self) -> Self {
*self
}
}
pub type PhotoImportVideoSegment = *mut ::core::ffi::c_void;
|
#![windows_subsystem="windows"]
// https://stackoverflow.com/a/45520092/13378247
mod png;
mod jpg;
mod gif;
mod svg;
mod misc;
use misc::{ Args, Options};
#[macro_use] extern crate sciter;
use sciter::{ Value };
use std::{ env, thread };
struct EventHandler {}
impl EventHandler {
fn compressFile(&self, filename: Value, format: Value, addExt: Value, addFolder: Value, callback: Value) -> () {
let ext = String::from(format.to_string());
println!("{}", ext);
let ext = ext.as_str();
println!("{}", ext);
let compression_function = match &ext as &str {
"\"png\"" => png::compress_file,
"\"jpg\"" | "\"jpeg\"" => jpg::compress_file,
ext => {
let err_msg = format!("Unsupported file extension: {}", ext);
callback.call(None, &make_args!("", 0, 0, err_msg), None).unwrap();
return;
}
};
let options = Options { addExt: addExt, addFolder: addFolder };
thread::spawn(move || {
let args = compression_function(filename.as_string().unwrap(), options);
let Args { path, sizeBefore, sizeAfter, error } = args;
callback.call(None, &make_args!(path, sizeBefore, sizeAfter, error), None).unwrap();
});
}
}
impl sciter::EventHandler for EventHandler {
dispatch_script_call! {
fn compressFile(Value, Value, Value, Value, Value);
}
}
fn main() {
sciter::set_options(sciter::RuntimeOptions::DebugMode(false)).unwrap();
let archived = include_bytes!("../target/assets.rc");
sciter::set_options(sciter::RuntimeOptions::ScriptFeatures(
sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_SYSINFO as u8
| sciter::SCRIPT_RUNTIME_FEATURES::ALLOW_FILE_IO as u8
)).unwrap();
let mut frame = sciter::Window::new();
frame.event_handler(EventHandler {});
frame.archive_handler(archived).expect("Unable to load archive");
frame.load_file("this://app/main.htm");
frame.run_app();
}
|
use std::sync::Arc;
use crate::context::Context;
use crate::error::Result;
use crate::file::{Rick, SSTable};
use crate::index::MemIndex;
#[cfg(test)]
use crate::types::Offset;
use crate::types::{Bytes, Entry, LevelId, ThreadId, Timestamp};
#[derive(Hash, PartialEq, Eq)]
pub struct TableIdentifier {
pub tid: ThreadId,
pub lid: LevelId,
}
impl From<(ThreadId, LevelId)> for TableIdentifier {
fn from(ids: (ThreadId, LevelId)) -> Self {
Self {
tid: ids.0,
lid: ids.1,
}
}
}
/// Provides read methods to SSTable.
///
/// If wants to modify a sstable should upgrade to a writable handle
/// (unimplemented).
pub struct TableReadHandle {
memindex: MemIndex,
sstable: SSTable,
rick: Rick,
ctx: Arc<Context>,
}
impl TableReadHandle {
pub fn new(memindex: MemIndex, sstable: SSTable, rick: Rick, ctx: Arc<Context>) -> Self {
Self {
memindex,
sstable,
rick,
ctx,
}
}
pub async fn get(&self, time_key: &(Timestamp, Bytes)) -> Result<Option<Entry>> {
let offset = if self.is_compressed() {
let mut align_time_key = time_key.clone();
align_time_key.0 = self.rick.get_align_ts();
self.memindex.get(&align_time_key)?
} else {
self.memindex.get(time_key)?
};
if let Some(offset) = offset {
Ok(Some(self.rick.read(offset).await?))
} else {
Ok(None)
}
}
/// Upgrade to writeable handle.
pub fn upgrade() -> ! {
todo!()
}
pub fn is_compressed(&self) -> bool {
self.rick.is_compressed()
}
// For test case.
/// Get value's offset in rick file.
#[cfg(test)]
pub fn get_offset(&self, time_key: &(Timestamp, Bytes)) -> Result<Option<Offset>> {
self.memindex.get(time_key)
}
fn decompress_entry(&self, key: &[u8], data: &[u8]) -> Result<Vec<(Timestamp, Bytes)>> {
self.ctx.fn_registry.decompress_entries(key, data)
}
}
|
use bigint::{Gas, U256};
use std::rc::Rc;
use evm::errors::{OnChainError, RuntimeError};
use evm::Precompiled;
pub static BN128_ADD_PRECOMPILED: Bn128AddPrecompiled = Bn128AddPrecompiled;
pub struct Bn128AddPrecompiled;
impl Precompiled for Bn128AddPrecompiled {
fn gas_and_step(&self, data: &[u8], gas_limit: Gas) -> Result<(Gas, Rc<Vec<u8>>), RuntimeError> {
use bn::{AffineG1, Fq, Group, G1};
let gas = Gas::from(500usize);
if gas > gas_limit {
return Err(RuntimeError::OnChain(OnChainError::EmptyGas));
}
// Padding data to be at least 32 * 4 bytes.
let mut data: Vec<u8> = data.into();
while data.len() < 32 * 4 {
data.push(0);
}
let px = Fq::from_slice(&data[0..32]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let py = Fq::from_slice(&data[32..64]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let qx = Fq::from_slice(&data[64..96]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let qy = Fq::from_slice(&data[96..128]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let p = if px == Fq::zero() && py == Fq::zero() {
G1::zero()
} else {
AffineG1::new(px, py)
.map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?
.into()
};
let q = if qx == Fq::zero() && qy == Fq::zero() {
G1::zero()
} else {
AffineG1::new(qx, qy)
.map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?
.into()
};
let mut output = vec![0u8; 64];
if let Some(ret) = AffineG1::from_jacobian(p + q) {
ret.x().to_big_endian(&mut output[0..32]).unwrap();
ret.y().to_big_endian(&mut output[32..64]).unwrap();
}
Ok((gas, Rc::new(output)))
}
}
pub static BN128_MUL_PRECOMPILED: Bn128MulPrecompiled = Bn128MulPrecompiled;
pub struct Bn128MulPrecompiled;
impl Precompiled for Bn128MulPrecompiled {
fn gas_and_step(&self, data: &[u8], gas_limit: Gas) -> Result<(Gas, Rc<Vec<u8>>), RuntimeError> {
use bn::{AffineG1, Fq, Fr, Group, G1};
let gas = Gas::from(40000usize);
if gas > gas_limit {
return Err(RuntimeError::OnChain(OnChainError::EmptyGas));
}
// Padding data to be at least 32 * 4 bytes.
let mut data: Vec<u8> = data.into();
while data.len() < 32 * 3 {
data.push(0);
}
let px = Fq::from_slice(&data[0..32]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let py = Fq::from_slice(&data[32..64]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let fr = Fr::from_slice(&data[64..96]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let p = if px == Fq::zero() && py == Fq::zero() {
G1::zero()
} else {
AffineG1::new(px, py)
.map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?
.into()
};
let mut output = vec![0u8; 64];
if let Some(ret) = AffineG1::from_jacobian(p * fr) {
ret.x().to_big_endian(&mut output[0..32]).unwrap();
ret.y().to_big_endian(&mut output[32..64]).unwrap();
};
Ok((gas, Rc::new(output)))
}
}
pub static BN128_PAIRING_PRECOMPILED: Bn128PairingPrecompiled = Bn128PairingPrecompiled;
pub struct Bn128PairingPrecompiled;
impl Precompiled for Bn128PairingPrecompiled {
fn gas_and_step(&self, data: &[u8], gas_limit: Gas) -> Result<(Gas, Rc<Vec<u8>>), RuntimeError> {
use bn::{pairing, AffineG1, AffineG2, Fq, Fq2, Group, Gt, G1, G2};
fn read_one(s: &[u8]) -> Result<(G1, G2), RuntimeError> {
let ax = Fq::from_slice(&s[0..32]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let ay = Fq::from_slice(&s[32..64]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let bay = Fq::from_slice(&s[64..96]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let bax = Fq::from_slice(&s[96..128]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let bby = Fq::from_slice(&s[128..160]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let bbx = Fq::from_slice(&s[160..192]).map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?;
let ba = Fq2::new(bax, bay);
let bb = Fq2::new(bbx, bby);
let b = if ba.is_zero() && bb.is_zero() {
G2::zero()
} else {
AffineG2::new(ba, bb)
.map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?
.into()
};
let a = if ax.is_zero() && ay.is_zero() {
G1::zero()
} else {
AffineG1::new(ax, ay)
.map_err(|_| RuntimeError::OnChain(OnChainError::EmptyGas))?
.into()
};
Ok((a, b))
}
if data.len() % 192 != 0 {
return Err(RuntimeError::OnChain(OnChainError::EmptyGas));
}
let ele_len = data.len() / 192;
let gas = Gas::from(80000usize) * Gas::from(ele_len) + Gas::from(100000usize);
if gas > gas_limit {
return Err(RuntimeError::OnChain(OnChainError::EmptyGas));
}
let mut acc = Gt::one();
for i in 0..ele_len {
let (a, b) = read_one(&data[i * 192..i * 192 + 192])?;
acc = acc * pairing(a, b);
}
let result = if acc == Gt::one() { U256::from(1) } else { U256::zero() };
let mut output = vec![0u8; 32];
result.to_big_endian(&mut output);
Ok((gas, Rc::new(output)))
}
}
|
// Copyright (c) 2017 Martijn Rijkeboer <mrr@sru-systems.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use crate::common;
use crate::config::Config;
use crate::error::Error;
use crate::result::Result;
/// Structure containing settings for the Argon2 algorithm. A combination of
/// the original argon2_context and argon2_instance_t.
#[derive(Debug, PartialEq)]
pub struct Context<'a> {
/// The config for this context.
pub config: Config<'a>,
/// The length of a lane.
pub lane_length: u32,
/// The number of memory blocks.
pub memory_blocks: u32,
/// The password.
pub pwd: &'a [u8],
/// The salt.
pub salt: &'a [u8],
/// The length of a segment.
pub segment_length: u32,
}
impl<'a> Context<'a> {
/// Attempts to create a new context.
pub fn new(config: Config<'a>, pwd: &'a [u8], salt: &'a [u8]) -> Result<Context<'a>> {
if config.lanes < common::MIN_LANES {
return Err(Error::LanesTooFew);
} else if config.lanes > common::MAX_LANES {
return Err(Error::LanesTooMany);
}
let lanes = config.lanes;
if config.mem_cost < common::MIN_MEMORY {
return Err(Error::MemoryTooLittle);
} else if config.mem_cost > common::MAX_MEMORY {
return Err(Error::MemoryTooMuch);
} else if config.mem_cost < 8 * lanes {
return Err(Error::MemoryTooLittle);
}
if config.time_cost < common::MIN_TIME {
return Err(Error::TimeTooSmall);
} else if config.time_cost > common::MAX_TIME {
return Err(Error::TimeTooLarge);
}
let pwd_len = pwd.len();
if pwd_len < common::MIN_PWD_LENGTH as usize {
return Err(Error::PwdTooShort);
} else if pwd_len > common::MAX_PWD_LENGTH as usize {
return Err(Error::PwdTooLong);
}
let salt_len = salt.len();
if salt_len < common::MIN_SALT_LENGTH as usize {
return Err(Error::SaltTooShort);
} else if salt_len > common::MAX_SALT_LENGTH as usize {
return Err(Error::SaltTooLong);
}
let secret_len = config.secret.len();
if secret_len < common::MIN_SECRET_LENGTH as usize {
return Err(Error::SecretTooShort);
} else if secret_len > common::MAX_SECRET_LENGTH as usize {
return Err(Error::SecretTooLong);
}
let ad_len = config.ad.len();
if ad_len < common::MIN_AD_LENGTH as usize {
return Err(Error::AdTooShort);
} else if ad_len > common::MAX_AD_LENGTH as usize {
return Err(Error::AdTooLong);
}
if config.hash_length < common::MIN_HASH_LENGTH {
return Err(Error::OutputTooShort);
} else if config.hash_length > common::MAX_HASH_LENGTH {
return Err(Error::OutputTooLong);
}
let mut memory_blocks = config.mem_cost;
if memory_blocks < 2 * common::SYNC_POINTS * lanes {
memory_blocks = 2 * common::SYNC_POINTS * lanes;
}
let segment_length = memory_blocks / (lanes * common::SYNC_POINTS);
let memory_blocks = segment_length * (lanes * common::SYNC_POINTS);
let lane_length = segment_length * common::SYNC_POINTS;
Ok(Context {
config,
lane_length,
memory_blocks,
pwd,
salt,
segment_length,
})
}
}
#[cfg(test)]
mod tests {
use crate::config::Config;
use crate::context::Context;
use crate::error::Error;
use crate::variant::Variant;
use crate::version::Version;
#[test]
fn new_returns_correct_instance() {
let config = Config {
ad: b"additionaldata",
hash_length: 32,
lanes: 4,
mem_cost: 4096,
secret: b"secret",
time_cost: 3,
variant: Variant::Argon2i,
version: Version::Version13,
};
let pwd = b"password";
let salt = b"somesalt";
let result = Context::new(config.clone(), pwd, salt);
assert!(result.is_ok());
let context = result.unwrap();
assert_eq!(context.config, config);
assert_eq!(context.pwd, pwd);
assert_eq!(context.salt, salt);
assert_eq!(context.memory_blocks, 4096);
assert_eq!(context.segment_length, 256);
assert_eq!(context.lane_length, 1024);
}
#[test]
fn new_with_too_little_mem_cost_returns_correct_error() {
let config = Config {
mem_cost: 7,
..Default::default()
};
assert_eq!(
Context::new(config, &[0u8; 8], &[0u8; 8]),
Err(Error::MemoryTooLittle)
);
}
#[test]
fn new_with_less_than_8_x_lanes_mem_cost_returns_correct_error() {
let config = Config {
lanes: 4,
mem_cost: 31,
..Default::default()
};
assert_eq!(
Context::new(config, &[0u8; 8], &[0u8; 8]),
Err(Error::MemoryTooLittle)
);
}
#[test]
fn new_with_too_small_time_cost_returns_correct_error() {
let config = Config {
time_cost: 0,
..Default::default()
};
assert_eq!(
Context::new(config, &[0u8; 8], &[0u8; 8]),
Err(Error::TimeTooSmall)
);
}
#[test]
fn new_with_too_few_lanes_returns_correct_error() {
let config = Config {
lanes: 0,
..Default::default()
};
assert_eq!(
Context::new(config, &[0u8; 8], &[0u8; 8]),
Err(Error::LanesTooFew)
);
}
#[test]
fn new_with_too_many_lanes_returns_correct_error() {
let config = Config {
lanes: 1 << 24,
..Default::default()
};
assert_eq!(
Context::new(config, &[0u8; 8], &[0u8; 8]),
Err(Error::LanesTooMany)
);
}
#[test]
fn new_with_too_short_salt_returns_correct_error() {
let config = Default::default();
let salt = [0u8; 7];
assert_eq!(
Context::new(config, &[0u8; 8], &salt),
Err(Error::SaltTooShort)
);
}
#[test]
fn new_with_too_short_hash_length_returns_correct_error() {
let config = Config {
hash_length: 3,
..Default::default()
};
assert_eq!(
Context::new(config, &[0u8; 8], &[0u8; 8]),
Err(Error::OutputTooShort)
);
}
}
|
{{#each inputs~}}
let {{this.[0]}} = {{>choice.getter this.[1] use_old=true}};
{{/each~}}
if true {{#each others_conditions}} && {{this}} {{/each}} {
if old.is({{self_condition}}).maybe_true() && new.is({{self_condition}}).is_true() {
trigger_{{call_id}}.push(({{>choice.arg_ids}}));
}
}
|
extern crate linked_list; // LinkedList in standard library is not usable,
// the solution on Vector does not finish even in 6 hours
fn forward( c : &mut linked_list::Cursor<i32>, times : usize ) -> i32 {
let mut value : Option<&mut i32> = None;
for _j in 0 .. times {
value = c.next();
if value.is_none() { value = c.next(); }
}
*value.unwrap()
}
fn task( steps : usize, last : i32 ) -> ( Vec<i32>, i32 ) {
let mut buffer : linked_list::LinkedList<i32> = linked_list::LinkedList::new();
let mut c = buffer.cursor();
c.insert(0);
let last1 = last + 1;
let steps1 = steps + 1;
for i in 1 .. last1 {
forward( &mut c, steps1 );
c.insert( i );
}
let r_next_element = forward( &mut c,2 );
let r_vec : Vec<i32> = buffer.into_iter().collect();
( r_vec, r_next_element )
}
pub fn task1( steps : usize ) -> i32 {
let last = 2017;
task( steps, last ).1
}
pub fn task2( steps : usize ) -> i32 {
let last = 50000000; // fifty million
let buffer = task( steps, last ).0;
let n = buffer.len();
for i in 0 .. n {
if buffer[i] == 0 { return buffer[(i+1) % n]; }
}
panic!( "unexpected to be here ever" );
} |
use gio::prelude::*;
use soup::Session;
use soup::traits::*;
fn main() -> Result<(), glib::Error> {
let session = Session::new();
let input = session
.request_http("GET", "http://example.com")?
.send(Option::<&gio::Cancellable>::None)?;
let output = gio::WriteOutputStream::new(std::io::stdout());
output.splice(
&input,
gio::OutputStreamSpliceFlags::CLOSE_SOURCE,
Option::<&gio::Cancellable>::None)?;
Ok(())
}
|
use super::Graph;
impl Graph {
pub fn new(node_size: usize) -> Graph{
let mut edge: Vec<Vec<(usize,i64)>> = Vec::<Vec<(usize,i64)>>::with_capacity(node_size);
for _ in 0..node_size {
edge.push(vec![]);
}
Graph{
node_size,
edge_size: 0,
edge
}
}
pub fn add_edge(&mut self, from: usize, to: usize, cost: i64) {
self.edge[from].push((to, cost));
self.edge_size += 1;
}
} |
use crate::{
impl_interfacetype::private_associated_type,
my_visibility::{RelativeVis, VisibilityKind},
parse_utils::parse_str_as_ident,
workaround::token_stream_to_string,
*,
};
use std::marker::PhantomData;
use proc_macro2::TokenStream as TokenStream2;
use quote::TokenStreamExt;
use syn::ItemTrait;
use as_derive_utils::{
gen_params_in::{GenParamsIn, InWhat},
to_token_fn::ToTokenFnMut,
};
mod attribute_parsing;
mod common_tokens;
mod impl_delegations;
mod lifetime_unelider;
mod method_where_clause;
mod methods_tokenizer;
mod replace_self_path;
mod trait_definition;
#[cfg(test)]
mod tests;
use self::{
attribute_parsing::SabiTraitOptions,
common_tokens::{CommonTokens, IsStaticTrait, LifetimeTokens},
lifetime_unelider::LifetimeUnelider,
method_where_clause::MethodWhereClause,
methods_tokenizer::MethodsTokenizer,
trait_definition::{TraitDefinition, TraitMethod},
};
/// Variables passed to all the `*_items` functions here.
#[allow(dead_code)]
#[derive(Copy, Clone)]
struct TokenizerParams<'a> {
arenas: &'a Arenas,
ctokens: &'a CommonTokens,
config: &'a SabiTraitOptions<'a>,
trait_def: &'a TraitDefinition<'a>,
vis: VisibilityKind<'a>,
submod_vis: RelativeVis<'a>,
totrait_def: &'a TraitDefinition<'a>,
vtable_trait_decl: &'a TraitDefinition<'a>,
vtable_trait_impl: &'a TraitDefinition<'a>,
trait_ident: &'a syn::Ident,
trait_to: &'a syn::Ident,
trait_backend: &'a syn::Ident,
trait_interface: &'a syn::Ident,
make_vtable_ident: &'a syn::Ident,
trait_cto_ident: &'a syn::Ident,
/// TokenStreams that don't have a `'lt,` if the trait object requires
/// `'static` to be constructed.
lt_tokens: &'a LifetimeTokens,
}
/// The implementation of the `#[sabi_trait]` proc-macro attribute.
pub fn derive_sabi_trait(item: ItemTrait) -> Result<TokenStream2, syn::Error> {
let arenas = Arenas::default();
let arenas = &arenas;
let ctokens = CommonTokens::new();
let ctokens = &ctokens;
let trait_ident = &item.ident;
let config = &self::attribute_parsing::parse_attrs_for_sabi_trait(&item, arenas, ctokens)?;
let trait_def = &config.trait_definition;
let lt_tokens = &LifetimeTokens::new(trait_def.is_static);
let vis = trait_def.vis;
let submod_vis = trait_def.submod_vis;
let totrait_def = &trait_def.replace_self(WhichItem::TraitObjectImpl)?;
let vtable_trait_decl = &trait_def.replace_self(WhichItem::VtableDecl)?;
let vtable_trait_impl = &trait_def.replace_self(WhichItem::VtableImpl)?;
let generated_mod = &parse_str_as_ident(&format!("{}_trait", trait_ident));
let trait_to = &parse_str_as_ident(&format!("{}_TO", trait_ident));
let trait_backend = &parse_str_as_ident(&format!("{}_Backend", trait_ident));
let trait_interface = &parse_str_as_ident(&format!("{}_Interface", trait_ident));
let make_vtable_ident = &parse_str_as_ident(&format!("{}_MV", trait_ident));
let trait_cto_ident = &parse_str_as_ident(&format!("{}_CTO", trait_ident));
let mut mod_contents = TokenStream2::default();
let tokenizer_params = TokenizerParams {
arenas,
ctokens,
config,
lt_tokens,
trait_def,
vis,
submod_vis,
totrait_def,
vtable_trait_decl,
vtable_trait_impl,
trait_ident,
trait_to,
trait_backend,
trait_interface,
make_vtable_ident,
trait_cto_ident,
};
first_items(tokenizer_params, &mut mod_contents);
constructor_items(tokenizer_params, &mut mod_contents);
trait_and_impl(tokenizer_params, &mut mod_contents);
methods_impls(tokenizer_params, &mut mod_contents)?;
declare_vtable(tokenizer_params, &mut mod_contents);
vtable_impl(tokenizer_params, &mut mod_contents);
impl_delegations::delegated_impls(tokenizer_params, &mut mod_contents);
let doc_hidden_attr = config.doc_hidden_attr;
let mod_docs = if doc_hidden_attr.is_none() {
Some(format!(
"This module is generated by the \
[`#[sabi_trait]`](macro@::abi_stable::sabi_trait) \
attribute on \
[{trait_}](trait@{trait_})",
trait_ = trait_ident,
))
} else {
None
}
.into_iter();
let mut tokens = quote!(
#doc_hidden_attr
#[doc(inline)]
#vis use self::#generated_mod::{
#trait_to,
#trait_ident,
#trait_cto_ident,
};
#doc_hidden_attr
#(#[doc = #mod_docs])*
#[allow(explicit_outlives_requirements)]
#vis mod #generated_mod{
#mod_contents
}
);
if config.debug_output_tokens {
let tokens_str = tokens.to_string();
tokens.append_all(quote!(
pub const TOKENS: &'static str = #tokens_str;
));
}
// drop(_measure_time1);
if config.debug_print_trait {
panic!("\n\n\n{}\n\n\n", token_stream_to_string(tokens.clone()));
}
Ok(tokens)
}
/// Outputs these items:
///
/// - `Trait_Backend`:
/// A type alias to the underlying implementation of the trait object,
/// which is either RObject
///
/// - `Trait_Interface`
/// A marker type describing the traits that are required when constructing
/// the underlying implementation of the trait object,
/// and are then implemented by it,
/// by implementing [`InterfaceType`](::abi_stable::InterfaceType).
///
/// - `Trait_TO`:
/// The ffi-safe trait object for the trait.
///
fn first_items(
TokenizerParams {
config,
ctokens,
lt_tokens,
trait_def,
submod_vis,
trait_to,
trait_backend,
trait_interface,
trait_cto_ident,
..
}: TokenizerParams,
mod_: &mut TokenStream2,
) {
let trait_ident = trait_def.name;
let doc_hidden_attr = config.doc_hidden_attr;
let mut uto_params = trait_def.generics_tokenizer(
InWhat::ItemDecl,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
uto_params.set_no_bounds();
let mut gen_params_header_rref = trait_def.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_sub_lt,
);
gen_params_header_rref.set_no_bounds();
let gen_params_use_to_rref = trait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_rref,
);
let uto_params_use = trait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let mut trait_interface_header = trait_def.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_empty,
);
trait_interface_header.set_no_bounds();
let mut trait_interface_decl = trait_def.generics_tokenizer(
InWhat::ItemDecl,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_empty,
);
trait_interface_decl.set_no_bounds();
// trait_interface_decl.set_unsized_types();
let trait_interface_use = trait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_empty,
);
let to_params = trait_def.generics_tokenizer(
InWhat::ItemDecl,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let where_preds = (&trait_def.where_preds).into_iter();
let vtable_args = trait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_unit_erasedptr,
);
let impld_traits = trait_def.impld_traits.iter().map(|x| &x.ident);
let impld_traits_a = impld_traits.clone();
let impld_traits_b = impld_traits.clone();
let unimpld_traits_a = trait_def.unimpld_traits.iter().cloned();
let unimpld_traits_b = trait_def.unimpld_traits.iter().cloned();
let priv_assocty = private_associated_type();
let object = match trait_def.which_object {
WhichObject::DynTrait => quote!(DynTrait),
WhichObject::RObject => quote!(RObject),
};
let vtable_argument = match trait_def.which_object {
WhichObject::DynTrait => quote!(__sabi_re::PrefixRef<VTable_Prefix<#vtable_args>>),
WhichObject::RObject => quote!(VTable_Prefix<#vtable_args>),
};
let dummy_struct_generics = trait_def.generics_tokenizer(
InWhat::DummyStruct,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_empty,
);
// dummy_struct_generics.set_unsized_types();
let used_trait_object = quote!(#trait_backend<#uto_params_use>);
let trait_flags = &trait_def.trait_flags;
let send_syncness = match (trait_flags.sync, trait_flags.send) {
(false, false) => "UnsyncUnsend",
(false, true) => "UnsyncSend",
(true, false) => "SyncUnsend",
(true, true) => "SyncSend",
}
.piped(parse_str_as_ident);
let mut trait_backend_docs = String::new();
let mut trait_interface_docs = String::new();
let mut trait_to_docs = String::new();
let mut trait_cto_docs = String::new();
if doc_hidden_attr.is_none() {
trait_backend_docs = format!(
"An alias for the underlying implementation of \
[`{trait_to}`](struct@{trait_to}).\
",
trait_to = trait_to
);
trait_interface_docs = format!(
"A marker type describing the traits that are required when constructing \
[`{trait_to}`](struct@{trait_to}),\
and are then implemented by it,
by implementing the
[`InterfaceType`](::abi_stable::InterfaceType)
trait.",
trait_to = trait_to
);
trait_to_docs = format!(
"\
The trait object for [{Trait}](trait@{Trait}).\n\
\n\
There are extra methods on the `obj` field.\n
",
Trait = trait_ident
);
trait_cto_docs = format!(
"A type alias for the const-constructible \
[`{trait_to}`](struct@{trait_to}).",
trait_to = trait_to
);
}
let one_lt = <_tokens.one_lt;
quote!(
use super::*;
use abi_stable::sabi_trait::reexports::{*,__sabi_re};
use self::#trait_ident as __Trait;
#[doc=#trait_backend_docs]
#submod_vis type #trait_backend<#uto_params>=
__sabi_re::#object<
#one_lt
_ErasedPtr,
#trait_interface<#trait_interface_use>,
#vtable_argument
>;
#[doc=#trait_cto_docs]
#submod_vis type #trait_cto_ident<#gen_params_header_rref>=
#trait_to<#gen_params_use_to_rref>;
#[doc=#trait_interface_docs]
#[repr(C)]
#[derive(::abi_stable::StableAbi)]
#submod_vis struct #trait_interface<#trait_interface_decl>(
__sabi_re::NonOwningPhantom<(#dummy_struct_generics)>
);
impl<#trait_interface_header> #trait_interface<#trait_interface_use> {
/// Constructs this type
#submod_vis const NEW:Self=#trait_interface(__sabi_re::NonOwningPhantom::NEW);
}
#[doc=#trait_to_docs]
#[repr(transparent)]
#[derive(::abi_stable::StableAbi)]
#[sabi(bound(#used_trait_object: ::abi_stable::StableAbi))]
#submod_vis struct #trait_to<#to_params>
where
_ErasedPtr:__GetPointerKind,
#(#where_preds)*
{
///
#submod_vis obj:#used_trait_object,
_marker:__sabi_re::UnsafeIgnoredType< __sabi_re::#send_syncness >,
}
const __inside_generated_mod:()={
use abi_stable::{
InterfaceType,
type_level::{
impl_enum::{Implemented,Unimplemented},
trait_marker,
},
};
impl<#trait_interface_header>
abi_stable::InterfaceType
for #trait_interface<#trait_interface_use>
{
#( type #impld_traits_a=Implemented<trait_marker::#impld_traits_b>; )*
#( type #unimpld_traits_a=Unimplemented<trait_marker::#unimpld_traits_b>; )*
type #priv_assocty=();
}
};
)
.to_tokens(mod_);
}
/// Outputs the trait object constructors.
fn constructor_items(params: TokenizerParams<'_>, mod_: &mut TokenStream2) {
let TokenizerParams {
ctokens,
totrait_def,
submod_vis,
trait_ident,
trait_to,
trait_backend,
trait_interface,
lt_tokens,
make_vtable_ident,
..
} = params;
let doc_hidden_attr = params.config.doc_hidden_attr;
let trait_params =
totrait_def.generics_tokenizer(InWhat::ItemUse, WithAssocTys::No, &ctokens.empty_ts);
let assoc_tys_a = totrait_def.assoc_tys.keys();
let assoc_tys_b = assoc_tys_a.clone();
let assoc_tys_c = assoc_tys_a.clone();
let assoc_tys_d = assoc_tys_a.clone();
let assoc_tys_e = assoc_tys_a.clone();
let assoc_tys_f = assoc_tys_a.clone();
let mut make_vtable_args = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::No,
&ctokens.ts_make_vtable_args,
);
make_vtable_args.skip_lifetimes();
let mut make_vtable_args_const = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::No,
&ctokens.ts_make_vtable_args_const,
);
make_vtable_args_const.skip_lifetimes();
let fn_can_it_downcast_arg = match totrait_def.which_object {
WhichObject::DynTrait => quote!(Downcasting),
WhichObject::RObject => quote!(),
};
let trait_interface_use = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_empty,
);
let one_lt = <_tokens.one_lt;
let extra_constraints_ptr = match totrait_def.which_object {
WhichObject::DynTrait => quote!(
#trait_interface<#trait_interface_use>:
::abi_stable::erased_types::InterfaceType,
__sabi_re::DynTraitVTable_Ref<
#one_lt
_OrigPtr::TransmutedPtr,
#trait_interface<#trait_interface_use>,
>:
__sabi_re::MakeDynTraitVTable<
#one_lt
_OrigPtr::PtrTarget,
_OrigPtr,
Downcasting
>,
),
WhichObject::RObject => quote!(),
};
let extra_constraints_value = match totrait_def.which_object {
WhichObject::DynTrait => quote!(
#trait_interface<#trait_interface_use>:
::abi_stable::erased_types::InterfaceType,
__sabi_re::DynTraitVTable_Ref<
#one_lt
__sabi_re::RBox<()>,
#trait_interface<#trait_interface_use>,
>:
__sabi_re::MakeDynTraitVTable<
#one_lt
_Self,
__sabi_re::RBox<_Self>,
Downcasting
>,
),
WhichObject::RObject => quote!(),
};
let extra_constraints_const = match totrait_def.which_object {
WhichObject::DynTrait => quote!(
#trait_interface<#trait_interface_use>:
::abi_stable::erased_types::InterfaceType,
__sabi_re::DynTraitVTable_Ref<
#one_lt
__sabi_re::RRef<'_sub, ()>,
#trait_interface<#trait_interface_use>,
>:
__sabi_re::MakeDynTraitVTable<
#one_lt
_Self,
&'_sub _Self,
Downcasting
>,
),
WhichObject::RObject => quote!(),
};
let gen_params_header = totrait_def.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let gen_params_use_to = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let gen_params_header_rbox = totrait_def.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt,
);
let gen_params_use_to_rbox = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_rbox,
);
let uto_params_use = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let trait_interface_use = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_empty,
);
let gen_params_header_rref = totrait_def.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_sub_lt,
);
let gen_params_use_to_rref = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_rref,
);
let mut shared_docs = String::new();
let mut from_ptr_docs = String::new();
let mut from_value_docs = String::new();
let mut from_const_docs = String::new();
if doc_hidden_attr.is_none() {
shared_docs = "\
<br><br>\
`can_it_downcast` describes whether the trait object can be \
converted back into the original type or not.<br>\n\
Its possible values are `TD_CanDowncast` and `TD_Opaque`.\n\
"
.to_string();
from_ptr_docs = format!(
"Constructs this trait object from a pointer to a type that implements `{trait_}`.\n\
\n\
This method is automatically generated,\n\
for more documentation you can look at\n\
[`abi_stable::docs::sabi_trait_inherent#from_ptr-method`]\n\
",
trait_ = trait_ident
);
from_value_docs = format!(
"Constructs this trait from a type that implements `{trait_}`.\n\
\n\
This method is automatically generated,\n\
for more documentation you can look at\n\
[`abi_stable::docs::sabi_trait_inherent#from_value-method`]\n\
",
trait_ = trait_ident
);
from_const_docs = format!(
"Constructs this trait from a constant of a type that implements `{trait_}`.\n\
\n\
This method is automatically generated,\n\
for more documentation you can look at\n\
[`abi_stable::docs::sabi_trait_inherent#from_const-method`]\n\
\n\
You can construct the `vtable_for` parameter with \
[`{make_vtable_ident}::VTABLE`].\n\
",
trait_ = trait_ident,
make_vtable_ident = make_vtable_ident,
);
}
let reborrow_methods = reborrow_methods_tokenizer(params);
let plus_lt = <_tokens.plus_lt;
let constructing_backend = match totrait_def.which_object {
WhichObject::DynTrait => quote!(
#trait_backend::from_const(
ptr,
can_it_downcast,
#make_vtable_ident::<#make_vtable_args_const>::VTABLE_INNER
)
),
WhichObject::RObject => quote!({
let _ = __sabi_re::ManuallyDrop::new(can_it_downcast);
#trait_backend::with_vtable_const::<_, Downcasting>(
ptr,
#make_vtable_ident::<#make_vtable_args_const>::VTABLE_INNER
)
}),
};
quote!(
impl<#gen_params_header> #trait_to<#gen_params_use_to>
where
_ErasedPtr: __sabi_re::AsPtr<PtrTarget = ()>,
{
#[doc=#from_ptr_docs]
#[doc=#shared_docs]
#submod_vis fn from_ptr<_OrigPtr,Downcasting>(
ptr:_OrigPtr,
can_it_downcast:Downcasting,
)->Self
where
_OrigPtr:
__sabi_re::CanTransmuteElement<(),TransmutedPtr=_ErasedPtr>,
_OrigPtr::PtrTarget:
#trait_ident<#trait_params #( #assoc_tys_a= #assoc_tys_b, )* >+
Sized
#plus_lt,
#trait_interface<#trait_interface_use>:
__sabi_re::GetRObjectVTable<
Downcasting,_OrigPtr::PtrTarget,_ErasedPtr,_OrigPtr
>,
#extra_constraints_ptr
{
let _can_it_downcast=can_it_downcast;
unsafe{
Self{
obj:#trait_backend::with_vtable::<_,#fn_can_it_downcast_arg>(
ptr,
#make_vtable_ident::<#make_vtable_args>::VTABLE_INNER
),
_marker:__sabi_re::UnsafeIgnoredType::DEFAULT,
}
}
}
/// Constructs this trait object from its underlying implementation.
///
/// This method is automatically generated,
/// for more documentation you can look at
/// [`abi_stable::docs::sabi_trait_inherent#from_sabi-method`]
#submod_vis fn from_sabi(obj:#trait_backend<#uto_params_use>)->Self{
Self{
obj,
_marker:__sabi_re::UnsafeIgnoredType::DEFAULT,
}
}
#reborrow_methods
}
impl<#gen_params_header_rbox> #trait_to<#gen_params_use_to_rbox> {
#[doc=#from_value_docs]
#[doc=#shared_docs]
#submod_vis fn from_value<_Self,Downcasting>(
ptr:_Self,
can_it_downcast:Downcasting,
)->Self
where
_Self:
#trait_ident<#trait_params #( #assoc_tys_c= #assoc_tys_d, )* >
#plus_lt,
#trait_interface<#trait_interface_use>:
__sabi_re::GetRObjectVTable<
Downcasting,_Self,__sabi_re::RBox<()>,__sabi_re::RBox<_Self>
>,
#extra_constraints_value
{
Self::from_ptr::<
__sabi_re::RBox<_Self>,
Downcasting
>(__sabi_re::RBox::new(ptr),can_it_downcast)
}
}
impl<#gen_params_header_rref> #trait_to<#gen_params_use_to_rref>{
#[doc=#from_const_docs]
#[doc=#shared_docs]
#submod_vis const fn from_const<_Self,Downcasting>(
ptr:&'_sub _Self,
can_it_downcast:Downcasting,
)->Self
where
_Self:
#trait_ident<#trait_params #( #assoc_tys_e = #assoc_tys_f, )* >
#plus_lt,
_Self: #one_lt
#trait_interface<#trait_interface_use>:
__sabi_re::GetRObjectVTable<
Downcasting, _Self, __sabi_re::RRef<'_sub, ()>, &'_sub _Self
>,
#extra_constraints_const
{
unsafe{
Self{
obj:#constructing_backend,
_marker:__sabi_re::UnsafeIgnoredType::DEFAULT,
}
}
}
}
)
.to_tokens(mod_);
}
/// Returns a tokenizer for the reborrowing methods
fn reborrow_methods_tokenizer(
TokenizerParams {
totrait_def,
submod_vis,
trait_to,
lt_tokens,
..
}: TokenizerParams<'_>,
) -> impl ToTokens + '_ {
ToTokenFnMut::new(move |ts| {
let traits = totrait_def.trait_flags;
// If the trait object doesn't have both Sync+Send as supertraits or neither,
// it can't be reborrowed.
if traits.sync != traits.send {
return;
}
let gen_params_use_ref = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_rref,
);
let gen_params_use_mut = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_rmut,
);
quote!(
/// Reborrows this trait object to a reference-based trait object.
///
/// This method is automatically generated,
/// for more documentation you can look at
/// [`abi_stable::docs::sabi_trait_inherent#sabi_reborrow-method`]
#submod_vis fn sabi_reborrow<'_sub>(&'_sub self)->#trait_to<#gen_params_use_ref> {
let x = self.obj.reborrow();
// This is transmuting the pointer type parameter of the vtable.
let x = unsafe{ __sabi_re::transmute(x) };
#trait_to::from_sabi(x)
}
/// Reborrows this trait object to a mutable-reference-based trait object.
///
/// This method is automatically generated,
/// for more documentation you can look at
/// [`abi_stable::docs::sabi_trait_inherent#sabi_reborrow_mut-method`]
#submod_vis fn sabi_reborrow_mut<'_sub>(&'_sub mut self)->#trait_to<#gen_params_use_mut>
where
_ErasedPtr: __sabi_re::AsMutPtr<PtrTarget=()>
{
let x = self.obj.reborrow_mut();
// This is transmuting the pointer type parameter of the vtable.
let x = unsafe{ __sabi_re::transmute(x) };
#trait_to::from_sabi(x)
}
)
.to_tokens(ts);
})
}
/// Outputs the annotated trait (as modified by the proc-macro)
/// and an implementation of the trait for the generated trait object.
fn trait_and_impl(
TokenizerParams {
ctokens,
submod_vis,
trait_def,
trait_to,
lt_tokens,
trait_ident,
..
}: TokenizerParams,
mod_: &mut TokenStream2,
) {
let other_attrs = trait_def.other_attrs;
let gen_params_trait =
trait_def.generics_tokenizer(InWhat::ItemDecl, WithAssocTys::No, &ctokens.empty_ts);
let where_preds = (&trait_def.where_preds).into_iter();
let where_preds_b = where_preds.clone();
let methods_tokenizer_def = trait_def.methods_tokenizer(WhichItem::Trait);
let methods_tokenizer_impl = trait_def.methods_tokenizer(WhichItem::TraitImpl);
let lifetime_bounds_a = trait_def.lifetime_bounds.iter();
let lifetime_bounds_c = trait_def.lifetime_bounds.iter();
let super_traits_a = trait_def.impld_traits.iter().map(|t| &t.bound);
let super_traits_b = super_traits_a.clone();
let assoc_tys_a = trait_def.assoc_tys.values().map(|x| &x.assoc_ty);
let unsafety = trait_def.item.unsafety;
let erased_ptr_bounds = trait_def.erased_ptr_preds();
quote!(
#[allow(clippy::needless_lifetimes, clippy::new_ret_no_self)]
#( #other_attrs )*
#submod_vis #unsafety trait #trait_ident<
#gen_params_trait
>: #( #super_traits_a + )* #( #lifetime_bounds_a + )*
where
#(#where_preds,)*
{
#( #assoc_tys_a )*
#methods_tokenizer_def
}
)
.to_tokens(mod_);
let gen_params_use_trait =
trait_def.generics_tokenizer(InWhat::ItemUse, WithAssocTys::No, &ctokens.empty_ts);
if !trait_def.disable_trait_impl {
let gen_params_header = trait_def.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let gen_params_use_to = trait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let assoc_ty_named_a = trait_def.assoc_tys.values().map(|x| &x.assoc_ty.ident);
let assoc_ty_named_b = assoc_ty_named_a.clone();
quote!(
#[deny(unsafe_op_in_unsafe_fn)]
#[allow(
clippy::needless_lifetimes,
clippy::new_ret_no_self,
)]
impl<#gen_params_header> #trait_ident<#gen_params_use_trait>
for #trait_to<#gen_params_use_to>
where
Self:#( #super_traits_b + )* #(#lifetime_bounds_c+)* ,
#erased_ptr_bounds
#(#where_preds_b,)*
{
#( type #assoc_ty_named_a=#assoc_ty_named_b; )*
#methods_tokenizer_impl
}
)
.to_tokens(mod_);
}
}
/// An inherent implementation of the generated trait object,
/// which mirrors the trait definition.
fn methods_impls(param: TokenizerParams, mod_: &mut TokenStream2) -> Result<(), syn::Error> {
let TokenizerParams {
totrait_def,
trait_to,
ctokens,
lt_tokens,
..
} = param;
let impl_where_preds = totrait_def.trait_impl_where_preds()?;
let super_traits_a = totrait_def.impld_traits.iter().map(|t| &t.bound);
let gen_params_header = totrait_def.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let gen_params_use_to = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
<_tokens.lt_erasedptr,
);
let generics_use1 = totrait_def.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_unit_erasedptr,
);
let methods_tokenizer_def = totrait_def.methods_tokenizer(WhichItem::TraitObjectImpl);
quote!(
#[allow(clippy::needless_lifetimes, clippy::new_ret_no_self)]
impl<#gen_params_header> #trait_to<#gen_params_use_to>
where
_ErasedPtr: __sabi_re::AsPtr<PtrTarget = ()>,
Self:#( #super_traits_a + )* ,
#impl_where_preds
{
#[inline]
fn sabi_vtable(
&self
)-> VTable_Ref<#generics_use1> {
unsafe{
VTable_Ref(self.obj.sabi_et_vtable())
}
}
#methods_tokenizer_def
}
)
.to_tokens(mod_);
Ok(())
}
/// Outputs the vtable struct.
fn declare_vtable(
TokenizerParams {
ctokens,
vtable_trait_decl,
submod_vis,
trait_interface,
..
}: TokenizerParams,
mod_: &mut TokenStream2,
) {
let generics_decl = vtable_trait_decl.generics_tokenizer(
InWhat::ItemDecl,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_self_erasedptr,
);
let mut generics_decl_unbounded = generics_decl;
generics_decl_unbounded.set_no_bounds();
let mut generics_use0 = vtable_trait_decl.generics_tokenizer(
InWhat::DummyStruct,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_self_erasedptr,
);
generics_use0.set_no_bounds();
let derive_attrs = vtable_trait_decl.derive_attrs;
let methods_tokenizer = vtable_trait_decl.methods_tokenizer(WhichItem::VtableDecl);
let lifetime_bounds = if vtable_trait_decl.lifetime_bounds.is_empty() {
None
} else {
let mut lifetime_bounds = quote!(_Self:);
for lt in &vtable_trait_decl.lifetime_bounds {
lifetime_bounds.append_all(quote!(#lt +));
}
lifetime_bounds.append(parse_str_as_ident("Sized"));
Some(lifetime_bounds)
}
.into_iter();
let trait_interface_use = vtable_trait_decl.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::NoSelf),
&ctokens.ts_empty,
);
let robject_vtable = quote!(
__sabi_re::RObjectVtable_Ref<
_Self,
_ErasedPtr,
#trait_interface<#trait_interface_use>
>
);
quote!(
#[repr(C)]
#[derive(abi_stable::StableAbi)]
#[sabi(kind(Prefix(prefix_ref = VTable_Ref)))]
#[sabi(missing_field(panic))]
#( #[sabi(prefix_bound(#lifetime_bounds))] )*
#[sabi(bound(#robject_vtable: ::abi_stable::StableAbi))]
#(#derive_attrs)*
#[doc(hidden)]
#submod_vis struct VTable<#generics_decl>
where
_ErasedPtr:__GetPointerKind,
{
_sabi_tys: __sabi_re::NonOwningPhantom<(#generics_use0)>,
_sabi_vtable:#robject_vtable,
#methods_tokenizer
}
)
.to_tokens(mod_);
}
/// Outputs the vtable impl block with both:
///
/// - A constant where the vtable is constructed.
///
/// - The methods that the vtable is constructed with.
///
fn vtable_impl(
TokenizerParams {
ctokens,
vtable_trait_impl,
trait_interface,
trait_ident,
make_vtable_ident,
lt_tokens,
..
}: TokenizerParams,
mod_: &mut TokenStream2,
) {
let struct_decl_generics = vtable_trait_impl.generics_tokenizer(
InWhat::ItemDecl,
WithAssocTys::No,
&ctokens.ts_getvtable_params,
);
let dummy_struct_tys = vtable_trait_impl.generics_tokenizer(
InWhat::DummyStruct,
WithAssocTys::No,
&ctokens.ts_getvtable_dummy_struct_fields,
);
let impl_header_generics = vtable_trait_impl.generics_tokenizer(
InWhat::ImplHeader,
WithAssocTys::No,
&ctokens.ts_getvtable_params,
);
let makevtable_generics = vtable_trait_impl.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::No,
&ctokens.ts_getvtable_params,
);
let trait_generics =
vtable_trait_impl.generics_tokenizer(InWhat::ItemUse, WithAssocTys::No, &ctokens.empty_ts);
let withmetadata_generics = vtable_trait_impl.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::Underscore),
&ctokens.ts_self_erasedptr,
);
let trait_interface_use = vtable_trait_impl.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::Underscore),
&ctokens.ts_empty,
);
let method_names_a = vtable_trait_impl.methods.iter().map(|m| m.name);
let method_names_b = method_names_a.clone();
let vtable_generics = vtable_trait_impl.generics_tokenizer(
InWhat::ItemUse,
WithAssocTys::Yes(WhichSelf::Underscore),
&ctokens.ts_unit_erasedptr,
);
let methods_tokenizer = vtable_trait_impl.methods_tokenizer(WhichItem::VtableImpl);
let one_lt = <_tokens.one_lt;
let extra_constraints = match vtable_trait_impl.which_object {
WhichObject::DynTrait => quote!(
#trait_interface<#trait_interface_use>:
::abi_stable::erased_types::InterfaceType,
__sabi_re::DynTraitVTable_Ref<
#one_lt
_ErasedPtr,
#trait_interface<#trait_interface_use>,
>:
__sabi_re::MakeDynTraitVTable<
#one_lt
_Self,
_OrigPtr,
IA,
>,
),
WhichObject::RObject => quote!(),
};
quote!(
struct #make_vtable_ident<#struct_decl_generics>(#dummy_struct_tys);
#[deny(unsafe_op_in_unsafe_fn)]
impl<#impl_header_generics> #make_vtable_ident<#makevtable_generics>
where
_Self: #trait_ident<#trait_generics>,
_OrigPtr:
__sabi_re::CanTransmuteElement<(), PtrTarget = _Self, TransmutedPtr = _ErasedPtr>,
_ErasedPtr:__sabi_re::AsPtr<PtrTarget=()>,
#trait_interface<#trait_interface_use>:
__sabi_re::GetRObjectVTable<IA,_Self,_ErasedPtr,_OrigPtr>,
#extra_constraints
{
const TMP0: __sabi_re::WithMetadata<
VTable<#withmetadata_generics>
>={
__sabi_re::WithMetadata::new(
VTable{
_sabi_tys: __sabi_re::NonOwningPhantom::NEW,
_sabi_vtable:__sabi_re::GetRObjectVTable::ROBJECT_VTABLE,
#(
#method_names_a:Self::#method_names_b,
)*
}
)
};
const VTABLE_INNER: __sabi_re::PrefixRef<VTable_Prefix<#vtable_generics> > =unsafe{
__sabi_re::WithMetadata::raw_as_prefix(&Self::TMP0)
.cast() // erasing the `_Self` parameter
};
#methods_tokenizer
}
)
.to_tokens(mod_);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SelfParam<'a> {
ByRef {
lifetime: Option<&'a syn::Lifetime>,
is_mutable: bool,
},
ByVal,
}
/// Which item this is refering to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WhichItem {
/// the method in the trait definition
Trait,
/// the method in the trait implemetation for the generated trait object.
TraitImpl,
/// the methods in the inherent implemetation of the generated trait object.
TraitObjectImpl,
/// the fields of the trait object vtable.
VtableDecl,
/// the methods used to construct the vtable.
VtableImpl,
}
/// Which type used to implement the trait object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WhichObject {
DynTrait,
RObject,
}
impl Default for WhichObject {
fn default() -> Self {
WhichObject::RObject
}
}
/// Which Self type to get the associated types from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WhichSelf {
/// Self::AssocTy
#[allow(dead_code)]
Regular,
/// _Self::AssocTy
Underscore,
/// <_OrigPtr as __Trait< <generic_params> >>::AssocTy
#[allow(dead_code)]
FullyQualified,
/// AssocTy
NoSelf,
}
/// Whether to include associated types when printing generic parameters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WithAssocTys {
No,
Yes(WhichSelf),
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct ACCOUNTINGPROPERTIES(pub i32);
pub const PROPERTY_ACCOUNTING_LOG_ACCOUNTING: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1026i32);
pub const PROPERTY_ACCOUNTING_LOG_ACCOUNTING_INTERIM: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1027i32);
pub const PROPERTY_ACCOUNTING_LOG_AUTHENTICATION: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1028i32);
pub const PROPERTY_ACCOUNTING_LOG_OPEN_NEW_FREQUENCY: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1029i32);
pub const PROPERTY_ACCOUNTING_LOG_OPEN_NEW_SIZE: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1030i32);
pub const PROPERTY_ACCOUNTING_LOG_FILE_DIRECTORY: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1031i32);
pub const PROPERTY_ACCOUNTING_LOG_IAS1_FORMAT: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1032i32);
pub const PROPERTY_ACCOUNTING_LOG_ENABLE_LOGGING: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1033i32);
pub const PROPERTY_ACCOUNTING_LOG_DELETE_IF_FULL: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1034i32);
pub const PROPERTY_ACCOUNTING_SQL_MAX_SESSIONS: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1035i32);
pub const PROPERTY_ACCOUNTING_LOG_AUTHENTICATION_INTERIM: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1036i32);
pub const PROPERTY_ACCOUNTING_LOG_FILE_IS_BACKUP: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1037i32);
pub const PROPERTY_ACCOUNTING_DISCARD_REQUEST_ON_FAILURE: ACCOUNTINGPROPERTIES = ACCOUNTINGPROPERTIES(1038i32);
impl ::core::convert::From<i32> for ACCOUNTINGPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ACCOUNTINGPROPERTIES {
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 ATTRIBUTEFILTER(pub i32);
pub const ATTRIBUTE_FILTER_NONE: ATTRIBUTEFILTER = ATTRIBUTEFILTER(0i32);
pub const ATTRIBUTE_FILTER_VPN_DIALUP: ATTRIBUTEFILTER = ATTRIBUTEFILTER(1i32);
pub const ATTRIBUTE_FILTER_IEEE_802_1x: ATTRIBUTEFILTER = ATTRIBUTEFILTER(2i32);
impl ::core::convert::From<i32> for ATTRIBUTEFILTER {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ATTRIBUTEFILTER {
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 ATTRIBUTEID(pub u32);
pub const ATTRIBUTE_UNDEFINED: ATTRIBUTEID = ATTRIBUTEID(0u32);
pub const ATTRIBUTE_MIN_VALUE: ATTRIBUTEID = ATTRIBUTEID(1u32);
pub const RADIUS_ATTRIBUTE_USER_NAME: ATTRIBUTEID = ATTRIBUTEID(1u32);
pub const RADIUS_ATTRIBUTE_USER_PASSWORD: ATTRIBUTEID = ATTRIBUTEID(2u32);
pub const RADIUS_ATTRIBUTE_CHAP_PASSWORD: ATTRIBUTEID = ATTRIBUTEID(3u32);
pub const RADIUS_ATTRIBUTE_NAS_IP_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(4u32);
pub const RADIUS_ATTRIBUTE_NAS_PORT: ATTRIBUTEID = ATTRIBUTEID(5u32);
pub const RADIUS_ATTRIBUTE_SERVICE_TYPE: ATTRIBUTEID = ATTRIBUTEID(6u32);
pub const RADIUS_ATTRIBUTE_FRAMED_PROTOCOL: ATTRIBUTEID = ATTRIBUTEID(7u32);
pub const RADIUS_ATTRIBUTE_FRAMED_IP_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(8u32);
pub const RADIUS_ATTRIBUTE_FRAMED_IP_NETMASK: ATTRIBUTEID = ATTRIBUTEID(9u32);
pub const RADIUS_ATTRIBUTE_FRAMED_ROUTING: ATTRIBUTEID = ATTRIBUTEID(10u32);
pub const RADIUS_ATTRIBUTE_FILTER_ID: ATTRIBUTEID = ATTRIBUTEID(11u32);
pub const RADIUS_ATTRIBUTE_FRAMED_MTU: ATTRIBUTEID = ATTRIBUTEID(12u32);
pub const RADIUS_ATTRIBUTE_FRAMED_COMPRESSION: ATTRIBUTEID = ATTRIBUTEID(13u32);
pub const RADIUS_ATTRIBUTE_LOGIN_IP_HOST: ATTRIBUTEID = ATTRIBUTEID(14u32);
pub const RADIUS_ATTRIBUTE_LOGIN_SERVICE: ATTRIBUTEID = ATTRIBUTEID(15u32);
pub const RADIUS_ATTRIBUTE_LOGIN_TCP_PORT: ATTRIBUTEID = ATTRIBUTEID(16u32);
pub const RADIUS_ATTRIBUTE_UNASSIGNED1: ATTRIBUTEID = ATTRIBUTEID(17u32);
pub const RADIUS_ATTRIBUTE_REPLY_MESSAGE: ATTRIBUTEID = ATTRIBUTEID(18u32);
pub const RADIUS_ATTRIBUTE_CALLBACK_NUMBER: ATTRIBUTEID = ATTRIBUTEID(19u32);
pub const RADIUS_ATTRIBUTE_CALLBACK_ID: ATTRIBUTEID = ATTRIBUTEID(20u32);
pub const RADIUS_ATTRIBUTE_UNASSIGNED2: ATTRIBUTEID = ATTRIBUTEID(21u32);
pub const RADIUS_ATTRIBUTE_FRAMED_ROUTE: ATTRIBUTEID = ATTRIBUTEID(22u32);
pub const RADIUS_ATTRIBUTE_FRAMED_IPX_NETWORK: ATTRIBUTEID = ATTRIBUTEID(23u32);
pub const RADIUS_ATTRIBUTE_STATE: ATTRIBUTEID = ATTRIBUTEID(24u32);
pub const RADIUS_ATTRIBUTE_CLASS: ATTRIBUTEID = ATTRIBUTEID(25u32);
pub const RADIUS_ATTRIBUTE_VENDOR_SPECIFIC: ATTRIBUTEID = ATTRIBUTEID(26u32);
pub const RADIUS_ATTRIBUTE_SESSION_TIMEOUT: ATTRIBUTEID = ATTRIBUTEID(27u32);
pub const RADIUS_ATTRIBUTE_IDLE_TIMEOUT: ATTRIBUTEID = ATTRIBUTEID(28u32);
pub const RADIUS_ATTRIBUTE_TERMINATION_ACTION: ATTRIBUTEID = ATTRIBUTEID(29u32);
pub const RADIUS_ATTRIBUTE_CALLED_STATION_ID: ATTRIBUTEID = ATTRIBUTEID(30u32);
pub const RADIUS_ATTRIBUTE_CALLING_STATION_ID: ATTRIBUTEID = ATTRIBUTEID(31u32);
pub const RADIUS_ATTRIBUTE_NAS_IDENTIFIER: ATTRIBUTEID = ATTRIBUTEID(32u32);
pub const RADIUS_ATTRIBUTE_PROXY_STATE: ATTRIBUTEID = ATTRIBUTEID(33u32);
pub const RADIUS_ATTRIBUTE_LOGIN_LAT_SERVICE: ATTRIBUTEID = ATTRIBUTEID(34u32);
pub const RADIUS_ATTRIBUTE_LOGIN_LAT_NODE: ATTRIBUTEID = ATTRIBUTEID(35u32);
pub const RADIUS_ATTRIBUTE_LOGIN_LAT_GROUP: ATTRIBUTEID = ATTRIBUTEID(36u32);
pub const RADIUS_ATTRIBUTE_FRAMED_APPLETALK_LINK: ATTRIBUTEID = ATTRIBUTEID(37u32);
pub const RADIUS_ATTRIBUTE_FRAMED_APPLETALK_NET: ATTRIBUTEID = ATTRIBUTEID(38u32);
pub const RADIUS_ATTRIBUTE_FRAMED_APPLETALK_ZONE: ATTRIBUTEID = ATTRIBUTEID(39u32);
pub const RADIUS_ATTRIBUTE_ACCT_STATUS_TYPE: ATTRIBUTEID = ATTRIBUTEID(40u32);
pub const RADIUS_ATTRIBUTE_ACCT_DELAY_TIME: ATTRIBUTEID = ATTRIBUTEID(41u32);
pub const RADIUS_ATTRIBUTE_ACCT_INPUT_OCTETS: ATTRIBUTEID = ATTRIBUTEID(42u32);
pub const RADIUS_ATTRIBUTE_ACCT_OUTPUT_OCTETS: ATTRIBUTEID = ATTRIBUTEID(43u32);
pub const RADIUS_ATTRIBUTE_ACCT_SESSION_ID: ATTRIBUTEID = ATTRIBUTEID(44u32);
pub const RADIUS_ATTRIBUTE_ACCT_AUTHENTIC: ATTRIBUTEID = ATTRIBUTEID(45u32);
pub const RADIUS_ATTRIBUTE_ACCT_SESSION_TIME: ATTRIBUTEID = ATTRIBUTEID(46u32);
pub const RADIUS_ATTRIBUTE_ACCT_INPUT_PACKETS: ATTRIBUTEID = ATTRIBUTEID(47u32);
pub const RADIUS_ATTRIBUTE_ACCT_OUTPUT_PACKETS: ATTRIBUTEID = ATTRIBUTEID(48u32);
pub const RADIUS_ATTRIBUTE_ACCT_TERMINATE_CAUSE: ATTRIBUTEID = ATTRIBUTEID(49u32);
pub const RADIUS_ATTRIBUTE_ACCT_MULTI_SSN_ID: ATTRIBUTEID = ATTRIBUTEID(50u32);
pub const RADIUS_ATTRIBUTE_ACCT_LINK_COUNT: ATTRIBUTEID = ATTRIBUTEID(51u32);
pub const RADIUS_ATTRIBUTE_CHAP_CHALLENGE: ATTRIBUTEID = ATTRIBUTEID(60u32);
pub const RADIUS_ATTRIBUTE_NAS_PORT_TYPE: ATTRIBUTEID = ATTRIBUTEID(61u32);
pub const RADIUS_ATTRIBUTE_PORT_LIMIT: ATTRIBUTEID = ATTRIBUTEID(62u32);
pub const RADIUS_ATTRIBUTE_LOGIN_LAT_PORT: ATTRIBUTEID = ATTRIBUTEID(63u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_TYPE: ATTRIBUTEID = ATTRIBUTEID(64u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_MEDIUM_TYPE: ATTRIBUTEID = ATTRIBUTEID(65u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_CLIENT_ENDPT: ATTRIBUTEID = ATTRIBUTEID(66u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_SERVER_ENDPT: ATTRIBUTEID = ATTRIBUTEID(67u32);
pub const RADIUS_ATTRIBUTE_ACCT_TUNNEL_CONN: ATTRIBUTEID = ATTRIBUTEID(68u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_PASSWORD: ATTRIBUTEID = ATTRIBUTEID(69u32);
pub const RADIUS_ATTRIBUTE_ARAP_PASSWORD: ATTRIBUTEID = ATTRIBUTEID(70u32);
pub const RADIUS_ATTRIBUTE_ARAP_FEATURES: ATTRIBUTEID = ATTRIBUTEID(71u32);
pub const RADIUS_ATTRIBUTE_ARAP_ZONE_ACCESS: ATTRIBUTEID = ATTRIBUTEID(72u32);
pub const RADIUS_ATTRIBUTE_ARAP_SECURITY: ATTRIBUTEID = ATTRIBUTEID(73u32);
pub const RADIUS_ATTRIBUTE_ARAP_SECURITY_DATA: ATTRIBUTEID = ATTRIBUTEID(74u32);
pub const RADIUS_ATTRIBUTE_PASSWORD_RETRY: ATTRIBUTEID = ATTRIBUTEID(75u32);
pub const RADIUS_ATTRIBUTE_PROMPT: ATTRIBUTEID = ATTRIBUTEID(76u32);
pub const RADIUS_ATTRIBUTE_CONNECT_INFO: ATTRIBUTEID = ATTRIBUTEID(77u32);
pub const RADIUS_ATTRIBUTE_CONFIGURATION_TOKEN: ATTRIBUTEID = ATTRIBUTEID(78u32);
pub const RADIUS_ATTRIBUTE_EAP_MESSAGE: ATTRIBUTEID = ATTRIBUTEID(79u32);
pub const RADIUS_ATTRIBUTE_SIGNATURE: ATTRIBUTEID = ATTRIBUTEID(80u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_PVT_GROUP_ID: ATTRIBUTEID = ATTRIBUTEID(81u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_ASSIGNMENT_ID: ATTRIBUTEID = ATTRIBUTEID(82u32);
pub const RADIUS_ATTRIBUTE_TUNNEL_PREFERENCE: ATTRIBUTEID = ATTRIBUTEID(83u32);
pub const RADIUS_ATTRIBUTE_ARAP_CHALLENGE_RESPONSE: ATTRIBUTEID = ATTRIBUTEID(84u32);
pub const RADIUS_ATTRIBUTE_ACCT_INTERIM_INTERVAL: ATTRIBUTEID = ATTRIBUTEID(85u32);
pub const RADIUS_ATTRIBUTE_NAS_IPv6_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(95u32);
pub const RADIUS_ATTRIBUTE_FRAMED_INTERFACE_ID: ATTRIBUTEID = ATTRIBUTEID(96u32);
pub const RADIUS_ATTRIBUTE_FRAMED_IPv6_PREFIX: ATTRIBUTEID = ATTRIBUTEID(97u32);
pub const RADIUS_ATTRIBUTE_LOGIN_IPv6_HOST: ATTRIBUTEID = ATTRIBUTEID(98u32);
pub const RADIUS_ATTRIBUTE_FRAMED_IPv6_ROUTE: ATTRIBUTEID = ATTRIBUTEID(99u32);
pub const RADIUS_ATTRIBUTE_FRAMED_IPv6_POOL: ATTRIBUTEID = ATTRIBUTEID(100u32);
pub const IAS_ATTRIBUTE_SAVED_RADIUS_FRAMED_IP_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(4096u32);
pub const IAS_ATTRIBUTE_SAVED_RADIUS_CALLBACK_NUMBER: ATTRIBUTEID = ATTRIBUTEID(4097u32);
pub const IAS_ATTRIBUTE_NP_CALLING_STATION_ID: ATTRIBUTEID = ATTRIBUTEID(4098u32);
pub const IAS_ATTRIBUTE_SAVED_NP_CALLING_STATION_ID: ATTRIBUTEID = ATTRIBUTEID(4099u32);
pub const IAS_ATTRIBUTE_SAVED_RADIUS_FRAMED_ROUTE: ATTRIBUTEID = ATTRIBUTEID(4100u32);
pub const IAS_ATTRIBUTE_IGNORE_USER_DIALIN_PROPERTIES: ATTRIBUTEID = ATTRIBUTEID(4101u32);
pub const IAS_ATTRIBUTE_NP_TIME_OF_DAY: ATTRIBUTEID = ATTRIBUTEID(4102u32);
pub const IAS_ATTRIBUTE_NP_CALLED_STATION_ID: ATTRIBUTEID = ATTRIBUTEID(4103u32);
pub const IAS_ATTRIBUTE_NP_ALLOWED_PORT_TYPES: ATTRIBUTEID = ATTRIBUTEID(4104u32);
pub const IAS_ATTRIBUTE_NP_AUTHENTICATION_TYPE: ATTRIBUTEID = ATTRIBUTEID(4105u32);
pub const IAS_ATTRIBUTE_NP_ALLOWED_EAP_TYPE: ATTRIBUTEID = ATTRIBUTEID(4106u32);
pub const IAS_ATTRIBUTE_SHARED_SECRET: ATTRIBUTEID = ATTRIBUTEID(4107u32);
pub const IAS_ATTRIBUTE_CLIENT_IP_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(4108u32);
pub const IAS_ATTRIBUTE_CLIENT_PACKET_HEADER: ATTRIBUTEID = ATTRIBUTEID(4109u32);
pub const IAS_ATTRIBUTE_TOKEN_GROUPS: ATTRIBUTEID = ATTRIBUTEID(4110u32);
pub const IAS_ATTRIBUTE_ALLOW_DIALIN: ATTRIBUTEID = ATTRIBUTEID(4111u32);
pub const IAS_ATTRIBUTE_REQUEST_ID: ATTRIBUTEID = ATTRIBUTEID(4112u32);
pub const IAS_ATTRIBUTE_MANIPULATION_TARGET: ATTRIBUTEID = ATTRIBUTEID(4113u32);
pub const IAS_ATTRIBUTE_MANIPULATION_RULE: ATTRIBUTEID = ATTRIBUTEID(4114u32);
pub const IAS_ATTRIBUTE_ORIGINAL_USER_NAME: ATTRIBUTEID = ATTRIBUTEID(4115u32);
pub const IAS_ATTRIBUTE_CLIENT_VENDOR_TYPE: ATTRIBUTEID = ATTRIBUTEID(4116u32);
pub const IAS_ATTRIBUTE_CLIENT_UDP_PORT: ATTRIBUTEID = ATTRIBUTEID(4117u32);
pub const MS_ATTRIBUTE_CHAP_CHALLENGE: ATTRIBUTEID = ATTRIBUTEID(4118u32);
pub const MS_ATTRIBUTE_CHAP_RESPONSE: ATTRIBUTEID = ATTRIBUTEID(4119u32);
pub const MS_ATTRIBUTE_CHAP_DOMAIN: ATTRIBUTEID = ATTRIBUTEID(4120u32);
pub const MS_ATTRIBUTE_CHAP_ERROR: ATTRIBUTEID = ATTRIBUTEID(4121u32);
pub const MS_ATTRIBUTE_CHAP_CPW1: ATTRIBUTEID = ATTRIBUTEID(4122u32);
pub const MS_ATTRIBUTE_CHAP_CPW2: ATTRIBUTEID = ATTRIBUTEID(4123u32);
pub const MS_ATTRIBUTE_CHAP_LM_ENC_PW: ATTRIBUTEID = ATTRIBUTEID(4124u32);
pub const MS_ATTRIBUTE_CHAP_NT_ENC_PW: ATTRIBUTEID = ATTRIBUTEID(4125u32);
pub const MS_ATTRIBUTE_CHAP_MPPE_KEYS: ATTRIBUTEID = ATTRIBUTEID(4126u32);
pub const IAS_ATTRIBUTE_AUTHENTICATION_TYPE: ATTRIBUTEID = ATTRIBUTEID(4127u32);
pub const IAS_ATTRIBUTE_CLIENT_NAME: ATTRIBUTEID = ATTRIBUTEID(4128u32);
pub const IAS_ATTRIBUTE_NT4_ACCOUNT_NAME: ATTRIBUTEID = ATTRIBUTEID(4129u32);
pub const IAS_ATTRIBUTE_FULLY_QUALIFIED_USER_NAME: ATTRIBUTEID = ATTRIBUTEID(4130u32);
pub const IAS_ATTRIBUTE_NTGROUPS: ATTRIBUTEID = ATTRIBUTEID(4131u32);
pub const IAS_ATTRIBUTE_EAP_FRIENDLY_NAME: ATTRIBUTEID = ATTRIBUTEID(4132u32);
pub const IAS_ATTRIBUTE_AUTH_PROVIDER_TYPE: ATTRIBUTEID = ATTRIBUTEID(4133u32);
pub const MS_ATTRIBUTE_ACCT_AUTH_TYPE: ATTRIBUTEID = ATTRIBUTEID(4134u32);
pub const MS_ATTRIBUTE_ACCT_EAP_TYPE: ATTRIBUTEID = ATTRIBUTEID(4135u32);
pub const IAS_ATTRIBUTE_PACKET_TYPE: ATTRIBUTEID = ATTRIBUTEID(4136u32);
pub const IAS_ATTRIBUTE_AUTH_PROVIDER_NAME: ATTRIBUTEID = ATTRIBUTEID(4137u32);
pub const IAS_ATTRIBUTE_ACCT_PROVIDER_TYPE: ATTRIBUTEID = ATTRIBUTEID(4138u32);
pub const IAS_ATTRIBUTE_ACCT_PROVIDER_NAME: ATTRIBUTEID = ATTRIBUTEID(4139u32);
pub const MS_ATTRIBUTE_MPPE_SEND_KEY: ATTRIBUTEID = ATTRIBUTEID(4140u32);
pub const MS_ATTRIBUTE_MPPE_RECV_KEY: ATTRIBUTEID = ATTRIBUTEID(4141u32);
pub const IAS_ATTRIBUTE_REASON_CODE: ATTRIBUTEID = ATTRIBUTEID(4142u32);
pub const MS_ATTRIBUTE_FILTER: ATTRIBUTEID = ATTRIBUTEID(4143u32);
pub const MS_ATTRIBUTE_CHAP2_RESPONSE: ATTRIBUTEID = ATTRIBUTEID(4144u32);
pub const MS_ATTRIBUTE_CHAP2_SUCCESS: ATTRIBUTEID = ATTRIBUTEID(4145u32);
pub const MS_ATTRIBUTE_CHAP2_CPW: ATTRIBUTEID = ATTRIBUTEID(4146u32);
pub const MS_ATTRIBUTE_RAS_VENDOR: ATTRIBUTEID = ATTRIBUTEID(4147u32);
pub const MS_ATTRIBUTE_RAS_VERSION: ATTRIBUTEID = ATTRIBUTEID(4148u32);
pub const IAS_ATTRIBUTE_NP_NAME: ATTRIBUTEID = ATTRIBUTEID(4149u32);
pub const MS_ATTRIBUTE_PRIMARY_DNS_SERVER: ATTRIBUTEID = ATTRIBUTEID(4150u32);
pub const MS_ATTRIBUTE_SECONDARY_DNS_SERVER: ATTRIBUTEID = ATTRIBUTEID(4151u32);
pub const MS_ATTRIBUTE_PRIMARY_NBNS_SERVER: ATTRIBUTEID = ATTRIBUTEID(4152u32);
pub const MS_ATTRIBUTE_SECONDARY_NBNS_SERVER: ATTRIBUTEID = ATTRIBUTEID(4153u32);
pub const IAS_ATTRIBUTE_PROXY_POLICY_NAME: ATTRIBUTEID = ATTRIBUTEID(4154u32);
pub const IAS_ATTRIBUTE_PROVIDER_TYPE: ATTRIBUTEID = ATTRIBUTEID(4155u32);
pub const IAS_ATTRIBUTE_PROVIDER_NAME: ATTRIBUTEID = ATTRIBUTEID(4156u32);
pub const IAS_ATTRIBUTE_REMOTE_SERVER_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(4157u32);
pub const IAS_ATTRIBUTE_GENERATE_CLASS_ATTRIBUTE: ATTRIBUTEID = ATTRIBUTEID(4158u32);
pub const MS_ATTRIBUTE_RAS_CLIENT_NAME: ATTRIBUTEID = ATTRIBUTEID(4159u32);
pub const MS_ATTRIBUTE_RAS_CLIENT_VERSION: ATTRIBUTEID = ATTRIBUTEID(4160u32);
pub const IAS_ATTRIBUTE_ALLOWED_CERTIFICATE_EKU: ATTRIBUTEID = ATTRIBUTEID(4161u32);
pub const IAS_ATTRIBUTE_EXTENSION_STATE: ATTRIBUTEID = ATTRIBUTEID(4162u32);
pub const IAS_ATTRIBUTE_GENERATE_SESSION_TIMEOUT: ATTRIBUTEID = ATTRIBUTEID(4163u32);
pub const IAS_ATTRIBUTE_SESSION_TIMEOUT: ATTRIBUTEID = ATTRIBUTEID(4164u32);
pub const MS_ATTRIBUTE_QUARANTINE_IPFILTER: ATTRIBUTEID = ATTRIBUTEID(4165u32);
pub const MS_ATTRIBUTE_QUARANTINE_SESSION_TIMEOUT: ATTRIBUTEID = ATTRIBUTEID(4166u32);
pub const MS_ATTRIBUTE_USER_SECURITY_IDENTITY: ATTRIBUTEID = ATTRIBUTEID(4167u32);
pub const IAS_ATTRIBUTE_REMOTE_RADIUS_TO_WINDOWS_USER_MAPPING: ATTRIBUTEID = ATTRIBUTEID(4168u32);
pub const IAS_ATTRIBUTE_PASSPORT_USER_MAPPING_UPN_SUFFIX: ATTRIBUTEID = ATTRIBUTEID(4169u32);
pub const IAS_ATTRIBUTE_TUNNEL_TAG: ATTRIBUTEID = ATTRIBUTEID(4170u32);
pub const IAS_ATTRIBUTE_NP_PEAPUPFRONT_ENABLED: ATTRIBUTEID = ATTRIBUTEID(4171u32);
pub const IAS_ATTRIBUTE_CERTIFICATE_EKU: ATTRIBUTEID = ATTRIBUTEID(8097u32);
pub const IAS_ATTRIBUTE_EAP_CONFIG: ATTRIBUTEID = ATTRIBUTEID(8098u32);
pub const IAS_ATTRIBUTE_PEAP_EMBEDDED_EAP_TYPEID: ATTRIBUTEID = ATTRIBUTEID(8099u32);
pub const IAS_ATTRIBUTE_PEAP_FAST_ROAMED_SESSION: ATTRIBUTEID = ATTRIBUTEID(8100u32);
pub const IAS_ATTRIBUTE_EAP_TYPEID: ATTRIBUTEID = ATTRIBUTEID(8101u32);
pub const MS_ATTRIBUTE_EAP_TLV: ATTRIBUTEID = ATTRIBUTEID(8102u32);
pub const IAS_ATTRIBUTE_REJECT_REASON_CODE: ATTRIBUTEID = ATTRIBUTEID(8103u32);
pub const IAS_ATTRIBUTE_PROXY_EAP_CONFIG: ATTRIBUTEID = ATTRIBUTEID(8104u32);
pub const IAS_ATTRIBUTE_EAP_SESSION: ATTRIBUTEID = ATTRIBUTEID(8105u32);
pub const IAS_ATTRIBUTE_IS_REPLAY: ATTRIBUTEID = ATTRIBUTEID(8106u32);
pub const IAS_ATTRIBUTE_CLEAR_TEXT_PASSWORD: ATTRIBUTEID = ATTRIBUTEID(8107u32);
pub const MS_ATTRIBUTE_IDENTITY_TYPE: ATTRIBUTEID = ATTRIBUTEID(8108u32);
pub const MS_ATTRIBUTE_SERVICE_CLASS: ATTRIBUTEID = ATTRIBUTEID(8109u32);
pub const MS_ATTRIBUTE_QUARANTINE_USER_CLASS: ATTRIBUTEID = ATTRIBUTEID(8110u32);
pub const MS_ATTRIBUTE_QUARANTINE_STATE: ATTRIBUTEID = ATTRIBUTEID(8111u32);
pub const IAS_ATTRIBUTE_OVERRIDE_RAP_AUTH: ATTRIBUTEID = ATTRIBUTEID(8112u32);
pub const IAS_ATTRIBUTE_PEAP_CHANNEL_UP: ATTRIBUTEID = ATTRIBUTEID(8113u32);
pub const IAS_ATTRIBUTE_NAME_MAPPED: ATTRIBUTEID = ATTRIBUTEID(8114u32);
pub const IAS_ATTRIBUTE_POLICY_ENFORCED: ATTRIBUTEID = ATTRIBUTEID(8115u32);
pub const IAS_ATTRIBUTE_MACHINE_NTGROUPS: ATTRIBUTEID = ATTRIBUTEID(8116u32);
pub const IAS_ATTRIBUTE_USER_NTGROUPS: ATTRIBUTEID = ATTRIBUTEID(8117u32);
pub const IAS_ATTRIBUTE_MACHINE_TOKEN_GROUPS: ATTRIBUTEID = ATTRIBUTEID(8118u32);
pub const IAS_ATTRIBUTE_USER_TOKEN_GROUPS: ATTRIBUTEID = ATTRIBUTEID(8119u32);
pub const MS_ATTRIBUTE_QUARANTINE_GRACE_TIME: ATTRIBUTEID = ATTRIBUTEID(8120u32);
pub const IAS_ATTRIBUTE_QUARANTINE_URL: ATTRIBUTEID = ATTRIBUTEID(8121u32);
pub const IAS_ATTRIBUTE_QUARANTINE_FIXUP_SERVERS: ATTRIBUTEID = ATTRIBUTEID(8122u32);
pub const MS_ATTRIBUTE_NOT_QUARANTINE_CAPABLE: ATTRIBUTEID = ATTRIBUTEID(8123u32);
pub const IAS_ATTRIBUTE_QUARANTINE_SYSTEM_HEALTH_RESULT: ATTRIBUTEID = ATTRIBUTEID(8124u32);
pub const IAS_ATTRIBUTE_QUARANTINE_SYSTEM_HEALTH_VALIDATORS: ATTRIBUTEID = ATTRIBUTEID(8125u32);
pub const IAS_ATTRIBUTE_MACHINE_NAME: ATTRIBUTEID = ATTRIBUTEID(8126u32);
pub const IAS_ATTRIBUTE_NT4_MACHINE_NAME: ATTRIBUTEID = ATTRIBUTEID(8127u32);
pub const IAS_ATTRIBUTE_QUARANTINE_SESSION_HANDLE: ATTRIBUTEID = ATTRIBUTEID(8128u32);
pub const IAS_ATTRIBUTE_FULLY_QUALIFIED_MACHINE_NAME: ATTRIBUTEID = ATTRIBUTEID(8129u32);
pub const IAS_ATTRIBUTE_QUARANTINE_FIXUP_SERVERS_CONFIGURATION: ATTRIBUTEID = ATTRIBUTEID(8130u32);
pub const IAS_ATTRIBUTE_CLIENT_QUARANTINE_COMPATIBLE: ATTRIBUTEID = ATTRIBUTEID(8131u32);
pub const MS_ATTRIBUTE_NETWORK_ACCESS_SERVER_TYPE: ATTRIBUTEID = ATTRIBUTEID(8132u32);
pub const IAS_ATTRIBUTE_QUARANTINE_SESSION_ID: ATTRIBUTEID = ATTRIBUTEID(8133u32);
pub const MS_ATTRIBUTE_AFW_QUARANTINE_ZONE: ATTRIBUTEID = ATTRIBUTEID(8134u32);
pub const MS_ATTRIBUTE_AFW_PROTECTION_LEVEL: ATTRIBUTEID = ATTRIBUTEID(8135u32);
pub const IAS_ATTRIBUTE_QUARANTINE_UPDATE_NON_COMPLIANT: ATTRIBUTEID = ATTRIBUTEID(8136u32);
pub const IAS_ATTRIBUTE_REQUEST_START_TIME: ATTRIBUTEID = ATTRIBUTEID(8137u32);
pub const MS_ATTRIBUTE_MACHINE_NAME: ATTRIBUTEID = ATTRIBUTEID(8138u32);
pub const IAS_ATTRIBUTE_CLIENT_IPv6_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(8139u32);
pub const IAS_ATTRIBUTE_SAVED_RADIUS_FRAMED_INTERFACE_ID: ATTRIBUTEID = ATTRIBUTEID(8140u32);
pub const IAS_ATTRIBUTE_SAVED_RADIUS_FRAMED_IPv6_PREFIX: ATTRIBUTEID = ATTRIBUTEID(8141u32);
pub const IAS_ATTRIBUTE_SAVED_RADIUS_FRAMED_IPv6_ROUTE: ATTRIBUTEID = ATTRIBUTEID(8142u32);
pub const MS_ATTRIBUTE_QUARANTINE_GRACE_TIME_CONFIGURATION: ATTRIBUTEID = ATTRIBUTEID(8143u32);
pub const MS_ATTRIBUTE_IPv6_FILTER: ATTRIBUTEID = ATTRIBUTEID(8144u32);
pub const MS_ATTRIBUTE_IPV4_REMEDIATION_SERVERS: ATTRIBUTEID = ATTRIBUTEID(8145u32);
pub const MS_ATTRIBUTE_IPV6_REMEDIATION_SERVERS: ATTRIBUTEID = ATTRIBUTEID(8146u32);
pub const IAS_ATTRIBUTE_PROXY_RETRY_COUNT: ATTRIBUTEID = ATTRIBUTEID(8147u32);
pub const IAS_ATTRIBUTE_MACHINE_INVENTORY: ATTRIBUTEID = ATTRIBUTEID(8148u32);
pub const IAS_ATTRIBUTE_ABSOLUTE_TIME: ATTRIBUTEID = ATTRIBUTEID(8149u32);
pub const MS_ATTRIBUTE_QUARANTINE_SOH: ATTRIBUTEID = ATTRIBUTEID(8150u32);
pub const IAS_ATTRIBUTE_EAP_TYPES_CONFIGURED_IN_PROXYPOLICY: ATTRIBUTEID = ATTRIBUTEID(8151u32);
pub const MS_ATTRIBUTE_HCAP_LOCATION_GROUP_NAME: ATTRIBUTEID = ATTRIBUTEID(8152u32);
pub const MS_ATTRIBUTE_EXTENDED_QUARANTINE_STATE: ATTRIBUTEID = ATTRIBUTEID(8153u32);
pub const IAS_ATTRIBUTE_SOH_CARRIER_EAPTLV: ATTRIBUTEID = ATTRIBUTEID(8154u32);
pub const MS_ATTRIBUTE_HCAP_USER_GROUPS: ATTRIBUTEID = ATTRIBUTEID(8155u32);
pub const IAS_ATTRIBUTE_SAVED_MACHINE_HEALTHCHECK_ONLY: ATTRIBUTEID = ATTRIBUTEID(8156u32);
pub const IAS_ATTRIBUTE_POLICY_EVALUATED_SHV: ATTRIBUTEID = ATTRIBUTEID(8157u32);
pub const MS_ATTRIBUTE_RAS_CORRELATION_ID: ATTRIBUTEID = ATTRIBUTEID(8158u32);
pub const MS_ATTRIBUTE_HCAP_USER_NAME: ATTRIBUTEID = ATTRIBUTEID(8159u32);
pub const IAS_ATTRIBUTE_NT4_HCAP_ACCOUNT_NAME: ATTRIBUTEID = ATTRIBUTEID(8160u32);
pub const IAS_ATTRIBUTE_USER_TOKEN_SID: ATTRIBUTEID = ATTRIBUTEID(8161u32);
pub const IAS_ATTRIBUTE_MACHINE_TOKEN_SID: ATTRIBUTEID = ATTRIBUTEID(8162u32);
pub const IAS_ATTRIBUTE_MACHINE_VALIDATED: ATTRIBUTEID = ATTRIBUTEID(8163u32);
pub const MS_ATTRIBUTE_USER_IPv4_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(8164u32);
pub const MS_ATTRIBUTE_USER_IPv6_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(8165u32);
pub const MS_ATTRIBUTE_TSG_DEVICE_REDIRECTION: ATTRIBUTEID = ATTRIBUTEID(8166u32);
pub const IAS_ATTRIBUTE_ACCEPT_REASON_CODE: ATTRIBUTEID = ATTRIBUTEID(8167u32);
pub const IAS_ATTRIBUTE_LOGGING_RESULT: ATTRIBUTEID = ATTRIBUTEID(8168u32);
pub const IAS_ATTRIBUTE_SERVER_IP_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(8169u32);
pub const IAS_ATTRIBUTE_SERVER_IPv6_ADDRESS: ATTRIBUTEID = ATTRIBUTEID(8170u32);
pub const IAS_ATTRIBUTE_RADIUS_USERNAME_ENCODING_ASCII: ATTRIBUTEID = ATTRIBUTEID(8171u32);
pub const MS_ATTRIBUTE_RAS_ROUTING_DOMAIN_ID: ATTRIBUTEID = ATTRIBUTEID(8172u32);
pub const IAS_ATTRIBUTE_CERTIFICATE_THUMBPRINT: ATTRIBUTEID = ATTRIBUTEID(8250u32);
pub const RAS_ATTRIBUTE_ENCRYPTION_TYPE: ATTRIBUTEID = ATTRIBUTEID(4294967206u32);
pub const RAS_ATTRIBUTE_ENCRYPTION_POLICY: ATTRIBUTEID = ATTRIBUTEID(4294967207u32);
pub const RAS_ATTRIBUTE_BAP_REQUIRED: ATTRIBUTEID = ATTRIBUTEID(4294967208u32);
pub const RAS_ATTRIBUTE_BAP_LINE_DOWN_TIME: ATTRIBUTEID = ATTRIBUTEID(4294967209u32);
pub const RAS_ATTRIBUTE_BAP_LINE_DOWN_LIMIT: ATTRIBUTEID = ATTRIBUTEID(4294967210u32);
impl ::core::convert::From<u32> for ATTRIBUTEID {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ATTRIBUTEID {
type Abi = Self;
}
impl ::core::ops::BitOr for ATTRIBUTEID {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for ATTRIBUTEID {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for ATTRIBUTEID {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for ATTRIBUTEID {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for ATTRIBUTEID {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct ATTRIBUTEINFO(pub i32);
pub const NAME: ATTRIBUTEINFO = ATTRIBUTEINFO(1i32);
pub const SYNTAX: ATTRIBUTEINFO = ATTRIBUTEINFO(2i32);
pub const RESTRICTIONS: ATTRIBUTEINFO = ATTRIBUTEINFO(3i32);
pub const DESCRIPTION: ATTRIBUTEINFO = ATTRIBUTEINFO(4i32);
pub const VENDORID: ATTRIBUTEINFO = ATTRIBUTEINFO(5i32);
pub const LDAPNAME: ATTRIBUTEINFO = ATTRIBUTEINFO(6i32);
pub const VENDORTYPE: ATTRIBUTEINFO = ATTRIBUTEINFO(7i32);
impl ::core::convert::From<i32> for ATTRIBUTEINFO {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ATTRIBUTEINFO {
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 ATTRIBUTEPROPERTIES(pub i32);
pub const PROPERTY_ATTRIBUTE_ID: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1024i32);
pub const PROPERTY_ATTRIBUTE_VENDOR_ID: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1025i32);
pub const PROPERTY_ATTRIBUTE_VENDOR_TYPE_ID: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1026i32);
pub const PROPERTY_ATTRIBUTE_IS_ENUMERABLE: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1027i32);
pub const PROPERTY_ATTRIBUTE_ENUM_NAMES: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1028i32);
pub const PROPERTY_ATTRIBUTE_ENUM_VALUES: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1029i32);
pub const PROPERTY_ATTRIBUTE_SYNTAX: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1030i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_MULTIPLE: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1031i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_LOG_ORDINAL: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1032i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_IN_PROFILE: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1033i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_IN_CONDITION: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1034i32);
pub const PROPERTY_ATTRIBUTE_DISPLAY_NAME: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1035i32);
pub const PROPERTY_ATTRIBUTE_VALUE: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1036i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_IN_PROXY_PROFILE: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1037i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_IN_PROXY_CONDITION: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1038i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_IN_VPNDIALUP: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1039i32);
pub const PROPERTY_ATTRIBUTE_ALLOW_IN_8021X: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1040i32);
pub const PROPERTY_ATTRIBUTE_ENUM_FILTERS: ATTRIBUTEPROPERTIES = ATTRIBUTEPROPERTIES(1041i32);
impl ::core::convert::From<i32> for ATTRIBUTEPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ATTRIBUTEPROPERTIES {
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 ATTRIBUTERESTRICTIONS(pub i32);
pub const MULTIVALUED: ATTRIBUTERESTRICTIONS = ATTRIBUTERESTRICTIONS(1i32);
pub const ALLOWEDINPROFILE: ATTRIBUTERESTRICTIONS = ATTRIBUTERESTRICTIONS(2i32);
pub const ALLOWEDINCONDITION: ATTRIBUTERESTRICTIONS = ATTRIBUTERESTRICTIONS(4i32);
pub const ALLOWEDINPROXYPROFILE: ATTRIBUTERESTRICTIONS = ATTRIBUTERESTRICTIONS(8i32);
pub const ALLOWEDINPROXYCONDITION: ATTRIBUTERESTRICTIONS = ATTRIBUTERESTRICTIONS(16i32);
pub const ALLOWEDINVPNDIALUP: ATTRIBUTERESTRICTIONS = ATTRIBUTERESTRICTIONS(32i32);
pub const ALLOWEDIN8021X: ATTRIBUTERESTRICTIONS = ATTRIBUTERESTRICTIONS(64i32);
impl ::core::convert::From<i32> for ATTRIBUTERESTRICTIONS {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ATTRIBUTERESTRICTIONS {
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 ATTRIBUTESYNTAX(pub i32);
pub const IAS_SYNTAX_BOOLEAN: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(1i32);
pub const IAS_SYNTAX_INTEGER: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(2i32);
pub const IAS_SYNTAX_ENUMERATOR: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(3i32);
pub const IAS_SYNTAX_INETADDR: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(4i32);
pub const IAS_SYNTAX_STRING: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(5i32);
pub const IAS_SYNTAX_OCTETSTRING: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(6i32);
pub const IAS_SYNTAX_UTCTIME: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(7i32);
pub const IAS_SYNTAX_PROVIDERSPECIFIC: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(8i32);
pub const IAS_SYNTAX_UNSIGNEDINTEGER: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(9i32);
pub const IAS_SYNTAX_INETADDR6: ATTRIBUTESYNTAX = ATTRIBUTESYNTAX(10i32);
impl ::core::convert::From<i32> for ATTRIBUTESYNTAX {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ATTRIBUTESYNTAX {
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 AUTHENTICATION_TYPE(pub i32);
pub const IAS_AUTH_INVALID: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(0i32);
pub const IAS_AUTH_PAP: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(1i32);
pub const IAS_AUTH_MD5CHAP: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(2i32);
pub const IAS_AUTH_MSCHAP: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(3i32);
pub const IAS_AUTH_MSCHAP2: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(4i32);
pub const IAS_AUTH_EAP: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(5i32);
pub const IAS_AUTH_ARAP: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(6i32);
pub const IAS_AUTH_NONE: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(7i32);
pub const IAS_AUTH_CUSTOM: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(8i32);
pub const IAS_AUTH_MSCHAP_CPW: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(9i32);
pub const IAS_AUTH_MSCHAP2_CPW: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(10i32);
pub const IAS_AUTH_PEAP: AUTHENTICATION_TYPE = AUTHENTICATION_TYPE(11i32);
impl ::core::convert::From<i32> for AUTHENTICATION_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AUTHENTICATION_TYPE {
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 CLIENTPROPERTIES(pub i32);
pub const PROPERTY_CLIENT_REQUIRE_SIGNATURE: CLIENTPROPERTIES = CLIENTPROPERTIES(1024i32);
pub const PROPERTY_CLIENT_UNUSED: CLIENTPROPERTIES = CLIENTPROPERTIES(1025i32);
pub const PROPERTY_CLIENT_SHARED_SECRET: CLIENTPROPERTIES = CLIENTPROPERTIES(1026i32);
pub const PROPERTY_CLIENT_NAS_MANUFACTURER: CLIENTPROPERTIES = CLIENTPROPERTIES(1027i32);
pub const PROPERTY_CLIENT_ADDRESS: CLIENTPROPERTIES = CLIENTPROPERTIES(1028i32);
pub const PROPERTY_CLIENT_QUARANTINE_COMPATIBLE: CLIENTPROPERTIES = CLIENTPROPERTIES(1029i32);
pub const PROPERTY_CLIENT_ENABLED: CLIENTPROPERTIES = CLIENTPROPERTIES(1030i32);
pub const PROPERTY_CLIENT_SECRET_TEMPLATE_GUID: CLIENTPROPERTIES = CLIENTPROPERTIES(1031i32);
impl ::core::convert::From<i32> for CLIENTPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for CLIENTPROPERTIES {
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 CONDITIONPROPERTIES(pub i32);
pub const PROPERTY_CONDITION_TEXT: CONDITIONPROPERTIES = CONDITIONPROPERTIES(1024i32);
impl ::core::convert::From<i32> for CONDITIONPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for CONDITIONPROPERTIES {
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 DICTIONARYPROPERTIES(pub i32);
pub const PROPERTY_DICTIONARY_ATTRIBUTES_COLLECTION: DICTIONARYPROPERTIES = DICTIONARYPROPERTIES(1024i32);
pub const PROPERTY_DICTIONARY_LOCATION: DICTIONARYPROPERTIES = DICTIONARYPROPERTIES(1025i32);
impl ::core::convert::From<i32> for DICTIONARYPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DICTIONARYPROPERTIES {
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 IASCOMMONPROPERTIES(pub i32);
pub const PROPERTY_SDO_RESERVED: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(0i32);
pub const PROPERTY_SDO_CLASS: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(1i32);
pub const PROPERTY_SDO_NAME: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(2i32);
pub const PROPERTY_SDO_DESCRIPTION: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(3i32);
pub const PROPERTY_SDO_ID: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(4i32);
pub const PROPERTY_SDO_DATASTORE_NAME: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(5i32);
pub const PROPERTY_SDO_TEMPLATE_GUID: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(6i32);
pub const PROPERTY_SDO_OPAQUE: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(7i32);
pub const PROPERTY_SDO_START: IASCOMMONPROPERTIES = IASCOMMONPROPERTIES(1024i32);
impl ::core::convert::From<i32> for IASCOMMONPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IASCOMMONPROPERTIES {
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 IASCOMPONENTPROPERTIES(pub i32);
pub const PROPERTY_COMPONENT_ID: IASCOMPONENTPROPERTIES = IASCOMPONENTPROPERTIES(1024i32);
pub const PROPERTY_COMPONENT_PROG_ID: IASCOMPONENTPROPERTIES = IASCOMPONENTPROPERTIES(1025i32);
pub const PROPERTY_COMPONENT_START: IASCOMPONENTPROPERTIES = IASCOMPONENTPROPERTIES(1026i32);
impl ::core::convert::From<i32> for IASCOMPONENTPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IASCOMPONENTPROPERTIES {
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 IASDATASTORE(pub i32);
pub const DATA_STORE_LOCAL: IASDATASTORE = IASDATASTORE(0i32);
pub const DATA_STORE_DIRECTORY: IASDATASTORE = IASDATASTORE(1i32);
impl ::core::convert::From<i32> for IASDATASTORE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IASDATASTORE {
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 IASDOMAINTYPE(pub i32);
pub const DOMAIN_TYPE_NONE: IASDOMAINTYPE = IASDOMAINTYPE(0i32);
pub const DOMAIN_TYPE_NT4: IASDOMAINTYPE = IASDOMAINTYPE(1i32);
pub const DOMAIN_TYPE_NT5: IASDOMAINTYPE = IASDOMAINTYPE(2i32);
pub const DOMAIN_TYPE_MIXED: IASDOMAINTYPE = IASDOMAINTYPE(3i32);
impl ::core::convert::From<i32> for IASDOMAINTYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IASDOMAINTYPE {
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 IASOSTYPE(pub i32);
pub const SYSTEM_TYPE_NT4_WORKSTATION: IASOSTYPE = IASOSTYPE(0i32);
pub const SYSTEM_TYPE_NT5_WORKSTATION: IASOSTYPE = IASOSTYPE(1i32);
pub const SYSTEM_TYPE_NT6_WORKSTATION: IASOSTYPE = IASOSTYPE(2i32);
pub const SYSTEM_TYPE_NT6_1_WORKSTATION: IASOSTYPE = IASOSTYPE(3i32);
pub const SYSTEM_TYPE_NT6_2_WORKSTATION: IASOSTYPE = IASOSTYPE(4i32);
pub const SYSTEM_TYPE_NT6_3_WORKSTATION: IASOSTYPE = IASOSTYPE(5i32);
pub const SYSTEM_TYPE_NT10_0_WORKSTATION: IASOSTYPE = IASOSTYPE(6i32);
pub const SYSTEM_TYPE_NT4_SERVER: IASOSTYPE = IASOSTYPE(7i32);
pub const SYSTEM_TYPE_NT5_SERVER: IASOSTYPE = IASOSTYPE(8i32);
pub const SYSTEM_TYPE_NT6_SERVER: IASOSTYPE = IASOSTYPE(9i32);
pub const SYSTEM_TYPE_NT6_1_SERVER: IASOSTYPE = IASOSTYPE(10i32);
pub const SYSTEM_TYPE_NT6_2_SERVER: IASOSTYPE = IASOSTYPE(11i32);
pub const SYSTEM_TYPE_NT6_3_SERVER: IASOSTYPE = IASOSTYPE(12i32);
pub const SYSTEM_TYPE_NT10_0_SERVER: IASOSTYPE = IASOSTYPE(13i32);
impl ::core::convert::From<i32> for IASOSTYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IASOSTYPE {
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 IASPROPERTIES(pub i32);
pub const PROPERTY_IAS_RADIUSSERVERGROUPS_COLLECTION: IASPROPERTIES = IASPROPERTIES(1024i32);
pub const PROPERTY_IAS_POLICIES_COLLECTION: IASPROPERTIES = IASPROPERTIES(1025i32);
pub const PROPERTY_IAS_PROFILES_COLLECTION: IASPROPERTIES = IASPROPERTIES(1026i32);
pub const PROPERTY_IAS_PROTOCOLS_COLLECTION: IASPROPERTIES = IASPROPERTIES(1027i32);
pub const PROPERTY_IAS_AUDITORS_COLLECTION: IASPROPERTIES = IASPROPERTIES(1028i32);
pub const PROPERTY_IAS_REQUESTHANDLERS_COLLECTION: IASPROPERTIES = IASPROPERTIES(1029i32);
pub const PROPERTY_IAS_PROXYPOLICIES_COLLECTION: IASPROPERTIES = IASPROPERTIES(1030i32);
pub const PROPERTY_IAS_PROXYPROFILES_COLLECTION: IASPROPERTIES = IASPROPERTIES(1031i32);
pub const PROPERTY_IAS_REMEDIATIONSERVERGROUPS_COLLECTION: IASPROPERTIES = IASPROPERTIES(1032i32);
pub const PROPERTY_IAS_SHVTEMPLATES_COLLECTION: IASPROPERTIES = IASPROPERTIES(1033i32);
impl ::core::convert::From<i32> for IASPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IASPROPERTIES {
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 IDENTITY_TYPE(pub i32);
pub const IAS_IDENTITY_NO_DEFAULT: IDENTITY_TYPE = IDENTITY_TYPE(1i32);
impl ::core::convert::From<i32> for IDENTITY_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IDENTITY_TYPE {
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 IPFILTERPROPERTIES(pub i32);
pub const PROPERTY_IPFILTER_ATTRIBUTES_COLLECTION: IPFILTERPROPERTIES = IPFILTERPROPERTIES(1024i32);
impl ::core::convert::From<i32> for IPFILTERPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for IPFILTERPROPERTIES {
type Abi = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISdo(pub ::windows::core::IUnknown);
impl ISdo {
pub unsafe fn GetPropertyInfo(&self, id: i32) -> ::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), ::core::mem::transmute(id), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn GetProperty(&self, id: i32) -> ::windows::core::Result<super::super::System::Com::VARIANT> {
let mut result__: <super::super::System::Com::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), &mut result__).from_abi::<super::super::System::Com::VARIANT>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn PutProperty(&self, id: i32, pvalue: *const super::super::System::Com::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), ::core::mem::transmute(pvalue)).ok()
}
pub unsafe fn ResetProperty(&self, id: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(id)).ok()
}
pub unsafe fn Apply(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Restore(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self)).ok()
}
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).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
}
unsafe impl ::windows::core::Interface for ISdo {
type Vtable = ISdo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x56bc53de_96db_11d1_bf3f_000000000000);
}
impl ::core::convert::From<ISdo> for ::windows::core::IUnknown {
fn from(value: ISdo) -> Self {
value.0
}
}
impl ::core::convert::From<&ISdo> for ::windows::core::IUnknown {
fn from(value: &ISdo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISdo {
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 ISdo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ISdo> for super::super::System::Com::IDispatch {
fn from(value: ISdo) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ISdo> for super::super::System::Com::IDispatch {
fn from(value: &ISdo) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for ISdo {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for &ISdo {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISdo_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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", 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::super::System::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::super::System::Com::EXCEPINFO>, puargerr: *mut u32) -> ::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, id: i32, pppropertyinfo: *mut ::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, id: i32, pvalue: *mut ::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,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: i32, pvalue: *const ::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, id: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenumvariant: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISdoCollection(pub ::windows::core::IUnknown);
impl ISdoCollection {
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).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i32>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
pub unsafe fn Add<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrname: Param0, ppitem: *mut ::core::option::Option<super::super::System::Com::IDispatch>) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), bstrname.into_param().abi(), ::core::mem::transmute(ppitem)).ok()
}
#[cfg(feature = "Win32_System_Com")]
pub unsafe fn Remove<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch>>(&self, pitem: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), pitem.into_param().abi()).ok()
}
pub unsafe fn RemoveAll(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Reload(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn IsNameUnique<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrname: Param0) -> ::windows::core::Result<i16> {
let mut result__: <i16 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), bstrname.into_param().abi(), &mut result__).from_abi::<i16>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn Item(&self, name: *const super::super::System::Com::VARIANT) -> ::windows::core::Result<super::super::System::Com::IDispatch> {
let mut result__: <super::super::System::Com::IDispatch as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(name), &mut result__).from_abi::<super::super::System::Com::IDispatch>(result__)
}
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).14)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
}
unsafe impl ::windows::core::Interface for ISdoCollection {
type Vtable = ISdoCollection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x56bc53e2_96db_11d1_bf3f_000000000000);
}
impl ::core::convert::From<ISdoCollection> for ::windows::core::IUnknown {
fn from(value: ISdoCollection) -> Self {
value.0
}
}
impl ::core::convert::From<&ISdoCollection> for ::windows::core::IUnknown {
fn from(value: &ISdoCollection) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISdoCollection {
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 ISdoCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ISdoCollection> for super::super::System::Com::IDispatch {
fn from(value: ISdoCollection) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ISdoCollection> for super::super::System::Com::IDispatch {
fn from(value: &ISdoCollection) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for ISdoCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for &ISdoCollection {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISdoCollection_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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", 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::super::System::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::super::System::Com::EXCEPINFO>, puargerr: *mut u32) -> ::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, pcount: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrname: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppitem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pitem: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrname: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pbool: *mut i16) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: *const ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pitem: *mut ::windows::core::RawPtr) -> ::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, ppenumvariant: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISdoDictionaryOld(pub ::windows::core::IUnknown);
impl ISdoDictionaryOld {
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn EnumAttributes(&self, id: *mut super::super::System::Com::VARIANT, pvalues: *mut super::super::System::Com::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), ::core::mem::transmute(pvalues)).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn GetAttributeInfo(&self, id: ATTRIBUTEID, pinfoids: *const super::super::System::Com::VARIANT) -> ::windows::core::Result<super::super::System::Com::VARIANT> {
let mut result__: <super::super::System::Com::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), ::core::mem::transmute(pinfoids), &mut result__).from_abi::<super::super::System::Com::VARIANT>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn EnumAttributeValues(&self, id: ATTRIBUTEID, pvalueids: *mut super::super::System::Com::VARIANT, pvaluesdesc: *mut super::super::System::Com::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), ::core::mem::transmute(pvalueids), ::core::mem::transmute(pvaluesdesc)).ok()
}
#[cfg(feature = "Win32_System_Com")]
pub unsafe fn CreateAttribute(&self, id: ATTRIBUTEID) -> ::windows::core::Result<super::super::System::Com::IDispatch> {
let mut result__: <super::super::System::Com::IDispatch as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), &mut result__).from_abi::<super::super::System::Com::IDispatch>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetAttributeID<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrattributename: Param0) -> ::windows::core::Result<ATTRIBUTEID> {
let mut result__: <ATTRIBUTEID as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), bstrattributename.into_param().abi(), &mut result__).from_abi::<ATTRIBUTEID>(result__)
}
}
unsafe impl ::windows::core::Interface for ISdoDictionaryOld {
type Vtable = ISdoDictionaryOld_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd432e5f4_53d8_11d2_9a3a_00c04fb998ac);
}
impl ::core::convert::From<ISdoDictionaryOld> for ::windows::core::IUnknown {
fn from(value: ISdoDictionaryOld) -> Self {
value.0
}
}
impl ::core::convert::From<&ISdoDictionaryOld> for ::windows::core::IUnknown {
fn from(value: &ISdoDictionaryOld) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISdoDictionaryOld {
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 ISdoDictionaryOld {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ISdoDictionaryOld> for super::super::System::Com::IDispatch {
fn from(value: ISdoDictionaryOld) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ISdoDictionaryOld> for super::super::System::Com::IDispatch {
fn from(value: &ISdoDictionaryOld) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for ISdoDictionaryOld {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for &ISdoDictionaryOld {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISdoDictionaryOld_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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", 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::super::System::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::super::System::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pvalues: *mut ::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,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ATTRIBUTEID, pinfoids: *const ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pinfovalues: *mut ::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,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ATTRIBUTEID, pvalueids: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pvaluesdesc: *mut ::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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: ATTRIBUTEID, ppattributeobject: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrattributename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pid: *mut ATTRIBUTEID) -> ::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 ISdoMachine(pub ::windows::core::IUnknown);
impl ISdoMachine {
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn Attach<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrcomputername: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), bstrcomputername.into_param().abi()).ok()
}
pub unsafe fn GetDictionarySDO(&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).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetServiceSDO<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, edatastore: IASDATASTORE, bstrservicename: 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).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(edatastore), bstrservicename.into_param().abi(), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetUserSDO<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, edatastore: IASDATASTORE, bstrusername: 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).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(edatastore), bstrusername.into_param().abi(), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
pub unsafe fn GetOSType(&self) -> ::windows::core::Result<IASOSTYPE> {
let mut result__: <IASOSTYPE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IASOSTYPE>(result__)
}
pub unsafe fn GetDomainType(&self) -> ::windows::core::Result<IASDOMAINTYPE> {
let mut result__: <IASDOMAINTYPE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IASDOMAINTYPE>(result__)
}
pub unsafe fn IsDirectoryAvailable(&self) -> ::windows::core::Result<i16> {
let mut result__: <i16 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i16>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetAttachedComputer(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> {
let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__)
}
pub unsafe fn GetSDOSchema(&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).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
}
unsafe impl ::windows::core::Interface for ISdoMachine {
type Vtable = ISdoMachine_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x479f6e75_49a2_11d2_8eca_00c04fc2f519);
}
impl ::core::convert::From<ISdoMachine> for ::windows::core::IUnknown {
fn from(value: ISdoMachine) -> Self {
value.0
}
}
impl ::core::convert::From<&ISdoMachine> for ::windows::core::IUnknown {
fn from(value: &ISdoMachine) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISdoMachine {
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 ISdoMachine {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ISdoMachine> for super::super::System::Com::IDispatch {
fn from(value: ISdoMachine) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ISdoMachine> for super::super::System::Com::IDispatch {
fn from(value: &ISdoMachine) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for ISdoMachine {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for &ISdoMachine {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISdoMachine_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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", 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::super::System::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::super::System::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrcomputername: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppdictionarysdo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, edatastore: IASDATASTORE, bstrservicename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppservicesdo: *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, edatastore: IASDATASTORE, bstrusername: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppusersdo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eostype: *mut IASOSTYPE) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, edomaintype: *mut IASDOMAINTYPE) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, booldirectoryavailable: *mut i16) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrcomputername: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsdoschema: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISdoMachine2(pub ::windows::core::IUnknown);
impl ISdoMachine2 {
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__)
}
#[cfg(feature = "Win32_System_Com")]
pub unsafe fn GetTypeInfo(&self, itinfo: u32, lcid: u32) -> ::windows::core::Result<super::super::System::Com::ITypeInfo> {
let mut result__: <super::super::System::Com::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::super::System::Com::ITypeInfo>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetIDsOfNames(&self, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", feature = "Win32_System_Ole"))]
pub unsafe fn Invoke(&self, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::super::System::Com::DISPPARAMS, pvarresult: *mut super::super::System::Com::VARIANT, pexcepinfo: *mut super::super::System::Com::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 Attach<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrcomputername: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), bstrcomputername.into_param().abi()).ok()
}
pub unsafe fn GetDictionarySDO(&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).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetServiceSDO<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, edatastore: IASDATASTORE, bstrservicename: 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).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(edatastore), bstrservicename.into_param().abi(), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetUserSDO<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, edatastore: IASDATASTORE, bstrusername: 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).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(edatastore), bstrusername.into_param().abi(), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
pub unsafe fn GetOSType(&self) -> ::windows::core::Result<IASOSTYPE> {
let mut result__: <IASOSTYPE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IASOSTYPE>(result__)
}
pub unsafe fn GetDomainType(&self) -> ::windows::core::Result<IASDOMAINTYPE> {
let mut result__: <IASDOMAINTYPE as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), &mut result__).from_abi::<IASDOMAINTYPE>(result__)
}
pub unsafe fn IsDirectoryAvailable(&self) -> ::windows::core::Result<i16> {
let mut result__: <i16 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<i16>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetAttachedComputer(&self) -> ::windows::core::Result<super::super::Foundation::BSTR> {
let mut result__: <super::super::Foundation::BSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BSTR>(result__)
}
pub unsafe fn GetSDOSchema(&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).15)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetTemplatesSDO<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrservicename: 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).16)(::core::mem::transmute_copy(self), bstrservicename.into_param().abi(), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
pub unsafe fn EnableTemplates(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn SyncConfigAgainstTemplates<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, bstrservicename: Param0, ppconfigroot: *mut ::core::option::Option<::windows::core::IUnknown>, pptemplatesroot: *mut ::core::option::Option<::windows::core::IUnknown>, bforcedsync: i16) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), bstrservicename.into_param().abi(), ::core::mem::transmute(ppconfigroot), ::core::mem::transmute(pptemplatesroot), ::core::mem::transmute(bforcedsync)).ok()
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn ImportRemoteTemplates<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>>(&self, plocaltemplatesroot: Param0, bstrremotemachinename: Param1) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), plocaltemplatesroot.into_param().abi(), bstrremotemachinename.into_param().abi()).ok()
}
pub unsafe fn Reload(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for ISdoMachine2 {
type Vtable = ISdoMachine2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x518e5ffe_d8ce_4f7e_a5db_b40a35419d3b);
}
impl ::core::convert::From<ISdoMachine2> for ::windows::core::IUnknown {
fn from(value: ISdoMachine2) -> Self {
value.0
}
}
impl ::core::convert::From<&ISdoMachine2> for ::windows::core::IUnknown {
fn from(value: &ISdoMachine2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISdoMachine2 {
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 ISdoMachine2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<ISdoMachine2> for ISdoMachine {
fn from(value: ISdoMachine2) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&ISdoMachine2> for ISdoMachine {
fn from(value: &ISdoMachine2) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, ISdoMachine> for ISdoMachine2 {
fn into_param(self) -> ::windows::core::Param<'a, ISdoMachine> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, ISdoMachine> for &ISdoMachine2 {
fn into_param(self) -> ::windows::core::Param<'a, ISdoMachine> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ISdoMachine2> for super::super::System::Com::IDispatch {
fn from(value: ISdoMachine2) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ISdoMachine2> for super::super::System::Com::IDispatch {
fn from(value: &ISdoMachine2) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for ISdoMachine2 {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for &ISdoMachine2 {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISdoMachine2_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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", 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::super::System::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::super::System::Com::EXCEPINFO>, puargerr: *mut u32) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole")))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrcomputername: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppdictionarysdo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, edatastore: IASDATASTORE, bstrservicename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppservicesdo: *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, edatastore: IASDATASTORE, bstrusername: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppusersdo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eostype: *mut IASOSTYPE) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, edomaintype: *mut IASDOMAINTYPE) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, booldirectoryavailable: *mut i16) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrcomputername: *mut ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsdoschema: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrservicename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pptemplatessdo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrservicename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, ppconfigroot: *mut ::windows::core::RawPtr, pptemplatesroot: *mut ::windows::core::RawPtr, bforcedsync: i16) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, plocaltemplatesroot: ::windows::core::RawPtr, bstrremotemachinename: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_Foundation"))] usize,
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 ISdoServiceControl(pub ::windows::core::IUnknown);
impl ISdoServiceControl {
pub unsafe fn StartService(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn StopService(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn GetServiceStatus(&self) -> ::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), &mut result__).from_abi::<i32>(result__)
}
pub unsafe fn ResetService(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for ISdoServiceControl {
type Vtable = ISdoServiceControl_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x479f6e74_49a2_11d2_8eca_00c04fc2f519);
}
impl ::core::convert::From<ISdoServiceControl> for ::windows::core::IUnknown {
fn from(value: ISdoServiceControl) -> Self {
value.0
}
}
impl ::core::convert::From<&ISdoServiceControl> for ::windows::core::IUnknown {
fn from(value: &ISdoServiceControl) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISdoServiceControl {
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 ISdoServiceControl {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ISdoServiceControl> for super::super::System::Com::IDispatch {
fn from(value: ISdoServiceControl) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ISdoServiceControl> for super::super::System::Com::IDispatch {
fn from(value: &ISdoServiceControl) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for ISdoServiceControl {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for &ISdoServiceControl {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISdoServiceControl_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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", 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::super::System::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::super::System::Com::EXCEPINFO>, puargerr: *mut u32) -> ::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) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, status: *mut i32) -> ::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 ITemplateSdo(pub ::windows::core::IUnknown);
impl ITemplateSdo {
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__)
}
#[cfg(feature = "Win32_System_Com")]
pub unsafe fn GetTypeInfo(&self, itinfo: u32, lcid: u32) -> ::windows::core::Result<super::super::System::Com::ITypeInfo> {
let mut result__: <super::super::System::Com::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::super::System::Com::ITypeInfo>(result__)
}
#[cfg(feature = "Win32_Foundation")]
pub unsafe fn GetIDsOfNames(&self, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", feature = "Win32_System_Ole"))]
pub unsafe fn Invoke(&self, dispidmember: i32, riid: *const ::windows::core::GUID, lcid: u32, wflags: u16, pdispparams: *const super::super::System::Com::DISPPARAMS, pvarresult: *mut super::super::System::Com::VARIANT, pexcepinfo: *mut super::super::System::Com::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()
}
pub unsafe fn GetPropertyInfo(&self, id: i32) -> ::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), ::core::mem::transmute(id), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn GetProperty(&self, id: i32) -> ::windows::core::Result<super::super::System::Com::VARIANT> {
let mut result__: <super::super::System::Com::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), &mut result__).from_abi::<super::super::System::Com::VARIANT>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))]
pub unsafe fn PutProperty(&self, id: i32, pvalue: *const super::super::System::Com::VARIANT) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(id), ::core::mem::transmute(pvalue)).ok()
}
pub unsafe fn ResetProperty(&self, id: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(id)).ok()
}
pub unsafe fn Apply(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self)).ok()
}
pub unsafe fn Restore(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self)).ok()
}
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).13)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::IUnknown>(result__)
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
pub unsafe fn AddToCollection<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch>>(&self, bstrname: Param0, pcollection: Param1, ppitem: *mut ::core::option::Option<super::super::System::Com::IDispatch>) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), bstrname.into_param().abi(), pcollection.into_param().abi(), ::core::mem::transmute(ppitem)).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))]
pub unsafe fn AddToSdo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BSTR>, Param1: ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch>>(&self, bstrname: Param0, psdotarget: Param1, ppitem: *mut ::core::option::Option<super::super::System::Com::IDispatch>) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), bstrname.into_param().abi(), psdotarget.into_param().abi(), ::core::mem::transmute(ppitem)).ok()
}
#[cfg(feature = "Win32_System_Com")]
pub unsafe fn AddToSdoAsProperty<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch>>(&self, psdotarget: Param0, id: i32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), psdotarget.into_param().abi(), ::core::mem::transmute(id)).ok()
}
}
unsafe impl ::windows::core::Interface for ITemplateSdo {
type Vtable = ITemplateSdo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8aa85302_d2e2_4e20_8b1f_a571e437d6c9);
}
impl ::core::convert::From<ITemplateSdo> for ::windows::core::IUnknown {
fn from(value: ITemplateSdo) -> Self {
value.0
}
}
impl ::core::convert::From<&ITemplateSdo> for ::windows::core::IUnknown {
fn from(value: &ITemplateSdo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ITemplateSdo {
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 ITemplateSdo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<ITemplateSdo> for ISdo {
fn from(value: ITemplateSdo) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&ITemplateSdo> for ISdo {
fn from(value: &ITemplateSdo) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, ISdo> for ITemplateSdo {
fn into_param(self) -> ::windows::core::Param<'a, ISdo> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, ISdo> for &ITemplateSdo {
fn into_param(self) -> ::windows::core::Param<'a, ISdo> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<ITemplateSdo> for super::super::System::Com::IDispatch {
fn from(value: ITemplateSdo) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Win32_System_Com")]
impl ::core::convert::From<&ITemplateSdo> for super::super::System::Com::IDispatch {
fn from(value: &ITemplateSdo) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for ITemplateSdo {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Win32_System_Com")]
impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IDispatch> for &ITemplateSdo {
fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IDispatch> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ITemplateSdo_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,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, itinfo: u32, lcid: u32, pptinfo: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
#[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, riid: *const ::windows::core::GUID, rgsznames: *const 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_Com", 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::super::System::Com::DISPPARAMS, pvarresult: *mut ::core::mem::ManuallyDrop<super::super::System::Com::VARIANT>, pexcepinfo: *mut ::core::mem::ManuallyDrop<super::super::System::Com::EXCEPINFO>, puargerr: *mut u32) -> ::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, id: i32, pppropertyinfo: *mut ::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, id: i32, pvalue: *mut ::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,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, id: i32, pvalue: *const ::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, id: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppenumvariant: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrname: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, pcollection: ::windows::core::RawPtr, ppitem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, bstrname: ::core::mem::ManuallyDrop<super::super::Foundation::BSTR>, psdotarget: ::windows::core::RawPtr, ppitem: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize,
#[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psdotarget: ::windows::core::RawPtr, id: i32) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Win32_System_Com"))] usize,
);
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct NAMESPROPERTIES(pub i32);
pub const PROPERTY_NAMES_REALMS: NAMESPROPERTIES = NAMESPROPERTIES(1026i32);
impl ::core::convert::From<i32> for NAMESPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NAMESPROPERTIES {
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 NAPPROPERTIES(pub i32);
pub const PROPERTY_NAP_POLICIES_COLLECTION: NAPPROPERTIES = NAPPROPERTIES(1026i32);
pub const PROPERTY_SHV_TEMPLATES_COLLECTION: NAPPROPERTIES = NAPPROPERTIES(1027i32);
impl ::core::convert::From<i32> for NAPPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NAPPROPERTIES {
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 NEW_LOG_FILE_FREQUENCY(pub i32);
pub const IAS_LOGGING_UNLIMITED_SIZE: NEW_LOG_FILE_FREQUENCY = NEW_LOG_FILE_FREQUENCY(0i32);
pub const IAS_LOGGING_DAILY: NEW_LOG_FILE_FREQUENCY = NEW_LOG_FILE_FREQUENCY(1i32);
pub const IAS_LOGGING_WEEKLY: NEW_LOG_FILE_FREQUENCY = NEW_LOG_FILE_FREQUENCY(2i32);
pub const IAS_LOGGING_MONTHLY: NEW_LOG_FILE_FREQUENCY = NEW_LOG_FILE_FREQUENCY(3i32);
pub const IAS_LOGGING_WHEN_FILE_SIZE_REACHES: NEW_LOG_FILE_FREQUENCY = NEW_LOG_FILE_FREQUENCY(4i32);
impl ::core::convert::From<i32> for NEW_LOG_FILE_FREQUENCY {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NEW_LOG_FILE_FREQUENCY {
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 NTEVENTLOGPROPERTIES(pub i32);
pub const PROPERTY_EVENTLOG_LOG_APPLICATION_EVENTS: NTEVENTLOGPROPERTIES = NTEVENTLOGPROPERTIES(1026i32);
pub const PROPERTY_EVENTLOG_LOG_MALFORMED: NTEVENTLOGPROPERTIES = NTEVENTLOGPROPERTIES(1027i32);
pub const PROPERTY_EVENTLOG_LOG_DEBUG: NTEVENTLOGPROPERTIES = NTEVENTLOGPROPERTIES(1028i32);
impl ::core::convert::From<i32> for NTEVENTLOGPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NTEVENTLOGPROPERTIES {
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 NTSAMPROPERTIES(pub i32);
pub const PROPERTY_NTSAM_ALLOW_LM_AUTHENTICATION: NTSAMPROPERTIES = NTSAMPROPERTIES(1026i32);
impl ::core::convert::From<i32> for NTSAMPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for NTSAMPROPERTIES {
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 POLICYPROPERTIES(pub i32);
pub const PROPERTY_POLICY_CONSTRAINT: POLICYPROPERTIES = POLICYPROPERTIES(1024i32);
pub const PROPERTY_POLICY_MERIT: POLICYPROPERTIES = POLICYPROPERTIES(1025i32);
pub const PROPERTY_POLICY_UNUSED0: POLICYPROPERTIES = POLICYPROPERTIES(1026i32);
pub const PROPERTY_POLICY_UNUSED1: POLICYPROPERTIES = POLICYPROPERTIES(1027i32);
pub const PROPERTY_POLICY_PROFILE_NAME: POLICYPROPERTIES = POLICYPROPERTIES(1028i32);
pub const PROPERTY_POLICY_ACTION: POLICYPROPERTIES = POLICYPROPERTIES(1029i32);
pub const PROPERTY_POLICY_CONDITIONS_COLLECTION: POLICYPROPERTIES = POLICYPROPERTIES(1030i32);
pub const PROPERTY_POLICY_ENABLED: POLICYPROPERTIES = POLICYPROPERTIES(1031i32);
pub const PROPERTY_POLICY_SOURCETAG: POLICYPROPERTIES = POLICYPROPERTIES(1032i32);
impl ::core::convert::From<i32> for POLICYPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for POLICYPROPERTIES {
type Abi = Self;
}
pub type PRADIUS_EXTENSION_FREE_ATTRIBUTES = unsafe extern "system" fn(pattrs: *mut RADIUS_ATTRIBUTE);
pub type PRADIUS_EXTENSION_INIT = unsafe extern "system" fn() -> u32;
pub type PRADIUS_EXTENSION_PROCESS = unsafe extern "system" fn(pattrs: *const RADIUS_ATTRIBUTE, pfaction: *mut RADIUS_ACTION) -> u32;
pub type PRADIUS_EXTENSION_PROCESS_2 = unsafe extern "system" fn(pecb: *mut RADIUS_EXTENSION_CONTROL_BLOCK) -> u32;
pub type PRADIUS_EXTENSION_PROCESS_EX = unsafe extern "system" fn(pinattrs: *const RADIUS_ATTRIBUTE, poutattrs: *mut *mut RADIUS_ATTRIBUTE, pfaction: *mut RADIUS_ACTION) -> u32;
pub type PRADIUS_EXTENSION_TERM = unsafe extern "system" fn();
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PROFILEPROPERTIES(pub i32);
pub const PROPERTY_PROFILE_ATTRIBUTES_COLLECTION: PROFILEPROPERTIES = PROFILEPROPERTIES(1024i32);
pub const PROPERTY_PROFILE_IPFILTER_TEMPLATE_GUID: PROFILEPROPERTIES = PROFILEPROPERTIES(1025i32);
impl ::core::convert::From<i32> for PROFILEPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PROFILEPROPERTIES {
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 PROTOCOLPROPERTIES(pub i32);
pub const PROPERTY_PROTOCOL_REQUEST_HANDLER: PROTOCOLPROPERTIES = PROTOCOLPROPERTIES(1026i32);
pub const PROPERTY_PROTOCOL_START: PROTOCOLPROPERTIES = PROTOCOLPROPERTIES(1027i32);
impl ::core::convert::From<i32> for PROTOCOLPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PROTOCOLPROPERTIES {
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 RADIUSPROPERTIES(pub i32);
pub const PROPERTY_RADIUS_ACCOUNTING_PORT: RADIUSPROPERTIES = RADIUSPROPERTIES(1027i32);
pub const PROPERTY_RADIUS_AUTHENTICATION_PORT: RADIUSPROPERTIES = RADIUSPROPERTIES(1028i32);
pub const PROPERTY_RADIUS_CLIENTS_COLLECTION: RADIUSPROPERTIES = RADIUSPROPERTIES(1029i32);
pub const PROPERTY_RADIUS_VENDORS_COLLECTION: RADIUSPROPERTIES = RADIUSPROPERTIES(1030i32);
impl ::core::convert::From<i32> for RADIUSPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUSPROPERTIES {
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 RADIUSPROXYPROPERTIES(pub i32);
pub const PROPERTY_RADIUSPROXY_SERVERGROUPS: RADIUSPROXYPROPERTIES = RADIUSPROXYPROPERTIES(1026i32);
impl ::core::convert::From<i32> for RADIUSPROXYPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUSPROXYPROPERTIES {
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 RADIUSSERVERGROUPPROPERTIES(pub i32);
pub const PROPERTY_RADIUSSERVERGROUP_SERVERS_COLLECTION: RADIUSSERVERGROUPPROPERTIES = RADIUSSERVERGROUPPROPERTIES(1024i32);
impl ::core::convert::From<i32> for RADIUSSERVERGROUPPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUSSERVERGROUPPROPERTIES {
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 RADIUSSERVERPROPERTIES(pub i32);
pub const PROPERTY_RADIUSSERVER_AUTH_PORT: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1024i32);
pub const PROPERTY_RADIUSSERVER_AUTH_SECRET: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1025i32);
pub const PROPERTY_RADIUSSERVER_ACCT_PORT: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1026i32);
pub const PROPERTY_RADIUSSERVER_ACCT_SECRET: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1027i32);
pub const PROPERTY_RADIUSSERVER_ADDRESS: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1028i32);
pub const PROPERTY_RADIUSSERVER_FORWARD_ACCT_ONOFF: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1029i32);
pub const PROPERTY_RADIUSSERVER_PRIORITY: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1030i32);
pub const PROPERTY_RADIUSSERVER_WEIGHT: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1031i32);
pub const PROPERTY_RADIUSSERVER_TIMEOUT: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1032i32);
pub const PROPERTY_RADIUSSERVER_MAX_LOST: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1033i32);
pub const PROPERTY_RADIUSSERVER_BLACKOUT: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1034i32);
pub const PROPERTY_RADIUSSERVER_SEND_SIGNATURE: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1035i32);
pub const PROPERTY_RADIUSSERVER_AUTH_SECRET_TEMPLATE_GUID: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1036i32);
pub const PROPERTY_RADIUSSERVER_ACCT_SECRET_TEMPLATE_GUID: RADIUSSERVERPROPERTIES = RADIUSSERVERPROPERTIES(1037i32);
impl ::core::convert::From<i32> for RADIUSSERVERPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUSSERVERPROPERTIES {
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 RADIUS_ACTION(pub i32);
pub const raContinue: RADIUS_ACTION = RADIUS_ACTION(0i32);
pub const raReject: RADIUS_ACTION = RADIUS_ACTION(1i32);
pub const raAccept: RADIUS_ACTION = RADIUS_ACTION(2i32);
impl ::core::convert::From<i32> for RADIUS_ACTION {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUS_ACTION {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct RADIUS_ATTRIBUTE {
pub dwAttrType: u32,
pub fDataType: RADIUS_DATA_TYPE,
pub cbDataLength: u32,
pub Anonymous: RADIUS_ATTRIBUTE_0,
}
impl RADIUS_ATTRIBUTE {}
impl ::core::default::Default for RADIUS_ATTRIBUTE {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for RADIUS_ATTRIBUTE {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for RADIUS_ATTRIBUTE {}
unsafe impl ::windows::core::Abi for RADIUS_ATTRIBUTE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub union RADIUS_ATTRIBUTE_0 {
pub dwValue: u32,
pub lpValue: *mut u8,
}
impl RADIUS_ATTRIBUTE_0 {}
impl ::core::default::Default for RADIUS_ATTRIBUTE_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for RADIUS_ATTRIBUTE_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for RADIUS_ATTRIBUTE_0 {}
unsafe impl ::windows::core::Abi for RADIUS_ATTRIBUTE_0 {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct RADIUS_ATTRIBUTE_ARRAY {
pub cbSize: u32,
pub Add: isize,
pub AttributeAt: *mut *mut *mut *mut *mut *mut *mut *mut *mut *mut RADIUS_ATTRIBUTE,
pub GetSize: isize,
pub InsertAt: isize,
pub RemoveAt: isize,
pub SetAt: isize,
}
impl RADIUS_ATTRIBUTE_ARRAY {}
impl ::core::default::Default for RADIUS_ATTRIBUTE_ARRAY {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for RADIUS_ATTRIBUTE_ARRAY {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("RADIUS_ATTRIBUTE_ARRAY").field("cbSize", &self.cbSize).field("Add", &self.Add).field("AttributeAt", &self.AttributeAt).field("GetSize", &self.GetSize).field("InsertAt", &self.InsertAt).field("RemoveAt", &self.RemoveAt).field("SetAt", &self.SetAt).finish()
}
}
impl ::core::cmp::PartialEq for RADIUS_ATTRIBUTE_ARRAY {
fn eq(&self, other: &Self) -> bool {
self.cbSize == other.cbSize && self.Add == other.Add && self.AttributeAt == other.AttributeAt && self.GetSize == other.GetSize && self.InsertAt == other.InsertAt && self.RemoveAt == other.RemoveAt && self.SetAt == other.SetAt
}
}
impl ::core::cmp::Eq for RADIUS_ATTRIBUTE_ARRAY {}
unsafe impl ::windows::core::Abi for RADIUS_ATTRIBUTE_ARRAY {
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 RADIUS_ATTRIBUTE_TYPE(pub i32);
pub const ratMinimum: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(0i32);
pub const ratUserName: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(1i32);
pub const ratUserPassword: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(2i32);
pub const ratCHAPPassword: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(3i32);
pub const ratNASIPAddress: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(4i32);
pub const ratNASPort: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(5i32);
pub const ratServiceType: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(6i32);
pub const ratFramedProtocol: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(7i32);
pub const ratFramedIPAddress: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(8i32);
pub const ratFramedIPNetmask: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(9i32);
pub const ratFramedRouting: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(10i32);
pub const ratFilterId: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(11i32);
pub const ratFramedMTU: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(12i32);
pub const ratFramedCompression: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(13i32);
pub const ratLoginIPHost: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(14i32);
pub const ratLoginService: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(15i32);
pub const ratLoginPort: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(16i32);
pub const ratReplyMessage: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(18i32);
pub const ratCallbackNumber: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(19i32);
pub const ratCallbackId: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(20i32);
pub const ratFramedRoute: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(22i32);
pub const ratFramedIPXNetwork: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(23i32);
pub const ratState: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(24i32);
pub const ratClass: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(25i32);
pub const ratVendorSpecific: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(26i32);
pub const ratSessionTimeout: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(27i32);
pub const ratIdleTimeout: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(28i32);
pub const ratTerminationAction: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(29i32);
pub const ratCalledStationId: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(30i32);
pub const ratCallingStationId: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(31i32);
pub const ratNASIdentifier: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(32i32);
pub const ratProxyState: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(33i32);
pub const ratLoginLATService: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(34i32);
pub const ratLoginLATNode: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(35i32);
pub const ratLoginLATGroup: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(36i32);
pub const ratFramedAppleTalkLink: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(37i32);
pub const ratFramedAppleTalkNetwork: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(38i32);
pub const ratFramedAppleTalkZone: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(39i32);
pub const ratAcctStatusType: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(40i32);
pub const ratAcctDelayTime: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(41i32);
pub const ratAcctInputOctets: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(42i32);
pub const ratAcctOutputOctets: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(43i32);
pub const ratAcctSessionId: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(44i32);
pub const ratAcctAuthentic: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(45i32);
pub const ratAcctSessionTime: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(46i32);
pub const ratAcctInputPackets: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(47i32);
pub const ratAcctOutputPackets: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(48i32);
pub const ratAcctTerminationCause: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(49i32);
pub const ratCHAPChallenge: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(60i32);
pub const ratNASPortType: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(61i32);
pub const ratPortLimit: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(62i32);
pub const ratTunnelType: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(64i32);
pub const ratMediumType: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(65i32);
pub const ratTunnelPassword: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(69i32);
pub const ratTunnelPrivateGroupID: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(81i32);
pub const ratNASIPv6Address: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(95i32);
pub const ratFramedInterfaceId: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(96i32);
pub const ratFramedIPv6Prefix: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(97i32);
pub const ratLoginIPv6Host: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(98i32);
pub const ratFramedIPv6Route: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(99i32);
pub const ratFramedIPv6Pool: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(100i32);
pub const ratCode: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(262i32);
pub const ratIdentifier: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(263i32);
pub const ratAuthenticator: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(264i32);
pub const ratSrcIPAddress: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(265i32);
pub const ratSrcPort: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(266i32);
pub const ratProvider: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(267i32);
pub const ratStrippedUserName: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(268i32);
pub const ratFQUserName: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(269i32);
pub const ratPolicyName: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(270i32);
pub const ratUniqueId: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(271i32);
pub const ratExtensionState: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(272i32);
pub const ratEAPTLV: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(273i32);
pub const ratRejectReasonCode: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(274i32);
pub const ratCRPPolicyName: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(275i32);
pub const ratProviderName: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(276i32);
pub const ratClearTextPassword: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(277i32);
pub const ratSrcIPv6Address: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(278i32);
pub const ratCertificateThumbprint: RADIUS_ATTRIBUTE_TYPE = RADIUS_ATTRIBUTE_TYPE(279i32);
impl ::core::convert::From<i32> for RADIUS_ATTRIBUTE_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUS_ATTRIBUTE_TYPE {
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 RADIUS_AUTHENTICATION_PROVIDER(pub i32);
pub const rapUnknown: RADIUS_AUTHENTICATION_PROVIDER = RADIUS_AUTHENTICATION_PROVIDER(0i32);
pub const rapUsersFile: RADIUS_AUTHENTICATION_PROVIDER = RADIUS_AUTHENTICATION_PROVIDER(1i32);
pub const rapProxy: RADIUS_AUTHENTICATION_PROVIDER = RADIUS_AUTHENTICATION_PROVIDER(2i32);
pub const rapWindowsNT: RADIUS_AUTHENTICATION_PROVIDER = RADIUS_AUTHENTICATION_PROVIDER(3i32);
pub const rapMCIS: RADIUS_AUTHENTICATION_PROVIDER = RADIUS_AUTHENTICATION_PROVIDER(4i32);
pub const rapODBC: RADIUS_AUTHENTICATION_PROVIDER = RADIUS_AUTHENTICATION_PROVIDER(5i32);
pub const rapNone: RADIUS_AUTHENTICATION_PROVIDER = RADIUS_AUTHENTICATION_PROVIDER(6i32);
impl ::core::convert::From<i32> for RADIUS_AUTHENTICATION_PROVIDER {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUS_AUTHENTICATION_PROVIDER {
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 RADIUS_CODE(pub i32);
pub const rcUnknown: RADIUS_CODE = RADIUS_CODE(0i32);
pub const rcAccessRequest: RADIUS_CODE = RADIUS_CODE(1i32);
pub const rcAccessAccept: RADIUS_CODE = RADIUS_CODE(2i32);
pub const rcAccessReject: RADIUS_CODE = RADIUS_CODE(3i32);
pub const rcAccountingRequest: RADIUS_CODE = RADIUS_CODE(4i32);
pub const rcAccountingResponse: RADIUS_CODE = RADIUS_CODE(5i32);
pub const rcAccessChallenge: RADIUS_CODE = RADIUS_CODE(11i32);
pub const rcDiscard: RADIUS_CODE = RADIUS_CODE(256i32);
impl ::core::convert::From<i32> for RADIUS_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUS_CODE {
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 RADIUS_DATA_TYPE(pub i32);
pub const rdtUnknown: RADIUS_DATA_TYPE = RADIUS_DATA_TYPE(0i32);
pub const rdtString: RADIUS_DATA_TYPE = RADIUS_DATA_TYPE(1i32);
pub const rdtAddress: RADIUS_DATA_TYPE = RADIUS_DATA_TYPE(2i32);
pub const rdtInteger: RADIUS_DATA_TYPE = RADIUS_DATA_TYPE(3i32);
pub const rdtTime: RADIUS_DATA_TYPE = RADIUS_DATA_TYPE(4i32);
pub const rdtIpv6Address: RADIUS_DATA_TYPE = RADIUS_DATA_TYPE(5i32);
impl ::core::convert::From<i32> for RADIUS_DATA_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUS_DATA_TYPE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct RADIUS_EXTENSION_CONTROL_BLOCK {
pub cbSize: u32,
pub dwVersion: u32,
pub repPoint: RADIUS_EXTENSION_POINT,
pub rcRequestType: RADIUS_CODE,
pub rcResponseType: RADIUS_CODE,
pub GetRequest: isize,
pub GetResponse: isize,
pub SetResponseType: isize,
}
impl RADIUS_EXTENSION_CONTROL_BLOCK {}
impl ::core::default::Default for RADIUS_EXTENSION_CONTROL_BLOCK {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for RADIUS_EXTENSION_CONTROL_BLOCK {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("RADIUS_EXTENSION_CONTROL_BLOCK")
.field("cbSize", &self.cbSize)
.field("dwVersion", &self.dwVersion)
.field("repPoint", &self.repPoint)
.field("rcRequestType", &self.rcRequestType)
.field("rcResponseType", &self.rcResponseType)
.field("GetRequest", &self.GetRequest)
.field("GetResponse", &self.GetResponse)
.field("SetResponseType", &self.SetResponseType)
.finish()
}
}
impl ::core::cmp::PartialEq for RADIUS_EXTENSION_CONTROL_BLOCK {
fn eq(&self, other: &Self) -> bool {
self.cbSize == other.cbSize && self.dwVersion == other.dwVersion && self.repPoint == other.repPoint && self.rcRequestType == other.rcRequestType && self.rcResponseType == other.rcResponseType && self.GetRequest == other.GetRequest && self.GetResponse == other.GetResponse && self.SetResponseType == other.SetResponseType
}
}
impl ::core::cmp::Eq for RADIUS_EXTENSION_CONTROL_BLOCK {}
unsafe impl ::windows::core::Abi for RADIUS_EXTENSION_CONTROL_BLOCK {
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 RADIUS_EXTENSION_POINT(pub i32);
pub const repAuthentication: RADIUS_EXTENSION_POINT = RADIUS_EXTENSION_POINT(0i32);
pub const repAuthorization: RADIUS_EXTENSION_POINT = RADIUS_EXTENSION_POINT(1i32);
impl ::core::convert::From<i32> for RADIUS_EXTENSION_POINT {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUS_EXTENSION_POINT {
type Abi = Self;
}
pub const RADIUS_EXTENSION_VERSION: u32 = 1u32;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct RADIUS_REJECT_REASON_CODE(pub i32);
pub const rrrcUndefined: RADIUS_REJECT_REASON_CODE = RADIUS_REJECT_REASON_CODE(0i32);
pub const rrrcAccountUnknown: RADIUS_REJECT_REASON_CODE = RADIUS_REJECT_REASON_CODE(1i32);
pub const rrrcAccountDisabled: RADIUS_REJECT_REASON_CODE = RADIUS_REJECT_REASON_CODE(2i32);
pub const rrrcAccountExpired: RADIUS_REJECT_REASON_CODE = RADIUS_REJECT_REASON_CODE(3i32);
pub const rrrcAuthenticationFailure: RADIUS_REJECT_REASON_CODE = RADIUS_REJECT_REASON_CODE(4i32);
impl ::core::convert::From<i32> for RADIUS_REJECT_REASON_CODE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RADIUS_REJECT_REASON_CODE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct RADIUS_VSA_FORMAT {
pub VendorId: [u8; 4],
pub VendorType: u8,
pub VendorLength: u8,
pub AttributeSpecific: [u8; 1],
}
impl RADIUS_VSA_FORMAT {}
impl ::core::default::Default for RADIUS_VSA_FORMAT {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::fmt::Debug for RADIUS_VSA_FORMAT {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("RADIUS_VSA_FORMAT").field("VendorId", &self.VendorId).field("VendorType", &self.VendorType).field("VendorLength", &self.VendorLength).field("AttributeSpecific", &self.AttributeSpecific).finish()
}
}
impl ::core::cmp::PartialEq for RADIUS_VSA_FORMAT {
fn eq(&self, other: &Self) -> bool {
self.VendorId == other.VendorId && self.VendorType == other.VendorType && self.VendorLength == other.VendorLength && self.AttributeSpecific == other.AttributeSpecific
}
}
impl ::core::cmp::Eq for RADIUS_VSA_FORMAT {}
unsafe impl ::windows::core::Abi for RADIUS_VSA_FORMAT {
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 REMEDIATIONSERVERGROUPPROPERTIES(pub i32);
pub const PROPERTY_REMEDIATIONSERVERGROUP_SERVERS_COLLECTION: REMEDIATIONSERVERGROUPPROPERTIES = REMEDIATIONSERVERGROUPPROPERTIES(1024i32);
impl ::core::convert::From<i32> for REMEDIATIONSERVERGROUPPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for REMEDIATIONSERVERGROUPPROPERTIES {
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 REMEDIATIONSERVERPROPERTIES(pub i32);
pub const PROPERTY_REMEDIATIONSERVER_ADDRESS: REMEDIATIONSERVERPROPERTIES = REMEDIATIONSERVERPROPERTIES(1024i32);
pub const PROPERTY_REMEDIATIONSERVER_FRIENDLY_NAME: REMEDIATIONSERVERPROPERTIES = REMEDIATIONSERVERPROPERTIES(1025i32);
impl ::core::convert::From<i32> for REMEDIATIONSERVERPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for REMEDIATIONSERVERPROPERTIES {
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 REMEDIATIONSERVERSPROPERTIES(pub i32);
pub const PROPERTY_REMEDIATIONSERVERS_SERVERGROUPS: REMEDIATIONSERVERSPROPERTIES = REMEDIATIONSERVERSPROPERTIES(1026i32);
impl ::core::convert::From<i32> for REMEDIATIONSERVERSPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for REMEDIATIONSERVERSPROPERTIES {
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 SERVICE_TYPE(pub i32);
pub const SERVICE_TYPE_IAS: SERVICE_TYPE = SERVICE_TYPE(0i32);
pub const SERVICE_TYPE_RAS: SERVICE_TYPE = SERVICE_TYPE(1i32);
pub const SERVICE_TYPE_RAMGMTSVC: SERVICE_TYPE = SERVICE_TYPE(2i32);
pub const SERVICE_TYPE_MAX: SERVICE_TYPE = SERVICE_TYPE(3i32);
impl ::core::convert::From<i32> for SERVICE_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SERVICE_TYPE {
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 SHAREDSECRETPROPERTIES(pub i32);
pub const PROPERTY_SHAREDSECRET_STRING: SHAREDSECRETPROPERTIES = SHAREDSECRETPROPERTIES(1024i32);
impl ::core::convert::From<i32> for SHAREDSECRETPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SHAREDSECRETPROPERTIES {
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 SHVTEMPLATEPROPERTIES(pub i32);
pub const PROPERTY_SHV_COMBINATION_TYPE: SHVTEMPLATEPROPERTIES = SHVTEMPLATEPROPERTIES(1024i32);
pub const PROPERTY_SHV_LIST: SHVTEMPLATEPROPERTIES = SHVTEMPLATEPROPERTIES(1025i32);
pub const PROPERTY_SHVCONFIG_LIST: SHVTEMPLATEPROPERTIES = SHVTEMPLATEPROPERTIES(1026i32);
impl ::core::convert::From<i32> for SHVTEMPLATEPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SHVTEMPLATEPROPERTIES {
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 SHV_COMBINATION_TYPE(pub i32);
pub const SHV_COMBINATION_TYPE_ALL_PASS: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(0i32);
pub const SHV_COMBINATION_TYPE_ALL_FAIL: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(1i32);
pub const SHV_COMBINATION_TYPE_ONE_OR_MORE_PASS: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(2i32);
pub const SHV_COMBINATION_TYPE_ONE_OR_MORE_FAIL: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(3i32);
pub const SHV_COMBINATION_TYPE_ONE_OR_MORE_INFECTED: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(4i32);
pub const SHV_COMBINATION_TYPE_ONE_OR_MORE_TRANSITIONAL: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(5i32);
pub const SHV_COMBINATION_TYPE_ONE_OR_MORE_UNKNOWN: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(6i32);
pub const SHV_COMBINATION_TYPE_MAX: SHV_COMBINATION_TYPE = SHV_COMBINATION_TYPE(7i32);
impl ::core::convert::From<i32> for SHV_COMBINATION_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SHV_COMBINATION_TYPE {
type Abi = Self;
}
pub const SdoMachine: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe9218ae7_9e91_11d1_bf60_0080c7846bc0);
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct TEMPLATESPROPERTIES(pub i32);
pub const PROPERTY_TEMPLATES_POLICIES_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1024i32);
pub const PROPERTY_TEMPLATES_PROFILES_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1025i32);
pub const PROPERTY_TEMPLATES_PROFILES_COLLECTION: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1026i32);
pub const PROPERTY_TEMPLATES_PROXYPOLICIES_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1027i32);
pub const PROPERTY_TEMPLATES_PROXYPROFILES_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1028i32);
pub const PROPERTY_TEMPLATES_PROXYPROFILES_COLLECTION: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1029i32);
pub const PROPERTY_TEMPLATES_REMEDIATIONSERVERGROUPS_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1030i32);
pub const PROPERTY_TEMPLATES_SHVTEMPLATES_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1031i32);
pub const PROPERTY_TEMPLATES_CLIENTS_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1032i32);
pub const PROPERTY_TEMPLATES_RADIUSSERVERS_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1033i32);
pub const PROPERTY_TEMPLATES_SHAREDSECRETS_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1034i32);
pub const PROPERTY_TEMPLATES_IPFILTERS_TEMPLATES: TEMPLATESPROPERTIES = TEMPLATESPROPERTIES(1035i32);
impl ::core::convert::From<i32> for TEMPLATESPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for TEMPLATESPROPERTIES {
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 USERPROPERTIES(pub i32);
pub const PROPERTY_USER_CALLING_STATION_ID: USERPROPERTIES = USERPROPERTIES(1024i32);
pub const PROPERTY_USER_SAVED_CALLING_STATION_ID: USERPROPERTIES = USERPROPERTIES(1025i32);
pub const PROPERTY_USER_RADIUS_CALLBACK_NUMBER: USERPROPERTIES = USERPROPERTIES(1026i32);
pub const PROPERTY_USER_RADIUS_FRAMED_ROUTE: USERPROPERTIES = USERPROPERTIES(1027i32);
pub const PROPERTY_USER_RADIUS_FRAMED_IP_ADDRESS: USERPROPERTIES = USERPROPERTIES(1028i32);
pub const PROPERTY_USER_SAVED_RADIUS_CALLBACK_NUMBER: USERPROPERTIES = USERPROPERTIES(1029i32);
pub const PROPERTY_USER_SAVED_RADIUS_FRAMED_ROUTE: USERPROPERTIES = USERPROPERTIES(1030i32);
pub const PROPERTY_USER_SAVED_RADIUS_FRAMED_IP_ADDRESS: USERPROPERTIES = USERPROPERTIES(1031i32);
pub const PROPERTY_USER_ALLOW_DIALIN: USERPROPERTIES = USERPROPERTIES(1032i32);
pub const PROPERTY_USER_SERVICE_TYPE: USERPROPERTIES = USERPROPERTIES(1033i32);
pub const PROPERTY_USER_RADIUS_FRAMED_IPV6_ROUTE: USERPROPERTIES = USERPROPERTIES(1034i32);
pub const PROPERTY_USER_SAVED_RADIUS_FRAMED_IPV6_ROUTE: USERPROPERTIES = USERPROPERTIES(1035i32);
pub const PROPERTY_USER_RADIUS_FRAMED_INTERFACE_ID: USERPROPERTIES = USERPROPERTIES(1036i32);
pub const PROPERTY_USER_SAVED_RADIUS_FRAMED_INTERFACE_ID: USERPROPERTIES = USERPROPERTIES(1037i32);
pub const PROPERTY_USER_RADIUS_FRAMED_IPV6_PREFIX: USERPROPERTIES = USERPROPERTIES(1038i32);
pub const PROPERTY_USER_SAVED_RADIUS_FRAMED_IPV6_PREFIX: USERPROPERTIES = USERPROPERTIES(1039i32);
impl ::core::convert::From<i32> for USERPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for USERPROPERTIES {
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 VENDORPROPERTIES(pub i32);
pub const PROPERTY_NAS_VENDOR_ID: VENDORPROPERTIES = VENDORPROPERTIES(1024i32);
impl ::core::convert::From<i32> for VENDORPROPERTIES {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for VENDORPROPERTIES {
type Abi = Self;
}
|
/*
Project Euler Problem 16:
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
*/
fn main() {
let mut v = vec![0; 1000];
v[0] = 2;
for _ in 1..1000 {
let mut c = 0;
for j in 0..1000 {
v[j] = v[j]*2 + c;
c = 0;
while v[j] > 9 {
v[j] -= 10;
c += 1;
}
}
}
let s: i32 = v.iter().sum();
println!("{:}", s);
}
|
use crate::file_util::read_non_blank_lines;
use std::str::FromStr;
use std::cmp::{min, max};
#[allow(dead_code)]
pub fn run_day_nine() {
let lines = read_non_blank_lines("assets/day_nine")
.filter_map(|line| usize::from_str(line.as_str()).ok())
.collect::<Vec<usize>>();
let calculated_result = solve_part_one(&lines);
if let Some(result) = calculated_result {
println!("Result P1: {}", result);
let result2 = solve_part_two(result, &lines);
if let Some((smallest, largest)) = result2 {
println!(
"Result P2: Smallest {} and Largest {} sum to {}",
smallest,
largest,
smallest + largest
)
}
}
}
fn solve_part_one(data: &[usize]) -> Option<usize> {
let mut history = [0; 25];
let mut manipulated_history = [0; 25];
let mut iter = data.iter();
read_into_buffers(&mut history, &mut manipulated_history, &mut iter);
iter
.enumerate()
.find(|(index, &x)| {
let is_result = !is_number_sum_of_any(x, &mut manipulated_history);
let replacing = history[index % 25];
history[index % 25] = x;
if let Some(position) = manipulated_history.iter().position(|&it| it == replacing) {
manipulated_history[position] = x;
}
is_result
})
.map(|result| *result.1)
}
fn read_into_buffers<'a>(
buffer: &mut [usize; 25],
other_buffer: &mut [usize; 25],
iter: &mut impl Iterator<Item = &'a usize>
) {
iter.take(25).enumerate().for_each(|(index, n)| {
buffer[index] = *n;
other_buffer[index] = *n;
})
}
fn is_number_sum_of_any(value: usize, numbers: &mut[usize]) -> bool {
numbers.sort_unstable();
for x in 0..numbers.len() {
let current_value = numbers[x];
let other = numbers[x+1..]
.binary_search_by(|other| (other + current_value).cmp(&value));
if other.is_ok() {
return true;
}
}
false
}
fn solve_part_two(number: usize, numbers: &[usize]) -> Option<(usize, usize)> {
let mut sum;
let mut smallest;
let mut largest;
for i in 0..numbers.len() {
sum = numbers[i];
smallest = sum;
largest = sum;
for &value in numbers.iter().skip(i + 1) {
sum += value;
smallest = min(smallest, value);
largest = max(largest, value);
if sum == number {
return Some((smallest, largest));
}
if sum > number {
break;
}
}
}
None
}
#[cfg(test)]
mod tests {
use crate::day_nine::*;
#[test]
fn should_find_bounds_of_continuous_sum_matching_number() {
assert_eq!(
solve_part_two(
17,
&vec!(1, 32, 4, 7, 6, 78)
),
Some((4, 7))
)
}
#[test]
fn should_determine_if_number_is_sum_of_others() {
assert_eq!(
is_number_sum_of_any(
25,
&mut [1, 24]
),
true
);
assert_eq!(
is_number_sum_of_any(
25,
&mut [1, 23]
),
false
);
assert_eq!(
is_number_sum_of_any(
25,
&mut [1, 7, 8, 22, 3, 13, 24]
),
true
);
}
}
|
test_stdout!(errors_with_reason, "{caught, error, reason}\n");
|
extern crate toml;
/// The config object for the operation of the bot.
#[derive(Deserialize)]
pub struct Config {
/// Discord config object
pub discord: Discord,
// /// Database config object
// pub database: Database,
}
/// Contains all fields related to discord, such as tokens.
#[derive(Deserialize)]
pub struct Discord {
/// Discord bot token snowflake
pub token: String,
}
// # Use dotenv instead, works better for infer_schema!
// /// Database login config for postgresql.
// /// will be parsed into `postgres://username:password@location/name`
// #[derive(Deserialize)]
// pub struct Database {
// pub username: String,
// pub password: String,
// /// The IP location for the database
// pub location: String,
// /// The name of the database in psql
// pub name: String,
// }
|
//! Helper utilities.
use std::borrow::{Cow, ToOwned};
/// Be given a Cow for the "current" version of an object,
/// and visit it. If the visitor makes any changes and doesn't
/// error out, the new owned version will be returned.
/// This is only necessary because a new scope is needed to move the cow.
/// This will be deprecated once NLL lands.
pub fn atomic_maybe_change<T, F, E>(
current: &T,
examiner: F,
) -> Result<Option<<T as ToOwned>::Owned>, E>
where
T: ToOwned,
F: FnOnce(&mut Cow<'_, T>) -> Result<(), E>,
{
let mut cow = Cow::Borrowed(current);
(examiner)(&mut cow).map(|_| {
if let Cow::Owned(x) = cow {
Some(x)
} else {
None
}
})
}
|
use lib::{clumps, frequency_table, Kmer, Nucl};
use std::{
fs,
time::{Duration, Instant},
};
fn main() {
let str = fs::read_to_string("oric_vibrio_cholerae").unwrap();
let genome: Vec<_> = str
.chars()
.filter(|c| !c.is_whitespace())
.map(|c| Nucl::from(c))
.collect();
let now = Instant::now();
clumps(&genome, 500, 3, 9);
let dur = now.elapsed();
println!("{:?}", dur);
// let freqs = frequency_table(&nucls, 9);
// for (k, v) in freqs {
// if v >= 3 {
// print!("{},", Kmer::from_id(k, 9));
// }
// }
// println!("hello world")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.