text stringlengths 8 4.13M |
|---|
#[doc = "Reader of register ITLINE29"]
pub type R = crate::R<u32, super::ITLINE29>;
#[doc = "Reader of field `USART5`"]
pub type USART5_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 2 - USART5"]
#[inline(always)]
pub fn usart5(&self) -> USART5_R {
USART5_R::new(((self.bits >> 2) & 0x01) != 0)
}
}
|
// 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::registry::base::Command,
crate::registry::service_context::ServiceContext,
crate::switchboard::base::*,
failure::{format_err, Error},
fuchsia_async as fasync,
futures::StreamExt,
parking_lot::RwLock,
std::sync::Arc,
};
const FACTORY_RESET_FLAG: &str = "FactoryReset";
async fn schedule_clear_accounts(
service_context_handle: Arc<RwLock<ServiceContext>>,
) -> Result<(), Error> {
let device_settings_manager = service_context_handle
.read()
.connect::<fidl_fuchsia_devicesettings::DeviceSettingsManagerMarker>(
)?;
if device_settings_manager.set_integer(FACTORY_RESET_FLAG, 1).await.is_ok() {
return Ok(());
} else {
return Err(format_err!("could not set value in device settings"));
}
}
pub fn spawn_account_controller(
service_context_handle: Arc<RwLock<ServiceContext>>,
) -> futures::channel::mpsc::UnboundedSender<Command> {
let (account_handler_tx, mut account_handler_rx) =
futures::channel::mpsc::unbounded::<Command>();
fasync::spawn(async move {
while let Some(command) = account_handler_rx.next().await {
match command {
#[allow(unreachable_patterns)]
Command::HandleRequest(request, responder) =>
{
#[allow(unreachable_patterns)]
match request {
SettingRequest::ScheduleClearAccounts => {
match schedule_clear_accounts(service_context_handle.clone()).await {
Ok(()) => {
responder.send(Ok(None)).ok();
}
Err(error) => {
responder.send(Err(error)).ok();
}
}
}
_ => panic!("Unexpected request to account"),
}
}
// Ignore unsupported commands
_ => {}
}
}
});
account_handler_tx
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type IInkAnalysisNode = *mut ::core::ffi::c_void;
pub type IInkAnalyzerFactory = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct InkAnalysisDrawingKind(pub i32);
impl InkAnalysisDrawingKind {
pub const Drawing: Self = Self(0i32);
pub const Circle: Self = Self(1i32);
pub const Ellipse: Self = Self(2i32);
pub const Triangle: Self = Self(3i32);
pub const IsoscelesTriangle: Self = Self(4i32);
pub const EquilateralTriangle: Self = Self(5i32);
pub const RightTriangle: Self = Self(6i32);
pub const Quadrilateral: Self = Self(7i32);
pub const Rectangle: Self = Self(8i32);
pub const Square: Self = Self(9i32);
pub const Diamond: Self = Self(10i32);
pub const Trapezoid: Self = Self(11i32);
pub const Parallelogram: Self = Self(12i32);
pub const Pentagon: Self = Self(13i32);
pub const Hexagon: Self = Self(14i32);
}
impl ::core::marker::Copy for InkAnalysisDrawingKind {}
impl ::core::clone::Clone for InkAnalysisDrawingKind {
fn clone(&self) -> Self {
*self
}
}
pub type InkAnalysisInkBullet = *mut ::core::ffi::c_void;
pub type InkAnalysisInkDrawing = *mut ::core::ffi::c_void;
pub type InkAnalysisInkWord = *mut ::core::ffi::c_void;
pub type InkAnalysisLine = *mut ::core::ffi::c_void;
pub type InkAnalysisListItem = *mut ::core::ffi::c_void;
pub type InkAnalysisNode = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct InkAnalysisNodeKind(pub i32);
impl InkAnalysisNodeKind {
pub const UnclassifiedInk: Self = Self(0i32);
pub const Root: Self = Self(1i32);
pub const WritingRegion: Self = Self(2i32);
pub const Paragraph: Self = Self(3i32);
pub const Line: Self = Self(4i32);
pub const InkWord: Self = Self(5i32);
pub const InkBullet: Self = Self(6i32);
pub const InkDrawing: Self = Self(7i32);
pub const ListItem: Self = Self(8i32);
}
impl ::core::marker::Copy for InkAnalysisNodeKind {}
impl ::core::clone::Clone for InkAnalysisNodeKind {
fn clone(&self) -> Self {
*self
}
}
pub type InkAnalysisParagraph = *mut ::core::ffi::c_void;
pub type InkAnalysisResult = *mut ::core::ffi::c_void;
pub type InkAnalysisRoot = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct InkAnalysisStatus(pub i32);
impl InkAnalysisStatus {
pub const Updated: Self = Self(0i32);
pub const Unchanged: Self = Self(1i32);
}
impl ::core::marker::Copy for InkAnalysisStatus {}
impl ::core::clone::Clone for InkAnalysisStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct InkAnalysisStrokeKind(pub i32);
impl InkAnalysisStrokeKind {
pub const Auto: Self = Self(0i32);
pub const Writing: Self = Self(1i32);
pub const Drawing: Self = Self(2i32);
}
impl ::core::marker::Copy for InkAnalysisStrokeKind {}
impl ::core::clone::Clone for InkAnalysisStrokeKind {
fn clone(&self) -> Self {
*self
}
}
pub type InkAnalysisWritingRegion = *mut ::core::ffi::c_void;
pub type InkAnalyzer = *mut ::core::ffi::c_void;
|
//!
use std::ops::{Add, Sub, Mul, Div};
/// Trait for u8, u16, u32, u64 types
pub trait IsU8163264 : Copy + Add + Sub + Mul + Div {}
/// Trait for u8, u16, u32 types
pub trait IsU81632 : IsU8163264 {}
macro_rules! impl_trait {
($tr: ident, $ty: ident) => {
impl $tr for $ty {}
};
($tr: ident, $ty : ident, $($tt: ident), *) => {
impl_trait!($tr, $ty);
impl_trait!($tr, $($tt), *);
}
}
impl_trait!(IsU8163264, u8, u16, u32, u64);
impl_trait!(IsU81632, u8, u16, u32);
|
// This crate deliberately does not use the same linting rules as the other
// crates because of all the generated code it contains that we don't have much
// control over.
#![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)]
#![warn(
clippy::clone_on_ref_ptr,
clippy::dbg_macro,
clippy::explicit_iter_loop,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::todo,
clippy::use_self,
missing_debug_implementations,
unused_crate_dependencies
)]
#![allow(clippy::derive_partial_eq_without_eq, clippy::needless_borrow)]
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
use crate::influxdata::iox::ingester::v1 as proto;
use crate::influxdata::iox::ingester::v2 as proto2;
use base64::{prelude::BASE64_STANDARD, Engine};
use data_types::{NamespaceId, TableId, TimestampRange};
use datafusion::{common::DataFusionError, prelude::Expr};
use datafusion_proto::bytes::Serializeable;
use predicate::{Predicate, ValueExpr};
use prost::Message;
use snafu::{ResultExt, Snafu};
/// This module imports the generated protobuf code into a Rust module
/// hierarchy that matches the namespace hierarchy of the protobuf
/// definitions
#[allow(clippy::use_self)]
pub mod influxdata {
pub mod iox {
pub mod ingester {
pub mod v1 {
include!(concat!(env!("OUT_DIR"), "/influxdata.iox.ingester.v1.rs"));
include!(concat!(
env!("OUT_DIR"),
"/influxdata.iox.ingester.v1.serde.rs"
));
}
pub mod v2 {
// generated code violates a few lints, so opt-out of them
#![allow(clippy::future_not_send)]
include!(concat!(env!("OUT_DIR"), "/influxdata.iox.ingester.v2.rs"));
include!(concat!(
env!("OUT_DIR"),
"/influxdata.iox.ingester.v2.serde.rs"
));
}
}
}
}
/// Error returned if a request field has an invalid value. Includes
/// machinery to add parent field names for context -- thus it will
/// report `rules.write_timeout` than simply `write_timeout`.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct FieldViolation {
pub field: String,
pub description: String,
}
impl FieldViolation {
pub fn required(field: impl Into<String>) -> Self {
Self {
field: field.into(),
description: "Field is required".to_string(),
}
}
/// Re-scopes this error as the child of another field
pub fn scope(self, field: impl Into<String>) -> Self {
let field = if self.field.is_empty() {
field.into()
} else {
[field.into(), self.field].join(".")
};
Self {
field,
description: self.description,
}
}
}
impl std::error::Error for FieldViolation {}
impl std::fmt::Display for FieldViolation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Violation for field \"{}\": {}",
self.field, self.description
)
}
}
fn expr_to_bytes_violation(field: impl Into<String>, e: DataFusionError) -> FieldViolation {
FieldViolation {
field: field.into(),
description: format!("Error converting Expr to bytes: {e}"),
}
}
fn expr_from_bytes_violation(field: impl Into<String>, e: DataFusionError) -> FieldViolation {
FieldViolation {
field: field.into(),
description: format!("Error creating Expr from bytes: {e}"),
}
}
/// Request from the querier service to the ingester service
#[derive(Debug, PartialEq, Clone)]
pub struct IngesterQueryRequest {
/// namespace to search
pub namespace_id: NamespaceId,
/// Table to search
pub table_id: TableId,
/// Columns the query service is interested in
pub columns: Vec<String>,
/// Predicate for filtering
pub predicate: Option<Predicate>,
}
impl IngesterQueryRequest {
/// Make a request to return data for a specified table
pub fn new(
namespace_id: NamespaceId,
table_id: TableId,
columns: Vec<String>,
predicate: Option<Predicate>,
) -> Self {
Self {
namespace_id,
table_id,
columns,
predicate,
}
}
}
impl TryFrom<proto::IngesterQueryRequest> for IngesterQueryRequest {
type Error = FieldViolation;
fn try_from(proto: proto::IngesterQueryRequest) -> Result<Self, Self::Error> {
let proto::IngesterQueryRequest {
namespace_id,
table_id,
columns,
predicate,
} = proto;
let namespace_id = NamespaceId::new(namespace_id);
let table_id = TableId::new(table_id);
let predicate = predicate.map(TryInto::try_into).transpose()?;
Ok(Self::new(namespace_id, table_id, columns, predicate))
}
}
impl TryFrom<IngesterQueryRequest> for proto::IngesterQueryRequest {
type Error = FieldViolation;
fn try_from(query: IngesterQueryRequest) -> Result<Self, Self::Error> {
let IngesterQueryRequest {
namespace_id,
table_id,
columns,
predicate,
} = query;
Ok(Self {
namespace_id: namespace_id.get(),
table_id: table_id.get(),
columns,
predicate: predicate.map(TryInto::try_into).transpose()?,
})
}
}
/// Request from the querier service to the ingester service
#[derive(Debug, PartialEq, Clone)]
pub struct IngesterQueryRequest2 {
/// namespace to search
pub namespace_id: NamespaceId,
/// Table to search
pub table_id: TableId,
/// Columns the query service is interested in
pub columns: Vec<String>,
/// Predicate for filtering
pub filters: Vec<Expr>,
}
impl IngesterQueryRequest2 {
/// Make a request to return data for a specified table
pub fn new(
namespace_id: NamespaceId,
table_id: TableId,
columns: Vec<String>,
filters: Vec<Expr>,
) -> Self {
Self {
namespace_id,
table_id,
columns,
filters,
}
}
}
impl TryFrom<proto2::QueryRequest> for IngesterQueryRequest2 {
type Error = FieldViolation;
fn try_from(proto: proto2::QueryRequest) -> Result<Self, Self::Error> {
let proto2::QueryRequest {
namespace_id,
table_id,
columns,
filters,
} = proto;
let namespace_id = NamespaceId::new(namespace_id);
let table_id = TableId::new(table_id);
let filters = filters
.map(TryInto::try_into)
.transpose()?
.unwrap_or_default();
Ok(Self::new(namespace_id, table_id, columns, filters))
}
}
impl TryFrom<IngesterQueryRequest2> for proto2::QueryRequest {
type Error = FieldViolation;
fn try_from(query: IngesterQueryRequest2) -> Result<Self, Self::Error> {
let IngesterQueryRequest2 {
namespace_id,
table_id,
columns,
filters,
} = query;
Ok(Self {
namespace_id: namespace_id.get(),
table_id: table_id.get(),
columns,
filters: Some(filters.try_into()?),
})
}
}
impl TryFrom<Predicate> for proto::Predicate {
type Error = FieldViolation;
fn try_from(pred: Predicate) -> Result<Self, Self::Error> {
let Predicate {
field_columns,
range,
exprs,
value_expr,
} = pred;
let field_columns = field_columns.into_iter().flatten().collect();
let range = range.map(|r| proto::TimestampRange {
start: r.start(),
end: r.end(),
});
let exprs = exprs
.iter()
.map(|expr| {
expr.to_bytes()
.map(|bytes| bytes.to_vec())
.map_err(|e| expr_to_bytes_violation("exprs", e))
})
.collect::<Result<Vec<_>, _>>()?;
let value_expr = value_expr
.into_iter()
.map(TryInto::try_into)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
field_columns,
range,
exprs,
value_expr,
})
}
}
impl TryFrom<proto::Predicate> for Predicate {
type Error = FieldViolation;
fn try_from(proto: proto::Predicate) -> Result<Self, Self::Error> {
let proto::Predicate {
field_columns,
range,
exprs,
value_expr,
} = proto;
let field_columns = if field_columns.is_empty() {
None
} else {
Some(field_columns.into_iter().collect())
};
let range = range.map(|r| TimestampRange::new(r.start, r.end));
let exprs = exprs
.into_iter()
.map(|bytes| {
Expr::from_bytes_with_registry(&bytes, query_functions::registry())
.map_err(|e| expr_from_bytes_violation("exprs", e))
})
.collect::<Result<Vec<_>, _>>()?;
let value_expr = value_expr
.into_iter()
.map(|ve| {
let expr = Expr::from_bytes_with_registry(&ve.expr, query_functions::registry())
.map_err(|e| expr_from_bytes_violation("value_expr.expr", e))?;
// try to convert to ValueExpr
expr.try_into().map_err(|e| FieldViolation {
field: "expr".into(),
description: format!("Internal: Serialized expr a valid ValueExpr: {e:?}"),
})
})
.collect::<Result<Vec<ValueExpr>, FieldViolation>>()?;
Ok(Self {
field_columns,
range,
exprs,
value_expr,
})
}
}
impl TryFrom<ValueExpr> for proto::ValueExpr {
type Error = FieldViolation;
fn try_from(value_expr: ValueExpr) -> Result<Self, Self::Error> {
let expr: Expr = value_expr.into();
let expr = expr
.to_bytes()
.map_err(|e| expr_to_bytes_violation("value_expr.expr", e))?
.to_vec();
Ok(Self { expr })
}
}
impl TryFrom<Vec<Expr>> for proto2::Filters {
type Error = FieldViolation;
fn try_from(filters: Vec<Expr>) -> Result<Self, Self::Error> {
let exprs = filters
.iter()
.map(|expr| {
expr.to_bytes()
.map(|bytes| bytes.to_vec())
.map_err(|e| expr_to_bytes_violation("exprs", e))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Self { exprs })
}
}
impl TryFrom<proto2::Filters> for Vec<Expr> {
type Error = FieldViolation;
fn try_from(proto: proto2::Filters) -> Result<Self, Self::Error> {
let proto2::Filters { exprs } = proto;
let exprs = exprs
.into_iter()
.map(|bytes| {
Expr::from_bytes_with_registry(&bytes, query_functions::registry())
.map_err(|e| expr_from_bytes_violation("exprs", e))
})
.collect::<Result<Self, _>>()?;
Ok(exprs)
}
}
#[derive(Debug, Snafu)]
pub enum EncodeProtoPredicateFromBase64Error {
#[snafu(display("Cannot encode protobuf: {source}"))]
ProtobufEncode { source: prost::EncodeError },
}
/// Encodes [`proto::Predicate`] as base64.
pub fn encode_proto_predicate_as_base64(
predicate: &proto::Predicate,
) -> Result<String, EncodeProtoPredicateFromBase64Error> {
let mut buf = vec![];
predicate.encode(&mut buf).context(ProtobufEncodeSnafu)?;
Ok(BASE64_STANDARD.encode(&buf))
}
/// Encodes [`proto2::Filters`] as base64.
pub fn encode_proto2_filters_as_base64(
filters: &proto2::Filters,
) -> Result<String, EncodeProtoPredicateFromBase64Error> {
let mut buf = vec![];
filters.encode(&mut buf).context(ProtobufEncodeSnafu)?;
Ok(BASE64_STANDARD.encode(&buf))
}
#[derive(Debug, Snafu)]
pub enum DecodeProtoPredicateFromBase64Error {
#[snafu(display("Cannot decode base64: {source}"))]
Base64Decode { source: base64::DecodeError },
#[snafu(display("Cannot decode protobuf: {source}"))]
ProtobufDecode { source: prost::DecodeError },
}
/// Decodes [`proto::Predicate`] from base64 string.
pub fn decode_proto_predicate_from_base64(
s: &str,
) -> Result<proto::Predicate, DecodeProtoPredicateFromBase64Error> {
let predicate_binary = BASE64_STANDARD.decode(s).context(Base64DecodeSnafu)?;
proto::Predicate::decode(predicate_binary.as_slice()).context(ProtobufDecodeSnafu)
}
/// Decodes [`proto2::Filters`] from base64 string.
pub fn decode_proto2_filters_from_base64(
s: &str,
) -> Result<proto2::Filters, DecodeProtoPredicateFromBase64Error> {
let predicate_binary = BASE64_STANDARD.decode(s).context(Base64DecodeSnafu)?;
proto2::Filters::decode(predicate_binary.as_slice()).context(ProtobufDecodeSnafu)
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use super::*;
use datafusion::prelude::*;
#[test]
fn query_round_trip() {
let rust_predicate = predicate::Predicate::new()
.with_range(1, 100)
.with_expr(col("foo"))
.with_value_expr(col("_value").eq(lit("bar")).try_into().unwrap());
let rust_query = IngesterQueryRequest::new(
NamespaceId::new(42),
TableId::new(1337),
vec!["usage".into(), "time".into()],
Some(rust_predicate),
);
let proto_query: proto::IngesterQueryRequest = rust_query.clone().try_into().unwrap();
let rust_query_converted: IngesterQueryRequest = proto_query.try_into().unwrap();
assert_eq!(rust_query, rust_query_converted);
}
#[test]
fn query2_round_trip() {
let rust_query = IngesterQueryRequest2::new(
NamespaceId::new(42),
TableId::new(1337),
vec!["usage".into(), "time".into()],
vec![col("foo").eq(lit(1i64))],
);
let proto_query: proto2::QueryRequest = rust_query.clone().try_into().unwrap();
let rust_query_converted: IngesterQueryRequest2 = proto_query.try_into().unwrap();
assert_eq!(rust_query, rust_query_converted);
}
#[test]
fn predicate_proto_base64_roundtrip() {
let predicate = Predicate {
field_columns: Some(BTreeSet::from([String::from("foo"), String::from("bar")])),
range: Some(TimestampRange::new(13, 42)),
exprs: vec![Expr::Wildcard],
value_expr: vec![col("_value").eq(lit("bar")).try_into().unwrap()],
};
let predicate: proto::Predicate = predicate.try_into().unwrap();
let base64 = encode_proto_predicate_as_base64(&predicate).unwrap();
let predicate2 = decode_proto_predicate_from_base64(&base64).unwrap();
assert_eq!(predicate, predicate2);
}
#[test]
fn filters_proto2_base64_roundtrip() {
let filters = vec![col("col").eq(lit(1i64))];
let filters_1: proto2::Filters = filters.try_into().unwrap();
let base64_1 = encode_proto2_filters_as_base64(&filters_1).unwrap();
let filters_2 = decode_proto2_filters_from_base64(&base64_1).unwrap();
let base64_2 = encode_proto2_filters_as_base64(&filters_2).unwrap();
assert_eq!(filters_1, filters_2);
assert_eq!(base64_1, base64_2);
}
}
|
// 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.
#![cfg(test)]
use pretty_assertions::assert_eq;
use serde_json;
use std::collections::BTreeMap;
#[test]
fn fidl_ir() {
use banjo_lib::fidl;
let input = include_str!("fidl/test.fidl.json");
let mut decls = BTreeMap::new();
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/Int64Struct".to_string()),
fidl::Declaration::Struct,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/HasOptionalFieldStruct".to_string()),
fidl::Declaration::Struct,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/Has2OptionalFieldStruct".to_string()),
fidl::Declaration::Struct,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/Empty".to_string()),
fidl::Declaration::Struct,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/EmptyStructSandwich".to_string()),
fidl::Declaration::Struct,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/InlineXUnionInStruct".to_string()),
fidl::Declaration::Struct,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/OptionalXUnionInStruct".to_string()),
fidl::Declaration::Struct,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/SimpleTable".to_string()),
fidl::Declaration::Table,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/OlderSimpleTable".to_string()),
fidl::Declaration::Table,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/NewerSimpleTable".to_string()),
fidl::Declaration::Table,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/XUnionInTable".to_string()),
fidl::Declaration::Table,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/SimpleUnion".to_string()),
fidl::Declaration::Union,
);
decls.insert(
fidl::CompoundIdentifier("fidl.test.misc/SampleXUnion".to_string()),
fidl::Declaration::XUnion,
);
let decls = decls;
let expected = fidl::Ir {
version: fidl::Version("0.0.1".to_string()),
name: fidl::LibraryIdentifier("fidl.test.misc".to_string()),
const_declarations: vec![],
enum_declarations: vec![],
interface_declarations: vec![],
struct_declarations: vec![
fidl::Struct {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/Int64Struct".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 7,
column: 7,
}),
anonymous: Some(false),
members: vec![fidl::StructMember {
_type: fidl::Type::Primitive { subtype: fidl::PrimitiveSubtype::Int64 },
name: fidl::Identifier("x".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 8,
column: 10,
}),
size: fidl::Count(8),
max_out_of_line: fidl::Count(0),
alignment: fidl::Count(8),
offset: fidl::Count(0),
maybe_attributes: None,
maybe_default_value: None,
}],
size: fidl::Count(8),
max_out_of_line: fidl::Count(0),
},
fidl::Struct {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/HasOptionalFieldStruct".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 11,
column: 7,
}),
anonymous: Some(false),
members: vec![fidl::StructMember {
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/Int64Struct".to_string(),
),
nullable: true,
},
name: fidl::Identifier("x".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 12,
column: 17,
}),
size: fidl::Count(8),
max_out_of_line: fidl::Count(8),
alignment: fidl::Count(8),
offset: fidl::Count(0),
maybe_attributes: None,
maybe_default_value: None,
}],
size: fidl::Count(8),
max_out_of_line: fidl::Count(8),
},
fidl::Struct {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier(
"fidl.test.misc/Has2OptionalFieldStruct".to_string(),
),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 15,
column: 7,
}),
anonymous: Some(false),
members: vec![
fidl::StructMember {
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/Int64Struct".to_string(),
),
nullable: true,
},
name: fidl::Identifier("x".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 16,
column: 17,
}),
size: fidl::Count(8),
max_out_of_line: fidl::Count(8),
alignment: fidl::Count(8),
offset: fidl::Count(0),
maybe_attributes: None,
maybe_default_value: None,
},
fidl::StructMember {
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/Int64Struct".to_string(),
),
nullable: true,
},
name: fidl::Identifier("y".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 17,
column: 17,
}),
size: fidl::Count(8),
max_out_of_line: fidl::Count(8),
alignment: fidl::Count(8),
offset: fidl::Count(8),
maybe_attributes: None,
maybe_default_value: None,
},
],
size: fidl::Count(16),
max_out_of_line: fidl::Count(16),
},
fidl::Struct {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/Empty".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 20,
column: 7,
}),
anonymous: Some(false),
members: vec![],
size: fidl::Count(1),
max_out_of_line: fidl::Count(0),
},
fidl::Struct {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/EmptyStructSandwich".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 23,
column: 7,
}),
anonymous: Some(false),
members: vec![
fidl::StructMember {
_type: fidl::Type::Str { maybe_element_count: None, nullable: false },
name: fidl::Identifier("before".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 24,
column: 11,
}),
size: fidl::Count(16),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
offset: fidl::Count(0),
maybe_attributes: None,
maybe_default_value: None,
},
fidl::StructMember {
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/Empty".to_string(),
),
nullable: false,
},
name: fidl::Identifier("e".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 25,
column: 10,
}),
size: fidl::Count(1),
max_out_of_line: fidl::Count(0),
alignment: fidl::Count(1),
offset: fidl::Count(16),
maybe_attributes: None,
maybe_default_value: None,
},
fidl::StructMember {
_type: fidl::Type::Str { maybe_element_count: None, nullable: false },
name: fidl::Identifier("after".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 26,
column: 11,
}),
size: fidl::Count(16),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
offset: fidl::Count(24),
maybe_attributes: None,
maybe_default_value: None,
},
],
size: fidl::Count(40),
max_out_of_line: fidl::Count(4294967295),
},
fidl::Struct {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/InlineXUnionInStruct".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 70,
column: 7,
}),
anonymous: Some(false),
members: vec![
fidl::StructMember {
_type: fidl::Type::Str { maybe_element_count: None, nullable: false },
name: fidl::Identifier("before".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 71,
column: 11,
}),
size: fidl::Count(16),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
offset: fidl::Count(0),
maybe_attributes: None,
maybe_default_value: None,
},
fidl::StructMember {
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/SampleXUnion".to_string(),
),
nullable: false,
},
name: fidl::Identifier("xu".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 72,
column: 17,
}),
size: fidl::Count(24),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
offset: fidl::Count(16),
maybe_attributes: None,
maybe_default_value: None,
},
fidl::StructMember {
_type: fidl::Type::Str { maybe_element_count: None, nullable: false },
name: fidl::Identifier("after".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 73,
column: 11,
}),
size: fidl::Count(16),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
offset: fidl::Count(40),
maybe_attributes: None,
maybe_default_value: None,
},
],
size: fidl::Count(56),
max_out_of_line: fidl::Count(4294967295),
},
],
table_declarations: vec![fidl::Table {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/SimpleTable".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 37,
column: 6,
}),
members: vec![
fidl::TableMember {
ordinal: fidl::Ordinal(1),
reserved: false,
_type: Some(fidl::Type::Primitive { subtype: fidl::PrimitiveSubtype::Int64 }),
name: Some(fidl::Identifier("x".to_string())),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 38,
column: 13,
}),
size: Some(fidl::Count(8)),
max_out_of_line: Some(fidl::Count(0)),
alignment: Some(fidl::Count(8)),
offset: None,
maybe_default_value: None,
},
fidl::TableMember {
ordinal: fidl::Ordinal(2),
reserved: true,
..Default::default()
},
fidl::TableMember {
ordinal: fidl::Ordinal(3),
reserved: true,
..Default::default()
},
fidl::TableMember {
ordinal: fidl::Ordinal(4),
reserved: true,
..Default::default()
},
fidl::TableMember {
ordinal: fidl::Ordinal(5),
reserved: false,
_type: Some(fidl::Type::Primitive { subtype: fidl::PrimitiveSubtype::Int64 }),
name: Some(fidl::Identifier("y".to_string())),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 42,
column: 13,
}),
size: Some(fidl::Count(8)),
max_out_of_line: Some(fidl::Count(0)),
alignment: Some(fidl::Count(8)),
offset: None,
maybe_default_value: None,
},
],
size: fidl::Count(16),
max_out_of_line: fidl::Count(48),
}],
union_declarations: vec![fidl::Union {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/SimpleUnion".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 29,
column: 6,
}),
members: vec![
fidl::UnionMember {
_type: fidl::Type::Primitive { subtype: fidl::PrimitiveSubtype::Int32 },
name: fidl::Identifier("i32".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 30,
column: 10,
}),
size: fidl::Count(4),
max_out_of_line: fidl::Count(0),
alignment: fidl::Count(4),
offset: fidl::Count(8),
maybe_attributes: None,
},
fidl::UnionMember {
_type: fidl::Type::Primitive { subtype: fidl::PrimitiveSubtype::Int64 },
name: fidl::Identifier("i64".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 31,
column: 10,
}),
size: fidl::Count(8),
max_out_of_line: fidl::Count(0),
alignment: fidl::Count(8),
offset: fidl::Count(8),
maybe_attributes: None,
},
fidl::UnionMember {
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/Int64Struct".to_string(),
),
nullable: false,
},
name: fidl::Identifier("s".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 32,
column: 16,
}),
size: fidl::Count(8),
max_out_of_line: fidl::Count(0),
alignment: fidl::Count(8),
offset: fidl::Count(8),
maybe_attributes: None,
},
fidl::UnionMember {
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/Int64Struct".to_string(),
),
nullable: true,
},
name: fidl::Identifier("os".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 33,
column: 17,
}),
size: fidl::Count(8),
max_out_of_line: fidl::Count(8),
alignment: fidl::Count(8),
offset: fidl::Count(8),
maybe_attributes: None,
},
fidl::UnionMember {
_type: fidl::Type::Str { maybe_element_count: None, nullable: false },
name: fidl::Identifier("str".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 34,
column: 11,
}),
size: fidl::Count(16),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
offset: fidl::Count(8),
maybe_attributes: None,
},
],
size: fidl::Count(24),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
}],
xunion_declarations: vec![fidl::XUnion {
max_handles: Some(fidl::Count(0)),
maybe_attributes: None,
name: fidl::CompoundIdentifier("fidl.test.misc/SampleXUnion".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 64,
column: 7,
}),
members: vec![
fidl::XUnionMember {
ordinal: fidl::Ordinal(702498725),
_type: fidl::Type::Primitive { subtype: fidl::PrimitiveSubtype::Int32 },
name: fidl::Identifier("i".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 65,
column: 10,
}),
size: fidl::Count(4),
max_out_of_line: fidl::Count(0),
alignment: fidl::Count(4),
offset: fidl::Count(0),
maybe_attributes: None,
},
fidl::XUnionMember {
ordinal: fidl::Ordinal(1865512531),
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/SimpleUnion".to_string(),
),
nullable: false,
},
name: fidl::Identifier("su".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 66,
column: 16,
}),
size: fidl::Count(24),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
offset: fidl::Count(0),
maybe_attributes: None,
},
fidl::XUnionMember {
ordinal: fidl::Ordinal(811936989),
_type: fidl::Type::Identifier {
identifier: fidl::CompoundIdentifier(
"fidl.test.misc/SimpleTable".to_string(),
),
nullable: false,
},
name: fidl::Identifier("st".to_string()),
location: Some(fidl::Location {
filename: "../../sdk/lib/fidl/cpp/fidl_test.fidl".to_string(),
line: 67,
column: 16,
}),
size: fidl::Count(16),
max_out_of_line: fidl::Count(48),
alignment: fidl::Count(8),
offset: fidl::Count(0),
maybe_attributes: None,
},
],
size: fidl::Count(24),
max_out_of_line: fidl::Count(4294967295),
alignment: fidl::Count(8),
}],
declaration_order: vec![
fidl::CompoundIdentifier("fidl.test.misc/Has2OptionalFieldStruct".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/OptionalXUnionInStruct".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/HasOptionalFieldStruct".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/OlderSimpleTable".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/NewerSimpleTable".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/SimpleTable".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/Int64Struct".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/SimpleUnion".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/SampleXUnion".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/InlineXUnionInStruct".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/XUnionInTable".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/Empty".to_string()),
fidl::CompoundIdentifier("fidl.test.misc/EmptyStructSandwich".to_string()),
],
declarations: fidl::DeclarationsMap(decls),
library_dependencies: vec![],
};
let ir: fidl::Ir = serde_json::from_str(input).unwrap();
assert_eq!(ir, expected)
}
|
//! Types used to represent values at compile-time, eg: True/False.
/// Type-level booleans.
///
/// This is a re-export from `core_extensions::type_level_bool`,
/// so as to allow glob imports (`abi_stable::type_level::bools::*`)
/// without worrying about importing too many items.
pub mod bools {
#[doc(no_inline)]
pub use core_extensions::type_level_bool::{Boolean, False, True};
}
// Uncomment if I have a use for type-level `Option`s
// pub mod option;
/// Type-level enum representing whether a
/// `DynTrait`/`RObject`/`#[sabi_trait]`-generated trait object
/// can be converted back into the concrete type they were constructed with.
pub mod downcasting;
/// Marker types representing traits.
pub mod trait_marker {
///
pub struct Send;
///
pub struct Sync;
///
pub struct Clone;
///
pub struct Default;
///
pub struct Display;
///
pub struct Debug;
///
pub struct Eq;
///
pub struct PartialEq;
///
pub struct Ord;
///
pub struct PartialOrd;
///
pub struct Hash;
/// Represents the [`serde::Deserialize`] trait.
pub struct Deserialize;
/// Represents the [`serde::Serialize`] trait.
pub struct Serialize;
///
pub struct Iterator;
///
pub struct DoubleEndedIterator;
/// Represents the [`std::fmt::Write`] trait.
pub struct FmtWrite;
/// Represents the [`std::io::Write`] trait.
pub struct IoWrite;
/// Represents the [`std::io::Seek`] trait.
pub struct IoSeek;
/// Represents the [`std::io::Read`] trait.
pub struct IoRead;
/// Represents the [`std::io::BufRead`] trait.
pub struct IoBufRead;
/// Represents the [`std::error::Error`] trait.
pub struct Error;
/// Represents the [`std::marker::Unpin`] trait.
pub struct Unpin;
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct define_this_in_the_impl_InterfaceType_macro;
}
/// Type-level-enum representing whether a trait is implemented or not implemented.
pub mod impl_enum {
use crate::marker_type::NonOwningPhantom;
use core_extensions::type_level_bool::{False, True};
mod sealed {
pub trait Sealed {}
}
use self::sealed::Sealed;
/// Trait for [`Implemented`] and [`Unimplemented`]
pub trait Implementability: Sealed {
/// Whether the trait represented by the type parameter must be implemented.
const IS_IMPLD: bool;
}
/// Converts a type to either `Unimplemented` or `Implemented`.
///
/// The `T` type parameter represents the (un)required trait.
///
pub trait ImplFrom_<T: ?Sized> {
/// Either `Unimplemented` or `Implemented`.
type Impl: ?Sized + Implementability;
}
impl<T: ?Sized> ImplFrom_<T> for False {
type Impl = Unimplemented<T>;
}
impl<T: ?Sized> ImplFrom_<T> for True {
type Impl = Implemented<T>;
}
impl<T: ?Sized> ImplFrom_<T> for Unimplemented<T> {
type Impl = Unimplemented<T>;
}
impl<T: ?Sized> ImplFrom_<T> for Implemented<T> {
type Impl = Implemented<T>;
}
/// Converts `B` to either `Unimplemented<T>` or `Implemented<T>`.
///
/// The `T` type parameter represents the (un)required trait.
pub type ImplFrom<B, T> = <B as ImplFrom_<T>>::Impl;
/// Describes that a trait must be implemented.
///
/// The `T` type parameter represents the required trait.
pub struct Implemented<T: ?Sized>(NonOwningPhantom<T>);
impl<T: ?Sized> Sealed for Implemented<T> {}
impl<T: ?Sized> Implementability for Implemented<T> {
const IS_IMPLD: bool = true;
}
/// Describes that a trait does not need to be implemented.
///
/// The `T` type parameter represents the trait.
pub struct Unimplemented<T: ?Sized>(NonOwningPhantom<T>);
impl<T: ?Sized> Sealed for Unimplemented<T> {}
impl<T: ?Sized> Implementability for Unimplemented<T> {
const IS_IMPLD: bool = false;
}
}
|
/*
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
*
* push(x) -- Push element x onto stack.
* pop() -- Removes the element on top of the stack.
* top() -- Get the top element.
* getMin() -- Retrieve the minimum element in the stack.
*
* Examples:
* ----------
* MinStack minStack = new MinStack();
* minStack.push(-2);
* minStack.push(0);
* minStack.push(-3);
* minStack.getMin(); --> Returns -3.
* minStack.pop();
* minStack.top(); --> Returns 0.
* minStack.getMin(); --> Returns -2.
*/
#[derive(Debug)]
pub struct MinStack {
items: Vec<i32>,
min_items: Vec<i32>,
}
impl MinStack {
fn new() -> Self {
MinStack {
min_items: vec![],
items: vec![],
}
}
fn push(&mut self, x: i32) {
self.items.insert(0, x);
if self.min_items.len() == 0 {
self.min_items.push(x)
} else {
if x <= self.min_items[0] {
self.min_items.insert(0, x)
}
}
}
fn pop(&mut self) {
let x = self.items.remove(0);
if x == self.min_items[0] {
self.min_items.remove(0);
}
}
fn top(&self) -> i32 {
self.items[0]
}
fn get_min(&self) -> i32 {
self.min_items[0]
}
fn len(&self) -> usize {
self.items.len()
}
}
#[cfg(test)]
mod test {
use super::MinStack;
#[test]
fn example1() {
let mut stack = MinStack::new();
stack.push(-2);
stack.push(0);
stack.push(-3);
println!("stack: {:?}", stack);
stack.pop();
println!("stack: {:?}", stack);
assert_eq!(stack.len(), 2);
assert_eq!(stack.top(), 0);
assert_eq!(stack.get_min(), -2);
}
#[test]
fn example2() {
let mut stack = MinStack::new();
stack.push(0);
stack.push(1);
stack.push(0);
println!("stack: {:?}", stack);
assert_eq!(stack.get_min(), 0);
stack.pop();
println!("stack: {:?}", stack);
assert_eq!(stack.get_min(), 0);
}
}
|
use super::*;
use std::os::raw::c_char;
#[link(name = "dna")]
extern "C" {
fn dna4_revcomp(begin: *const c_char, end: *const c_char, out: *mut c_char) -> *mut c_char;
fn dna4_count_mismatches(
begin: *const c_char,
end: *const c_char,
other: *const c_char,
) -> usize;
fn dna4_count_mismatches_rc(
begin: *const c_char,
end: *const c_char,
other: *const c_char,
) -> usize;
fn dna4_fill_random(dest: *mut c_char, end: *mut c_char, seed: u32);
fn dna4_pack_2bits(begin: *const c_char, k: usize) -> u64;
fn dna4_unpack_2bits(begin: *mut c_char, k: usize, packed: u64);
}
pub fn revcomp(forward: &str) -> String {
let (begin, end) = to_ptrs(forward);
create_string_and_overwrite(forward.len(), |dest| unsafe {
dna4_revcomp(begin, end, dest)
})
}
pub fn count_mismatches(forward: &str, other: &str) -> usize {
let (begin, end) = to_ptrs(forward);
let (other, _) = to_ptrs(other);
unsafe { dna4_count_mismatches(begin, end, other) }
}
pub fn count_mismatches_rc(forward: &str, other: &str) -> usize {
let (begin, end) = to_ptrs(forward);
let (other, _) = to_ptrs(other);
unsafe { dna4_count_mismatches_rc(begin, end, other) }
}
pub fn random(size: usize, seed: u32) -> String {
create_string_and_overwrite(size, |dest| unsafe {
let dest_end = dest.offset(size as isize);
dna4_fill_random(dest, dest_end, seed);
dest_end
})
}
pub fn pack_2bits(forward: &str) -> u64 {
assert!(forward.len() <= 32);
let (begin, _) = to_ptrs(forward);
unsafe { dna4_pack_2bits(begin, forward.len()) }
}
pub fn unpack_2bits(k: usize, packed: u64) -> String {
assert!(k <= 32);
create_string_and_overwrite(k, |dest| unsafe {
dna4_unpack_2bits(dest, k, packed);
dest.offset(k as isize)
})
}
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use super::*;
#[test]
fn Trevcomp() {
let forward = "ACGT";
assert_eq!(forward, revcomp(&forward));
}
#[test]
fn Tcount_mismatches() {
let s1 = "ACGTACGTACGT";
let s2 = "ACGTTCGTACGA";
assert_eq!(count_mismatches(&s1, &s2), 2);
}
#[test]
fn Trandom() {
let tiny = random(6, 23);
let small = random(26, 23);
let large = random(10000, 23);
assert_eq!(tiny, small[..6]);
assert_eq!(small, large[..26]);
let unrelated = random(10000, 24);
assert!(large != unrelated);
}
#[test]
fn pack() {
let forward = "ACGTACGTTTCC";
let packed = pack_2bits(forward);
assert_eq!(packed, 0x1b1bf5);
let unpacked = unpack_2bits(forward.len(), packed);
assert_eq!(unpacked, forward);
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{err_msg, Error},
fidl_fuchsia_bluetooth::Status,
fidl_fuchsia_bluetooth_control::{
AddressType, BondingData, LeData, Ltk, RemoteKey, SecurityProperties, TechnologyType,
},
fuchsia_bluetooth::expectation,
futures::TryFutureExt,
};
use crate::harness::{
expect::expect_eq,
host_driver::{expect_host_peer, expect_remote_device, HostDriverHarness},
};
// TODO(armansito|xow): Add tests for BR/EDR and dual mode bond data.
fn new_le_bond_data(id: &str, address: &str, name: &str, has_ltk: bool) -> BondingData {
BondingData {
identifier: id.to_string(),
local_address: "AA:BB:CC:DD:EE:FF".to_string(),
name: Some(name.to_string()),
le: Some(Box::new(LeData {
address: address.to_string(),
address_type: AddressType::LeRandom,
connection_parameters: None,
services: vec![],
ltk: if has_ltk {
Some(Box::new(Ltk {
key: RemoteKey {
security_properties: SecurityProperties {
authenticated: true,
secure_connections: false,
encryption_key_size: 16,
},
value: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
},
key_size: 16,
ediv: 1,
rand: 2,
}))
} else {
None
},
irk: None,
csrk: None,
})),
bredr: None,
}
}
async fn add_bonds(
state: &HostDriverHarness,
mut bonds: Vec<BondingData>,
) -> Result<(Status), Error> {
state.aux().proxy().add_bonded_devices(&mut bonds.iter_mut()).err_into().await
}
const TEST_ID1: &str = "1234";
const TEST_ID2: &str = "2345";
const TEST_ADDR1: &str = "01:02:03:04:05:06";
const TEST_ADDR2: &str = "06:05:04:03:02:01";
const TEST_NAME1: &str = "Name1";
const TEST_NAME2: &str = "Name2";
// Tests initializing bonded LE devices.
async fn test_add_bonded_devices_success(test_state: HostDriverHarness) -> Result<(), Error> {
// Devices should be initially empty.
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(vec![], devices)?;
let bond_data1 = new_le_bond_data(TEST_ID1, TEST_ADDR1, TEST_NAME1, true /* has LTK */);
let bond_data2 = new_le_bond_data(TEST_ID2, TEST_ADDR2, TEST_NAME2, true /* has LTK */);
let status = add_bonds(&test_state, vec![bond_data1, bond_data2]).await?;
expect_true!(status.error.is_none())?;
// We should receive notifications for the newly added devices.
let expected1 = expectation::peer::address(TEST_ADDR1)
.and(expectation::peer::technology(TechnologyType::LowEnergy))
.and(expectation::peer::bonded(true));
let expected2 = expectation::peer::address(TEST_ADDR2)
.and(expectation::peer::technology(TechnologyType::LowEnergy))
.and(expectation::peer::bonded(true));
expect_host_peer(&test_state, expected1).await?;
expect_host_peer(&test_state, expected2).await?;
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(2, devices.len())?;
expect_true!(devices.iter().any(|dev| dev.address == TEST_ADDR1))?;
expect_true!(devices.iter().any(|dev| dev.address == TEST_ADDR2))?;
expect_true!(devices.iter().any(|dev| dev.name == Some(TEST_NAME1.to_string())))?;
expect_true!(devices.iter().any(|dev| dev.name == Some(TEST_NAME2.to_string())))?;
Ok(())
}
async fn test_add_bonded_devices_no_ltk_fails(test_state: HostDriverHarness) -> Result<(), Error> {
// Devices should be initially empty.
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(vec![], devices)?;
// Inserting a bonded device without a LTK should fail.
let bond_data = new_le_bond_data(TEST_ID1, TEST_ADDR1, TEST_NAME1, false /* no LTK */);
let status = add_bonds(&test_state, vec![bond_data]).await?;
expect_true!(status.error.is_some())?;
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(vec![], devices)?;
Ok(())
}
async fn test_add_bonded_devices_duplicate_entry(
test_state: HostDriverHarness,
) -> Result<(), Error> {
// Devices should be initially empty.
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(vec![], devices)?;
// Initialize one entry.
let bond_data = new_le_bond_data(TEST_ID1, TEST_ADDR1, TEST_NAME1, true /* with LTK */);
let status = add_bonds(&test_state, vec![bond_data]).await?;
expect_true!(status.error.is_none())?;
// We should receive a notification for the newly added device.
let expected = expectation::peer::address(TEST_ADDR1)
.and(expectation::peer::technology(TechnologyType::LowEnergy))
.and(expectation::peer::bonded(true));
expect_host_peer(&test_state, expected.clone()).await?;
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(1, devices.len())?;
// Adding an entry with the existing id should fail.
let bond_data = new_le_bond_data(TEST_ID1, TEST_ADDR2, TEST_NAME2, true /* with LTK */);
let status = add_bonds(&test_state, vec![bond_data]).await?;
expect_true!(status.error.is_some())?;
// Adding an entry with a different ID but existing address should fail.
let bond_data = new_le_bond_data(TEST_ID2, TEST_ADDR1, TEST_NAME1, true /* with LTK */);
let status = add_bonds(&test_state, vec![bond_data]).await?;
expect_true!(status.error.is_some())?;
Ok(())
}
// Tests that adding a list of bonding data with malformed content succeeds for the valid entries
// but reports an error.
async fn test_add_bonded_devices_invalid_entry(test_state: HostDriverHarness) -> Result<(), Error> {
// Devices should be initially empty.
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(vec![], devices)?;
// Add one entry with no LTK (invalid) and one with (valid). This should create an entry for the
// valid device but report an error for the invalid entry.
let no_ltk = new_le_bond_data(TEST_ID1, TEST_ADDR1, TEST_NAME1, false);
let with_ltk = new_le_bond_data(TEST_ID2, TEST_ADDR2, TEST_NAME2, true);
let status = add_bonds(&test_state, vec![no_ltk, with_ltk]).await?;
expect_true!(status.error.is_some())?;
let expected = expectation::peer::address(TEST_ADDR2)
.and(expectation::peer::technology(TechnologyType::LowEnergy))
.and(expectation::peer::bonded(true));
expect_host_peer(&test_state, expected.clone()).await?;
let devices = test_state.aux().proxy().list_devices().await?;
expect_eq!(1, devices.len())?;
expect_remote_device(&test_state, TEST_ADDR2, &expected)?;
Ok(())
}
/// Run all test cases.
pub fn run_all() -> Result<(), Error> {
run_suite!(
"bt-host driver bonding",
[
test_add_bonded_devices_success,
test_add_bonded_devices_no_ltk_fails,
test_add_bonded_devices_duplicate_entry,
test_add_bonded_devices_invalid_entry
]
)
}
|
use crate::{MetricKind, MetricObserver, Observation};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
/// An observation of a single u64 value
///
/// NOTE: If the same `U64Gauge` is used in multiple locations, e.g. a non-unique set
/// of attributes is provided to `Metric<U64Gauge>::recorder`, the reported value
/// will oscillate between those reported by the separate locations
#[derive(Debug, Clone, Default)]
pub struct U64Gauge {
state: Arc<AtomicU64>,
}
impl U64Gauge {
/// Sets the value of this U64Gauge
pub fn set(&self, value: u64) {
self.state.store(value, Ordering::Relaxed);
}
/// Increments the value of this U64Gauge by the specified amount.
pub fn inc(&self, delta: u64) {
self.state.fetch_add(delta, Ordering::Relaxed);
}
/// Decrements the value of this U64Gauge by the specified amount.
///
/// # Underflow / Overflow
///
/// This operation wraps around on over/underflow.
pub fn dec(&self, delta: u64) {
self.state.fetch_sub(delta, Ordering::Relaxed);
}
/// Adjusts the value of this U64Gauge by the specified delta.
///
/// # Underflow / Overflow
///
/// This operation wraps around on over/underflow.
pub fn delta(&self, delta: i64) {
if delta > 0 {
self.inc(delta as _);
} else {
self.dec(delta.unsigned_abs());
}
}
/// Fetches the value of this U64Gauge
pub fn fetch(&self) -> u64 {
self.state.load(Ordering::Relaxed)
}
}
impl MetricObserver for U64Gauge {
type Recorder = Self;
fn kind() -> MetricKind {
MetricKind::U64Gauge
}
fn recorder(&self) -> Self::Recorder {
self.clone()
}
fn observe(&self) -> Observation {
Observation::U64Gauge(self.fetch())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gauge() {
let gauge = U64Gauge::default();
assert_eq!(gauge.observe(), Observation::U64Gauge(0));
gauge.set(345);
assert_eq!(gauge.observe(), Observation::U64Gauge(345));
gauge.set(23);
assert_eq!(gauge.observe(), Observation::U64Gauge(23));
gauge.inc(10);
assert_eq!(gauge.observe(), Observation::U64Gauge(33));
gauge.dec(10);
assert_eq!(gauge.observe(), Observation::U64Gauge(23));
gauge.delta(19);
assert_eq!(gauge.observe(), Observation::U64Gauge(42));
gauge.delta(-19);
assert_eq!(gauge.observe(), Observation::U64Gauge(23));
let r2 = gauge.recorder();
r2.set(34);
assert_eq!(gauge.observe(), Observation::U64Gauge(34));
std::mem::drop(r2);
assert_eq!(gauge.observe(), Observation::U64Gauge(34));
}
}
|
/*
* @lc app=leetcode id=8 lang=rust
*
* [8] String to Integer (atoi)
*/
// @lc code=start
impl Solution {
pub fn my_atoi(s: String) -> i32 {
let s = s.as_bytes();
let n = s.len();
let mut i = 0;
let mut sign: i64 = 1;
let mut num: i64 = 0;
while i < n && s[i] == b' ' {
i += 1;
}
if i < n && s[i] == b'+' {
i += 1;
} else if i < n && s[i] == b'-' {
sign = -1;
i += 1;
}
while i < n {
if s[i] >= b'0' && s[i] <= b'9' {
num = 10*num + (s[i]-b'0') as i64;
if sign == 1 && num > i32::max_value() as i64 {
num = i32::max_value() as i64;
break;
}
if sign == -1 && num > -(i32::min_value() as i64) {
num = -(i32::min_value() as i64);
break;
}
} else {
break;
}
i += 1;
}
(sign * num) as i32
}
}
// @lc code=end
|
//! Handle operands invariants.
use crate::ir::Operand::*;
use crate::ir::{self, DimMapScope, Statement};
use crate::search_space::choices::{Action, DimKind, DimMapping, Order};
use fxhash::FxHashSet;
use log::debug;
/// Adds an order action to `actions` for all reduction dimensions of
/// reductions that the instruction `inst_id` depends on, such that
/// the instruction is placed after the reduction dimensions. This
/// ensures that the reductions have finished before the instruction
/// executes.
///
/// Relevant reductions are those that are operands of instructions or
/// reductions whose results are used by `inst_id`. E.g., for the
/// following code,
///
/// @0[%1]: add(..., reduce(..., [%1]))
/// @1[%2]: mul(..., reduce(..., [%2]))
///
/// @2[%3]: add(@0[%3], @1[%3])
///
/// the dimensions `%1` and `%2` need to be placed before `@2`, since
/// `@2` uses the results of `@0` and `@1`, which are reduced over
/// `%1` and `%2`, respectively.
fn order_reduce_dims(fun: &ir::Function, inst_id: ir::InstId, actions: &mut Vec<Action>) {
let mut red_dim_set: FxHashSet<_> = Default::default();
let instr = fun.inst(inst_id);
// Collect reduction dimensions of reductions that are operands of
// instructions that this instruction depends on
for operand in instr.operands() {
match *operand {
Inst(op_inst_id, ..) | Reduce(op_inst_id, ..) => {
red_dim_set.extend(fun.inst(op_inst_id).iter_reduced_dims());
}
_ => {}
}
}
// Order reduction dimensions before this instruction
for &red_dim in red_dim_set.iter() {
let action = Action::Order(red_dim.into(), instr.stmt_id(), Order::BEFORE);
debug!(
"Adding action ordering reduction dimension before the using instruction: {:?}",
action
);
actions.push(action);
}
}
/// Generates actions to enforce operands invariants.
pub fn invariants(fun: &ir::Function, op: &ir::Operand, user: ir::StmtId) -> Vec<Action> {
match *op {
Int(..) | Float(..) | Param(..) | Addr(..) | Variable(..) => vec![],
Inst(src, _, ref dim_map, ref scope) => {
// Order dimensions in the dim map.
let order = Order::BEFORE | Order::MERGED;
let mut actions = Vec::new();
for &(lhs, rhs) in dim_map.iter() {
actions.push(Action::Order(lhs.into(), rhs.into(), order));
let mapping = match scope {
DimMapScope::Local => DimMapping::UNROLL_MAP,
DimMapScope::Thread => DimMapping::MAPPED,
DimMapScope::Global(..) => DimMapping::ALL,
};
actions.push(Action::DimMapping(lhs, rhs, mapping));
// FIXME: allow tmp mem with dynamic size when the scope is global.
if fun.dim(lhs).possible_sizes().is_none() {
actions.push(Action::Order(lhs.into(), rhs.into(), Order::MERGED));
}
}
order_reduce_dims(fun, src, &mut actions);
// Order the with the source instruction.
actions.push(Action::Order(src.into(), user, Order::BEFORE));
actions
}
Reduce(src, _, ref dim_map, ref reduce_dims) => {
let order = Order::BEFORE | Order::MERGED;
let mut actions = Vec::new();
// TODO(search_space): allow tmp mem to be generated for reduce dim maps.
for &(lhs, rhs) in dim_map.iter() {
actions.push(Action::Order(lhs.into(), rhs.into(), order));
actions.push(Action::DimMapping(lhs, rhs, DimMapping::MAPPED));
}
actions.push(Action::Order(src.into(), user, Order::BEFORE));
for &dim in reduce_dims {
actions.push(Action::Order(src.into(), dim.into(), Order::BEFORE));
actions.push(Action::DimKind(dim, DimKind::LOOP | DimKind::UNROLL));
}
order_reduce_dims(fun, src, &mut actions);
actions
}
Index(dim) => vec![Action::Order(dim.into(), user, Order::OUTER)],
InductionVar(var_id, _) => {
let var = fun.induction_var(var_id);
let mut actions = invariants(fun, var.base(), user);
for &(dim, _) in var.dims().iter() {
actions.extend(invariants(fun, var.base(), dim.into()));
actions.push(Action::Order(dim.into(), user, Order::OUTER));
}
actions
}
}
}
/// Generates the invariants of the operands of an instuction.
pub fn inst_invariants(fun: &ir::Function, inst: &ir::Instruction) -> Vec<Action> {
inst.operands()
.into_iter()
.flat_map(move |op| invariants(fun, op, inst.stmt_id()))
.collect()
}
|
/*
* Firecracker API
*
* RESTful public-facing API. The API is accessible through HTTP calls on specific URLs carrying JSON modeled data. The transport medium is a Unix Domain Socket.
*
* The version of the OpenAPI document: 0.25.0
* Contact: compute-capsule@amazon.com
* Generated by: https://openapi-generator.tech
*/
/// MachineConfiguration : Describes the number of vCPUs, memory size, Hyperthreading capabilities and the CPU template.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MachineConfiguration {
#[serde(rename = "cpu_template", skip_serializing_if = "Option::is_none")]
pub cpu_template: Option<crate::models::CpuTemplate>,
/// Flag for enabling/disabling Hyperthreading
#[serde(rename = "ht_enabled")]
pub ht_enabled: bool,
/// Memory size of VM
#[serde(rename = "mem_size_mib")]
pub mem_size_mib: i32,
/// Enable dirty page tracking. If this is enabled, then incremental guest memory snapshots can be created. These belong to diff snapshots, which contain, besides the microVM state, only the memory dirtied since a previous snapshot. Full snapshots each contain a full copy of the guest memory.
#[serde(rename = "track_dirty_pages", skip_serializing_if = "Option::is_none")]
pub track_dirty_pages: Option<bool>,
/// Number of vCPUs (either 1 or an even number)
#[serde(rename = "vcpu_count")]
pub vcpu_count: i32,
}
impl MachineConfiguration {
/// Describes the number of vCPUs, memory size, Hyperthreading capabilities and the CPU template.
pub fn new(ht_enabled: bool, mem_size_mib: i32, vcpu_count: i32) -> MachineConfiguration {
MachineConfiguration {
cpu_template: None,
ht_enabled,
mem_size_mib,
track_dirty_pages: None,
vcpu_count,
}
}
}
|
use std::{
fmt::Display,
sync::{Arc, Mutex},
};
use async_trait::async_trait;
use data_types::{ColumnSet, CompactionLevel, ParquetFileParams, Timestamp};
use datafusion::{
arrow::{datatypes::SchemaRef, record_batch::RecordBatch},
error::DataFusionError,
physical_plan::SendableRecordBatchStream,
};
use futures::TryStreamExt;
use iox_time::Time;
use uuid::Uuid;
use crate::partition_info::PartitionInfo;
use super::ParquetFileSink;
#[derive(Debug, Clone)]
pub struct StoredFile {
pub batches: Vec<RecordBatch>,
pub level: CompactionLevel,
pub partition: Arc<PartitionInfo>,
pub schema: SchemaRef,
}
#[derive(Debug)]
pub struct MockParquetFileSink {
filter_empty_files: bool,
records: Mutex<Vec<StoredFile>>,
}
impl MockParquetFileSink {
/// If filter_empty_files is true, parquet files that have "0" rows will not be written to `ParquetFile`s in the catalog.
#[cfg(test)]
pub fn new(filter_empty_files: bool) -> Self {
Self {
filter_empty_files,
records: Default::default(),
}
}
#[allow(dead_code)] // not used anywhere
pub fn records(&self) -> Vec<StoredFile> {
self.records.lock().expect("not poisoned").clone()
}
}
impl Display for MockParquetFileSink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "mock")
}
}
#[async_trait]
impl ParquetFileSink for MockParquetFileSink {
async fn store(
&self,
stream: SendableRecordBatchStream,
partition: Arc<PartitionInfo>,
level: CompactionLevel,
max_l0_created_at: Time,
) -> Result<Option<ParquetFileParams>, DataFusionError> {
let schema = stream.schema();
let batches: Vec<_> = stream.try_collect().await?;
let row_count = batches.iter().map(|b| b.num_rows()).sum::<usize>();
let mut guard = self.records.lock().expect("not poisoned");
let out = ((row_count > 0) || !self.filter_empty_files).then(|| ParquetFileParams {
namespace_id: partition.namespace_id,
table_id: partition.table.id,
partition_id: partition.partition_id(),
object_store_id: Uuid::from_u128(guard.len() as u128),
min_time: Timestamp::new(0),
max_time: Timestamp::new(0),
file_size_bytes: 1,
row_count: 1,
compaction_level: level,
created_at: Timestamp::new(1),
column_set: ColumnSet::new(vec![]),
max_l0_created_at: max_l0_created_at.into(),
});
guard.push(StoredFile {
batches,
level,
partition,
schema,
});
Ok(out)
}
}
#[cfg(test)]
mod tests {
use arrow_util::assert_batches_eq;
use data_types::{NamespaceId, TableId};
use datafusion::{
arrow::{array::new_null_array, datatypes::DataType},
physical_plan::stream::RecordBatchStreamAdapter,
};
use schema::SchemaBuilder;
use crate::test_utils::PartitionInfoBuilder;
use super::*;
#[test]
fn test_display() {
assert_eq!(MockParquetFileSink::new(false).to_string(), "mock");
}
#[tokio::test]
async fn test_store_filter_empty() {
let sink = MockParquetFileSink::new(true);
let schema = SchemaBuilder::new()
.field("f", DataType::Int64)
.unwrap()
.build()
.unwrap()
.as_arrow();
let partition = Arc::new(PartitionInfoBuilder::new().build());
let level = CompactionLevel::FileNonOverlapped;
let max_l0_created_at = Time::from_timestamp_nanos(1);
let stream = Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(&schema),
futures::stream::empty(),
));
assert_eq!(
sink.store(stream, Arc::clone(&partition), level, max_l0_created_at)
.await
.unwrap(),
None,
);
let record_batch = RecordBatch::new_empty(Arc::clone(&schema));
let record_batch_captured = record_batch.clone();
let stream = Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(&schema),
futures::stream::once(async move { Ok(record_batch_captured) }),
));
assert_eq!(
sink.store(stream, Arc::clone(&partition), level, max_l0_created_at)
.await
.unwrap(),
None,
);
let record_batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![new_null_array(&DataType::Int64, 1)],
)
.unwrap();
let record_batch_captured = record_batch.clone();
let stream = Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(&schema),
futures::stream::once(async move { Ok(record_batch_captured) }),
));
let partition_id = partition.partition_id();
assert_eq!(
sink.store(stream, Arc::clone(&partition), level, max_l0_created_at)
.await
.unwrap(),
Some(ParquetFileParams {
namespace_id: NamespaceId::new(2),
table_id: TableId::new(3),
partition_id,
object_store_id: Uuid::from_u128(2),
min_time: Timestamp::new(0),
max_time: Timestamp::new(0),
file_size_bytes: 1,
row_count: 1,
compaction_level: CompactionLevel::FileNonOverlapped,
created_at: Timestamp::new(1),
column_set: ColumnSet::new([]),
max_l0_created_at: max_l0_created_at.into(),
}),
);
let records = sink.records();
assert_eq!(records.len(), 3);
assert_eq!(records[0].batches.len(), 0);
assert_eq!(records[0].schema, schema);
assert_eq!(records[0].level, level);
assert_eq!(records[0].partition, partition);
assert_batches_eq!(["+---+", "| f |", "+---+", "+---+",], &records[1].batches);
assert_eq!(records[1].batches.len(), 1);
assert_eq!(records[1].schema, schema);
assert_eq!(records[1].level, level);
assert_eq!(records[1].partition, partition);
assert_batches_eq!(
["+---+", "| f |", "+---+", "| |", "+---+",],
&records[2].batches
);
assert_eq!(records[2].batches.len(), 1);
assert_eq!(records[2].schema, schema);
assert_eq!(records[2].level, level);
assert_eq!(records[2].partition, partition);
}
#[tokio::test]
async fn test_store_keep_empty() {
let sink = MockParquetFileSink::new(false);
let schema = SchemaBuilder::new()
.field("f", DataType::Int64)
.unwrap()
.build()
.unwrap()
.as_arrow();
let partition = Arc::new(PartitionInfoBuilder::new().build());
let level = CompactionLevel::FileNonOverlapped;
let max_l0_created_at = Time::from_timestamp_nanos(1);
let stream = Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(&schema),
futures::stream::empty(),
));
let partition_id = partition.partition_id();
assert_eq!(
sink.store(stream, Arc::clone(&partition), level, max_l0_created_at)
.await
.unwrap(),
Some(ParquetFileParams {
namespace_id: NamespaceId::new(2),
table_id: TableId::new(3),
partition_id,
object_store_id: Uuid::from_u128(0),
min_time: Timestamp::new(0),
max_time: Timestamp::new(0),
file_size_bytes: 1,
row_count: 1,
compaction_level: CompactionLevel::FileNonOverlapped,
created_at: Timestamp::new(1),
column_set: ColumnSet::new([]),
max_l0_created_at: max_l0_created_at.into(),
}),
);
let records = sink.records();
assert_eq!(records.len(), 1);
assert_eq!(records[0].batches.len(), 0);
assert_eq!(records[0].schema, schema);
assert_eq!(records[0].level, level);
assert_eq!(records[0].partition, partition);
}
}
|
struct Years(i64);
fn main() {
let years = Years(42);
let _years_as_primitive_1: i64 = years.0; // Tuple
let Years(years_as_primitive_2) = years; // Destructuring
println!("{}", years_as_primitive_2);
}
|
#[doc = r" Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Tasks asssociated with GPIOTE channels."]
pub tasks_out: [TASKS_OUT; 4],
_reserved0: [u8; 240usize],
#[doc = "0x100 - Tasks asssociated with GPIOTE channels."]
pub events_in: [EVENTS_IN; 4],
_reserved1: [u8; 108usize],
#[doc = "0x17c - Event generated from multiple pins."]
pub events_port: EVENTS_PORT,
_reserved2: [u8; 388usize],
#[doc = "0x304 - Interrupt enable set register."]
pub intenset: INTENSET,
#[doc = "0x308 - Interrupt enable clear register."]
pub intenclr: INTENCLR,
_reserved3: [u8; 516usize],
#[doc = "0x510 - Channel configuration registers."]
pub config: [CONFIG; 4],
}
#[doc = "Tasks asssociated with GPIOTE channels."]
pub struct TASKS_OUT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Tasks asssociated with GPIOTE channels."]
pub mod tasks_out;
#[doc = "Tasks asssociated with GPIOTE channels."]
pub struct EVENTS_IN {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Tasks asssociated with GPIOTE channels."]
pub mod events_in;
#[doc = "Event generated from multiple pins."]
pub struct EVENTS_PORT {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Event generated from multiple pins."]
pub mod events_port;
#[doc = "Interrupt enable set register."]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt enable set register."]
pub mod intenset;
#[doc = "Interrupt enable clear register."]
pub struct INTENCLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt enable clear register."]
pub mod intenclr;
#[doc = "Channel configuration registers."]
pub struct CONFIG {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Channel configuration registers."]
pub mod config;
|
use crate::Point;
pub trait Force {
fn apply(&self, points: &mut [Point], alpha: f32);
}
pub trait ForceToNode {
fn apply_to_node(&self, u: usize, points: &mut [Point], alpha: f32);
}
|
pub struct Plane {
pub data: Vec<u16>
}
|
pub mod parsemath;
|
//! Better migrations.
//!
//! # Why
//!
//! SQLx migrations don't work for us, see:
//!
//! - <https://github.com/launchbadge/sqlx/issues/2085>
//! - <https://github.com/influxdata/influxdb_iox/issues/5031>
//!
//! # Usage
//!
//! Just place your migration in the `migrations` folder. They basically work like normal SQLx migrations but there are
//! a few extra, magic comments you can put in your code to modify the behavior.
//!
//! ## Steps
//!
//! The entire SQL text will be executed as a single statement. However, you can split it into multiple steps by using
//! a marker:
//!
//! ```sql
//! CREATE TABLE t1 (x INT);
//!
//! -- IOX_STEP_BOUNDARY
//!
//! CREATE TABLE t2 (x INT);
//! ```
//!
//! ## Transactions & Idempotency
//!
//! All steps will be executed within one transaction. However, you can opt-out of this:
//!
//! ```sql
//! -- this step is wrapped in a transaction
//! CREATE TABLE t1 (x INT);
//!
//! -- IOX_STEP_BOUNDARY
//!
//! -- this step isn't
//! -- IOX_NO_TRANSACTION
//! CREATE TABLE t2 (x INT);
//! ```
//!
//! If all steps can be run in a transaction, the entire migration (including its bookkeeping) will be executed in a
//! transaction. In this case, the transaction is automatically idempotent.
//!
//! Migrations that opt out of the transaction handling MUST ensure that they are idempotent. This also includes that
//! they end up in the desired target state even if they were interrupted midway in a previous run.
//!
//! ## Updating / Fixing Migrations
//!
//! **⚠️ In general a migration MUST NOT be updated / changed after it was committed to `main`. ⚠️**
//!
//! However, there is one exception to this rule: if the new version has the same outcome when applied successfully.
//! This can be due to:
//!
//! - **Optimization:** The migration script turns out to be too slow in production workloads, but you find a better
//! version that does the same but runs faster.
//! - **Failure:** The script worked fine during testing but in prod it always fails, e.g. because it is missing NULL
//! handling. It is important to remember that the fix MUST NOT change the outcome of the successful runs.
//! - **Idempotency:** The script works only w/o transactions (see section above) and cannot be re-applied when
//! interrupted midway. One common case is `CREATE INDEX CONCURRENTLY ...` where you MUST drop the index beforehand
//! via `DROP INDEX IF EXISTS ...` because a previous interrupted migration might have left it in an invalid state.
//! See ["Building Indexes Concurrently"].
//!
//! If you are very sure that you found a fix for your migration that does the same operation, you still MUST NOT just
//! change the existing migration. The reason is that we keep a checksum of the migration stored in the database.
//! Changing the script will change the checksum, which will lead to a [failure](MigrateError::VersionMismatch) when
//! running the migrations. You can work around that by obtaining the old checksum (in hex) and adding it to the new
//! version as: `-- IOX_OTHER_CHECKSUM: 42feedbull`. This pragma can be repeated multiple times.
//!
//! ### Example
//!
//! If the old migration script looks like this:
//!
//! ```sql
//! -- IOX_NO_TRANSACTION
//! SET statement_timeout TO '60min';
//!
//! -- IOX_STEP_BOUNDARY
//!
//! -- IOX_NO_TRANSACTION
//! CREATE INDEX CONCURRENTLY IF NOT EXISTS i ON t (x);
//! ```
//!
//! You can fix the idempotency by creating a new migration that contains:
//!
//! ```sql
//! -- IOX_OTHER_CHECKSUM: 067431eaa74f26ee86200aaed4992a5fe22354322102f1ed795e424ec529469079569072d856e96ee9fdb6cc848b6137
//! -- IOX_NO_TRANSACTION
//! SET statement_timeout TO '60min';
//!
//! -- IOX_STEP_BOUNDARY
//! DROP INDEX CONCURRENTLY IF EXISTS i;
//!
//! -- IOX_NO_TRANSACTION
//!
//! -- IOX_STEP_BOUNDARY
//!
//! -- IOX_NO_TRANSACTION
//! CREATE INDEX CONCURRENTLY IF NOT EXISTS i ON t (x);
//! ```
//!
//! ## Non-SQL steps
//!
//! At the moment, we only support SQL-based migration steps, but other step types can easily be added.
//!
//! ["Building Indexes Concurrently"]: https://www.postgresql.org/docs/15/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
hash::{Hash, Hasher},
ops::Deref,
str::FromStr,
time::{Duration, Instant},
};
use async_trait::async_trait;
use observability_deps::tracing::{debug, info, warn};
use siphasher::sip::SipHasher13;
use sqlx::{
migrate::{Migrate, MigrateError, Migration, MigrationType, Migrator},
query, query_as, query_scalar, Acquire, Connection, Executor, PgConnection, Postgres,
Transaction,
};
/// A single [`IOxMigration`] step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IOxMigrationStep {
/// Execute a SQL statement.
///
/// A SQL statement MAY contain multiple sub-statements, e.g.:
///
/// ```sql
/// CREATE TABLE IF NOT EXISTS table1 (
/// id BIGINT GENERATED ALWAYS AS IDENTITY,
/// PRIMARY KEY (id),
/// );
///
/// CREATE TABLE IF NOT EXISTS table2 (
/// id BIGINT GENERATED ALWAYS AS IDENTITY,
/// PRIMARY KEY (id),
/// );
/// ```
SqlStatement {
/// The SQL text.
///
/// If [`in_transaction`](Self::SqlStatement::in_transaction) is set, this MUST NOT contain any transaction
/// modifiers like `COMMIT`/`ROLLBACK`/`BEGIN`!
sql: Cow<'static, str>,
/// Should the execution of the SQL text be wrapped into a transaction?
///
/// Whenever possible, you likely want to set this to `true`. However, some database changes like `CREATE INDEX
/// CONCURRENTLY` under PostgreSQL cannot be executed within a transaction.
in_transaction: bool,
},
}
impl IOxMigrationStep {
/// Apply migration step.
async fn apply<C>(&self, conn: &mut C) -> Result<(), MigrateError>
where
C: IOxMigrate,
{
match self {
Self::SqlStatement { sql, .. } => {
conn.exec(sql).await?;
}
}
Ok(())
}
/// Will this step set up a transaction if there is none yet?
fn in_transaction(&self) -> bool {
match self {
Self::SqlStatement { in_transaction, .. } => *in_transaction,
}
}
}
/// Migration checksum.
#[derive(Clone, PartialEq, Eq)]
pub struct Checksum(Box<[u8]>);
impl Checksum {
fn as_bytes(&self) -> &[u8] {
&self.0
}
}
impl std::fmt::Debug for Checksum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for b in self.0.iter() {
write!(f, "{:02x}", b)?;
}
Ok(())
}
}
impl std::fmt::Display for Checksum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl<const N: usize> From<[u8; N]> for Checksum {
fn from(value: [u8; N]) -> Self {
Self(value.into())
}
}
impl From<&[u8]> for Checksum {
fn from(value: &[u8]) -> Self {
Self(value.into())
}
}
impl FromStr for Checksum {
type Err = MigrateError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let inner = (0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..(i + 2).min(s.len())], 16))
.collect::<Result<Box<[u8]>, _>>()
.map_err(|e| {
MigrateError::Source(format!("cannot parse checksum '{s}': {e}").into())
})?;
Ok(Self(inner))
}
}
/// Database migration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IOxMigration {
/// Version.
///
/// This is used to order migrations.
pub version: i64,
/// Human-readable description.
pub description: Cow<'static, str>,
/// Steps that compose this migration.
///
/// In most cases you want a single [SQL step](IOxMigrationStep::SqlStatement) which is executed
/// [in a transaction](IOxMigrationStep::SqlStatement::in_transaction).
pub steps: Box<[IOxMigrationStep]>,
/// Checksum of the given steps.
pub checksum: Checksum,
/// Checksums of other versions of this migration that are known to be compatible.
///
/// **Using this should be a rare exception!**
///
/// This can be used to convert a non-idempotent migration into an idempotent one.
pub other_compatible_checksums: Box<[Checksum]>,
}
impl IOxMigration {
/// Apply migration and return elapsed wall-clock time (measured locally).
async fn apply<C>(&self, conn: &mut C) -> Result<Duration, MigrateError>
where
C: IOxMigrate,
{
let single_transaction = self.single_transaction();
info!(
version = self.version,
description = self.description.as_ref(),
steps = self.steps.len(),
single_transaction,
"applying migration"
);
let elapsed = if single_transaction {
let mut txn = conn.begin_txn().await?;
let elapsed = {
let conn = txn.acquire_conn().await?;
self.apply_inner(conn, true).await?
};
txn.commit_txn().await?;
elapsed
} else {
self.apply_inner(conn, false).await?
};
info!(
version = self.version,
description = self.description.as_ref(),
steps = self.steps.len(),
elapsed_secs = elapsed.as_secs_f64(),
"migration applied"
);
Ok(elapsed)
}
/// Run actual application of the migration.
///
/// This may or may NOT be guarded by a transaction block.
async fn apply_inner<C>(&self, conn: &mut C, single_txn: bool) -> Result<Duration, MigrateError>
where
C: IOxMigrate,
{
let start = Instant::now();
conn.start_migration(self).await?;
for (i, step) in self.steps.iter().enumerate() {
info!(
version = self.version,
steps = self.steps.len(),
step = i + 1,
single_txn,
in_transaction = step.in_transaction(),
"applying migration step"
);
if step.in_transaction() && !single_txn {
let mut txn = conn.begin_txn().await?;
{
let conn = txn.acquire_conn().await?;
step.apply(conn).await?;
}
txn.commit_txn().await?;
} else {
step.apply(conn).await?;
}
info!(
version = self.version,
steps = self.steps.len(),
step = i + 1,
"applied migration step"
);
}
let elapsed = start.elapsed();
conn.run_sanity_checks().await?;
conn.finish_migration(self, elapsed).await?;
Ok(elapsed)
}
/// This migration can be run in a single transaction and will never be dirty.
pub fn single_transaction(&self) -> bool {
self.steps.iter().all(|s| s.in_transaction())
}
}
impl TryFrom<&Migration> for IOxMigration {
type Error = MigrateError;
fn try_from(migration: &Migration) -> Result<Self, Self::Error> {
if migration.migration_type != MigrationType::Simple {
return Err(MigrateError::Source(
format!(
"migration type has to be simple but is {:?}",
migration.migration_type
)
.into(),
));
}
let other_compatible_checksums = migration
.sql
.lines()
.filter_map(|s| {
s.strip_prefix("-- IOX_OTHER_CHECKSUM:")
.map(|s| s.trim().parse())
})
.collect::<Result<_, _>>()?;
let steps = migration
.sql
.split("-- IOX_STEP_BOUNDARY")
.map(|sql| {
let sql = sql.trim().to_owned();
let in_transaction = !sql.contains("IOX_NO_TRANSACTION");
IOxMigrationStep::SqlStatement {
sql: sql.into(),
in_transaction,
}
})
.collect();
Ok(Self {
version: migration.version,
description: migration.description.clone(),
steps,
// Keep original (unprocessed) checksum for backwards compatibility.
checksum: migration.checksum.deref().into(),
other_compatible_checksums,
})
}
}
/// Migration manager.
#[derive(Debug, PartialEq, Eq)]
pub struct IOxMigrator {
/// List of migrations.
migrations: Vec<IOxMigration>,
}
impl IOxMigrator {
/// Create new migrator.
///
/// # Error
/// Fails if migrations are not sorted or if there are duplicate [versions](IOxMigration::version).
pub fn try_new(
migrations: impl IntoIterator<Item = IOxMigration>,
) -> Result<Self, MigrateError> {
let migrations = migrations.into_iter().collect::<Vec<_>>();
if let Some(m) = migrations.windows(2).find(|m| m[0].version > m[1].version) {
return Err(MigrateError::Source(
format!(
"migrations are not sorted: version {} is before {} but should not be",
m[0].version, m[1].version,
)
.into(),
));
}
if let Some(m) = migrations.windows(2).find(|m| m[0].version == m[1].version) {
return Err(MigrateError::Source(
format!(
"migrations are not unique: version {} found twice",
m[0].version,
)
.into(),
));
}
Ok(Self { migrations })
}
/// Run migrator on connection/pool.
///
/// Returns set of executed [migrations](IOxMigration).
///
/// This may fail and some migrations may be applied. Also, it is possible that a migration itself fails half-way,
/// in which case it is marked as dirty. Subsequent migrations will fail until the issue is resolved.
pub async fn run<'a, A>(&self, migrator: A) -> Result<HashSet<i64>, MigrateError>
where
A: Acquire<'a> + Send,
<A::Connection as Deref>::Target: IOxMigrate,
{
let mut conn = migrator.acquire().await?;
self.run_direct(&mut *conn).await
}
/// Run migrator on open connection.
///
/// See docs for [run](Self::run).
async fn run_direct<C>(&self, conn: &mut C) -> Result<HashSet<i64>, MigrateError>
where
C: IOxMigrate,
{
let lock_id = conn.generate_lock_id().await?;
<C as IOxMigrate>::lock(conn, lock_id).await?;
let run_res = self.run_inner(conn).await;
// always try to unlock, even when we failed.
// While PG is timing out the lock, unlocking manually will give others the chance to re-lock faster. This is
// mostly relevant for tests where we re-use connections.
let unlock_res = <C as IOxMigrate>::unlock(conn, lock_id).await;
// return first error but also first OK (there doesn't seem to be an stdlib method for this)
match (run_res, unlock_res) {
(Err(e), _) => Err(e),
(Ok(_), Err(e)) => Err(e),
(Ok(res), Ok(())) => Ok(res),
}
}
/// Run migrator.
///
/// This expects that locking was already done.
async fn run_inner<C>(&self, conn: &mut C) -> Result<HashSet<i64>, MigrateError>
where
C: IOxMigrate,
{
// creates [_migrations] table only if needed
// eventually this will likely migrate previous versions of the table
conn.ensure_migrations_table().await?;
let applied_migrations = <C as IOxMigrate>::list_applied_migrations(conn).await?;
validate_applied_migrations(&applied_migrations, self)?;
let applied_and_not_dirty: HashSet<_> = applied_migrations
.into_iter()
.filter(|m| !m.dirty)
.map(|m| m.version)
.collect();
let mut new_migrations = HashSet::new();
for migration in &self.migrations {
if applied_and_not_dirty.contains(&migration.version) {
continue;
}
migration.apply(conn).await?;
new_migrations.insert(migration.version);
}
Ok(new_migrations)
}
}
impl TryFrom<&Migrator> for IOxMigrator {
type Error = MigrateError;
fn try_from(migrator: &Migrator) -> Result<Self, Self::Error> {
if migrator.ignore_missing {
return Err(MigrateError::Source(
"`Migrator::ignore_missing` MUST NOT be set"
.to_owned()
.into(),
));
}
if !migrator.locking {
return Err(MigrateError::Source(
"`Migrator::locking` MUST be set".to_owned().into(),
));
}
let migrations = migrator
.migrations
.iter()
.map(|migration| migration.try_into())
.collect::<Result<Vec<_>, _>>()?;
Self::try_new(migrations)
}
}
/// Validate an already-applied migration.
///
/// Checks that:
///
/// - applied migration is known
/// - checksum of applied migration and known migration match
/// - new migrations are newer than both the successfully applied and the dirty version
/// - there is at most one dirty migration (bug check)
/// - the dirty migration is the last applied one (bug check)
fn validate_applied_migrations(
applied_migrations: &[IOxAppliedMigration],
migrator: &IOxMigrator,
) -> Result<(), MigrateError> {
let migrations: HashMap<_, _> = migrator.migrations.iter().map(|m| (m.version, m)).collect();
for applied_migration in applied_migrations {
match migrations.get(&applied_migration.version) {
None => {
return Err(MigrateError::VersionMissing(applied_migration.version));
}
Some(migration) => {
if !std::iter::once(&migration.checksum)
.chain(migration.other_compatible_checksums.iter())
.any(|cs| cs.as_bytes() == applied_migration.checksum.deref())
{
return Err(MigrateError::VersionMismatch(migration.version));
}
if applied_migration.dirty {
warn!(
version = migration.version,
"found dirty migration, trying to recover"
);
}
}
}
}
let dirty_versions = applied_migrations
.iter()
.filter(|m| m.dirty)
.map(|m| m.version)
.collect::<Vec<_>>();
if dirty_versions.len() > 1 {
return Err(MigrateError::Source(format!(
"there are multiple dirty versions, this should not happen and is considered a bug: {:?}",
dirty_versions,
).into()));
}
let dirty_version = dirty_versions.into_iter().next();
let applied_last = applied_migrations
.iter()
.filter(|m| Some(m.version) != dirty_version)
.map(|m| m.version)
.max();
if let (Some(applied_last), Some(dirty_version)) = (applied_last, dirty_version) {
// algorithm error in this method, use an assertion
assert_ne!(applied_last, dirty_version);
if applied_last > dirty_version {
// database state error, so use a proper error
return Err(MigrateError::Source(format!(
"dirty version ({dirty_version}) is not the last applied version ({applied_last}), this is a bug",
).into()));
}
}
let applied_set = applied_migrations
.iter()
.map(|m| m.version)
.collect::<HashSet<_>>();
let new_first = migrator
.migrations
.iter()
.filter(|m| !applied_set.contains(&m.version))
.map(|m| m.version)
.min();
if let (Some(dirty_version), Some(new_first)) = (dirty_version, new_first) {
// algorithm error in this method, use an assertion
assert_ne!(dirty_version, new_first);
if dirty_version > new_first {
// database state error, so use a proper error
return Err(MigrateError::Source(
format!(
"new migration ({new_first}) goes before dirty version ({dirty_version}), \
this should not have been merged!",
)
.into(),
));
}
}
if let (Some(applied_last), Some(new_first)) = (applied_last, new_first) {
// algorithm error in this method, use an assertion
assert_ne!(applied_last, new_first);
if applied_last > new_first {
// database state error, so use a proper error
return Err(MigrateError::Source(
format!(
"new migration ({new_first}) goes before last applied migration ({applied_last}), \
this should not have been merged!",
)
.into(),
));
}
}
Ok(())
}
/// Information about a migration found in the database.
#[derive(Debug)]
pub struct IOxAppliedMigration {
/// Version of the migration.
pub version: i64,
/// Checksum.
pub checksum: Cow<'static, [u8]>,
/// Dirty flag.
///
/// If this is set, then the migration was interrupted midway.
pub dirty: bool,
}
/// Transaction type linked to [`IOxMigrate`].
///
/// This is a separate type because we need to own the transaction object at some point before handing out mutable
/// borrows to the actual connection again.
#[async_trait]
pub trait IOxMigrateTxn: Send {
/// The migration interface.
type M: IOxMigrate;
/// Acquire connection.
async fn acquire_conn(&mut self) -> Result<&mut Self::M, MigrateError>;
/// Commit transaction.
async fn commit_txn(self) -> Result<(), MigrateError>;
}
/// Interface of a specific database implementation (like Postgres) and the IOx migration system.
///
/// This mostly delegates to the SQLx [`Migrate`] interface but also has some extra methods.
#[async_trait]
pub trait IOxMigrate: Connection + Migrate + Send {
/// Transaction type.
type Txn<'a>: IOxMigrateTxn
where
Self: 'a;
/// Start new transaction.
async fn begin_txn<'a>(&'a mut self) -> Result<Self::Txn<'a>, MigrateError>;
/// Generate a lock ID that is used for [`lock`](Self::lock) and [`unlock`](Self::unlock).
async fn generate_lock_id(&mut self) -> Result<i64, MigrateError>;
/// Lock database for migrations.
async fn lock(&mut self, lock_id: i64) -> Result<(), MigrateError>;
/// Unlock database after migration.
async fn unlock(&mut self, lock_id: i64) -> Result<(), MigrateError>;
/// Get list of applied migrations.
async fn list_applied_migrations(&mut self) -> Result<Vec<IOxAppliedMigration>, MigrateError>;
/// Start a migration and mark it as "not finished".
async fn start_migration(&mut self, migration: &IOxMigration) -> Result<(), MigrateError>;
/// Finish a migration and register the elapsed time.
async fn finish_migration(
&mut self,
migration: &IOxMigration,
elapsed: Duration,
) -> Result<(), MigrateError>;
/// Execute a SQL statement (that may contain multiple sub-statements)
async fn exec(&mut self, sql: &str) -> Result<(), MigrateError>;
/// Run DB-specific sanity checks on the schema.
///
/// This mostly includes checks for "validity" markers (e.g. for indices).
async fn run_sanity_checks(&mut self) -> Result<(), MigrateError>;
}
#[async_trait]
impl<'a> IOxMigrateTxn for Transaction<'a, Postgres> {
type M = PgConnection;
async fn acquire_conn(&mut self) -> Result<&mut Self::M, MigrateError> {
let conn = self.acquire().await?;
Ok(conn)
}
async fn commit_txn(self) -> Result<(), MigrateError> {
self.commit().await?;
Ok(())
}
}
#[async_trait]
impl IOxMigrate for PgConnection {
type Txn<'a> = Transaction<'a, Postgres>;
async fn begin_txn<'a>(&'a mut self) -> Result<Self::Txn<'a>, MigrateError> {
let txn = <Self as Connection>::begin(self).await?;
Ok(txn)
}
async fn generate_lock_id(&mut self) -> Result<i64, MigrateError> {
let db: String = query_scalar("SELECT current_database()")
.fetch_one(self)
.await?;
// A randomly generated static siphash key to ensure all migrations use the same locks.
//
// Generated with: xxd -i -l 16 /dev/urandom
let key = [
0xb8, 0x52, 0x81, 0x3c, 0x12, 0x83, 0x6f, 0xd9, 0x00, 0x4f, 0xe7, 0xe3, 0x61, 0xbd,
0x03, 0xaf,
];
let mut hasher = SipHasher13::new_with_key(&key);
db.hash(&mut hasher);
Ok(i64::from_ne_bytes(hasher.finish().to_ne_bytes()))
}
async fn lock(&mut self, lock_id: i64) -> Result<(), MigrateError> {
loop {
let is_locked: bool = query_scalar("SELECT pg_try_advisory_lock($1)")
.bind(lock_id)
.fetch_one(&mut *self)
.await?;
if is_locked {
return Ok(());
}
let t_wait = Duration::from_millis(20);
debug!(
lock_id,
t_wait_millis = t_wait.as_millis(),
"lock held, waiting"
);
tokio::time::sleep(t_wait).await;
}
}
async fn unlock(&mut self, lock_id: i64) -> Result<(), MigrateError> {
let was_locked: bool = query_scalar("SELECT pg_advisory_unlock($1)")
.bind(lock_id)
.fetch_one(self)
.await?;
if !was_locked {
return Err(MigrateError::Source(
format!("did not own lock: {lock_id}").into(),
));
}
Ok(())
}
async fn list_applied_migrations(&mut self) -> Result<Vec<IOxAppliedMigration>, MigrateError> {
let rows: Vec<(i64, Vec<u8>, bool)> = query_as(
"SELECT version, checksum, NOT success FROM _sqlx_migrations ORDER BY version",
)
.fetch_all(self)
.await?;
let migrations = rows
.into_iter()
.map(|(version, checksum, dirty)| IOxAppliedMigration {
version,
checksum: checksum.into(),
dirty,
})
.collect();
Ok(migrations)
}
async fn start_migration(&mut self, migration: &IOxMigration) -> Result<(), MigrateError> {
let _ = query(
r#"
INSERT INTO _sqlx_migrations ( version, description, success, checksum, execution_time )
VALUES ( $1, $2, FALSE, $3, -1 )
ON CONFLICT (version)
DO NOTHING
"#,
)
.bind(migration.version)
.bind(&*migration.description)
.bind(migration.checksum.as_bytes())
.execute(self)
.await?;
Ok(())
}
async fn finish_migration(
&mut self,
migration: &IOxMigration,
elapsed: Duration,
) -> Result<(), MigrateError> {
let _ = query(
r#"
UPDATE _sqlx_migrations
SET success = TRUE, execution_time = $1
WHERE version = $2
"#,
)
.bind(elapsed.as_nanos() as i64)
.bind(migration.version)
.execute(self)
.await?;
Ok(())
}
async fn exec(&mut self, sql: &str) -> Result<(), MigrateError> {
let _ = self.execute(sql).await?;
Ok(())
}
async fn run_sanity_checks(&mut self) -> Result<(), MigrateError> {
let dirty_indices: Vec<String> = query_scalar(
r#"
SELECT pg_class.relname
FROM pg_index
JOIN pg_class ON pg_index.indexrelid = pg_class.oid
JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
WHERE pg_namespace.nspname = current_schema() AND NOT pg_index.indisvalid
ORDER BY pg_class.relname
"#,
)
.fetch_all(self)
.await?;
if !dirty_indices.is_empty() {
return Err(MigrateError::Source(
format!("Found invalid indexes: {}", dirty_indices.join(", ")).into(),
));
}
Ok(())
}
}
/// Testing tools for migrations.
#[cfg(test)]
pub mod test_utils {
use super::*;
use std::future::Future;
/// Test migration.
///
/// This runs the migrations to check if they pass. The given factory must provide an empty schema (i.e. w/o any
/// migrations applied).
///
/// # Tests
///
/// This tests that:
///
/// - **run once:** All migrations work when ran once.
/// - **idempotency:** Migrations marked as [`idempotent`](IOxMigration::idempotent) can be executed twice.
///
/// # Error
///
/// Fails if this finds a bug.
pub async fn test_migration<Factory, FactoryFut, Pool>(
migrator: &IOxMigrator,
factory: Factory,
) -> Result<(), MigrateError>
where
Factory: (Fn() -> FactoryFut) + Send + Sync,
FactoryFut: Future<Output = Pool> + Send,
Pool: Send,
for<'a> &'a Pool: Acquire<'a> + Send,
for<'a> <<&'a Pool as Acquire<'a>>::Connection as Deref>::Target: IOxMigrate,
{
{
info!("test: run all migrations");
let conn = factory().await;
let applied = migrator.run(&conn).await?;
assert_eq!(applied.len(), migrator.migrations.len());
}
info!("interrupt non-transaction migrations");
for (idx_m, m) in migrator.migrations.iter().enumerate() {
if m.single_transaction() {
info!(
version = m.version,
"skip migration because single transaction property"
);
continue;
}
let steps = m.steps.len();
info!(
version = m.version,
steps, "found non-transactional migration"
);
for step in 1..(steps + 1) {
info!(version = m.version, steps, step, "test: die after step");
let broken_cmd = "iox_this_is_a_broken_test_cmd";
let migrator_broken = IOxMigrator::try_new(
migrator
.migrations
.iter()
.take(idx_m)
.cloned()
.chain(std::iter::once(IOxMigration {
steps: m
.steps
.iter()
.take(step)
.cloned()
.chain(std::iter::once(IOxMigrationStep::SqlStatement {
sql: broken_cmd.into(),
in_transaction: false,
}))
.collect(),
..m.clone()
})),
)
.expect("bug in test");
let conn = factory().await;
let err = migrator_broken.run(&conn).await.unwrap_err();
if !err.to_string().contains(broken_cmd) {
panic!("migrator broke in expected way, bug in test setup: {err}");
}
info!(
version = m.version,
steps, step, "test: die after step, recover from error"
);
let applied = migrator.run(&conn).await?;
assert!(applied.contains(&m.version));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
mod generic {
use super::*;
use proptest::prelude::*;
proptest! {
#[test]
fn test_checksum_string_roundtrip(s: Vec<u8>) {
let checksum_1 = Checksum::from(s.as_slice());
let string_1 = checksum_1.to_string();
let checksum_2 = Checksum::from_str(&string_1).unwrap();
let string_2 = checksum_2.to_string();
assert_eq!(checksum_1, checksum_2);
assert_eq!(string_1, string_2);
}
}
#[test]
fn test_parse_valid_checksum() {
let actual = Checksum::from_str(
"b88c635e27f8b9ba8547b24efcb081429a8f3e85b70f35916e1900dffc4e6a77eed8a02acc7c72526dd7d50166b63fbd"
).unwrap();
let expected = Checksum::from([
184, 140, 99, 94, 39, 248, 185, 186, 133, 71, 178, 78, 252, 176, 129, 66, 154, 143,
62, 133, 183, 15, 53, 145, 110, 25, 0, 223, 252, 78, 106, 119, 238, 216, 160, 42,
204, 124, 114, 82, 109, 215, 213, 1, 102, 182, 63, 189,
]);
assert_eq!(actual, expected);
}
#[test]
fn test_parse_invalid_checksum() {
let err = Checksum::from_str("foo").unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: cannot parse checksum 'foo': invalid digit found in string",
);
}
#[test]
fn test_migrator_new_error_not_sorted() {
let err = IOxMigrator::try_new([
IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
},
])
.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: migrations are not sorted: version 2 is before 1 but should not be",
);
}
#[test]
fn test_migrator_new_error_not_unique() {
let err = IOxMigrator::try_new([
IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
},
])
.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: migrations are not unique: version 2 found twice",
);
}
#[test]
fn test_convert_migrator_from_sqlx_error_no_locking() {
let err = IOxMigrator::try_from(&Migrator {
migrations: vec![].into(),
ignore_missing: false,
locking: false,
})
.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: `Migrator::locking` MUST be set",
);
}
#[test]
fn test_convert_migrator_from_sqlx_error_ignore_missing() {
let err = IOxMigrator::try_from(&Migrator {
migrations: vec![].into(),
ignore_missing: true,
locking: true,
})
.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: `Migrator::ignore_missing` MUST NOT be set",
);
}
#[test]
fn test_convert_migrator_from_sqlx_error_invalid_migration_type_rev_up() {
let err = IOxMigrator::try_from(&Migrator {
migrations: vec![Migration {
version: 1,
description: "".into(),
migration_type: MigrationType::ReversibleUp,
sql: "".into(),
checksum: vec![].into(),
}]
.into(),
ignore_missing: false,
locking: true,
})
.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: migration type has to be simple but is ReversibleUp",
);
}
#[test]
fn test_convert_migrator_from_sqlx_error_invalid_migration_type_rev_down() {
let err = IOxMigrator::try_from(&Migrator {
migrations: vec![Migration {
version: 1,
description: "".into(),
migration_type: MigrationType::ReversibleDown,
sql: "".into(),
checksum: vec![].into(),
}]
.into(),
ignore_missing: false,
locking: true,
})
.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: migration type has to be simple but is ReversibleDown",
);
}
#[test]
fn test_convert_migrator_from_sqlx_error_invalid_other_compatible_checksum() {
let err = IOxMigrator::try_from(&Migrator {
migrations: vec![Migration {
version: 1,
description: "".into(),
migration_type: MigrationType::Simple,
sql: "-- IOX_OTHER_CHECKSUM: foo".into(),
checksum: vec![].into(),
}]
.into(),
ignore_missing: false,
locking: true,
})
.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: cannot parse checksum 'foo': invalid digit found in string",
);
}
#[test]
fn test_convert_migrator_from_sqlx_ok() {
let actual = IOxMigrator::try_from(&Migrator {
migrations: vec![
Migration {
version: 1,
description: "some descr".into(),
migration_type: MigrationType::Simple,
sql: "SELECT 1;".into(),
checksum: vec![1, 2, 3].into(),
},
Migration {
version: 10,
description: "more descr".into(),
migration_type: MigrationType::Simple,
sql: "SELECT 2;\n-- IOX_STEP_BOUNDARY\n-- IOX_NO_TRANSACTION\nSELECT 3;"
.into(),
checksum: vec![4, 5, 6].into(),
},
Migration {
version: 11,
description: "xxx".into(),
migration_type: MigrationType::Simple,
sql: "-- IOX_OTHER_CHECKSUM:1ff\n-- IOX_OTHER_CHECKSUM: 2ff \nSELECT4;"
.into(),
checksum: vec![7, 8, 9].into(),
},
]
.into(),
ignore_missing: false,
locking: true,
})
.unwrap();
let expected = IOxMigrator {
migrations: vec![
IOxMigration {
version: 1,
description: "some descr".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "SELECT 1;".into(),
in_transaction: true,
}]
.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 10,
description: "more descr".into(),
steps: [
IOxMigrationStep::SqlStatement {
sql: "SELECT 2;".into(),
in_transaction: true,
},
IOxMigrationStep::SqlStatement {
sql: "-- IOX_NO_TRANSACTION\nSELECT 3;".into(),
in_transaction: false,
},
]
.into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 11,
description: "xxx".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "-- IOX_OTHER_CHECKSUM:1ff\n-- IOX_OTHER_CHECKSUM: 2ff \nSELECT4;".into(),
in_transaction: true,
}]
.into(),
checksum: [7, 8, 9].into(),
other_compatible_checksums: [
Checksum::from_str("1ff").unwrap(),
Checksum::from_str("2ff").unwrap(),
].into(),
},
],
};
assert_eq!(actual, expected);
}
}
mod postgres {
use std::sync::Arc;
use futures::{stream::FuturesUnordered, StreamExt};
use sqlx::{pool::PoolConnection, Postgres};
use sqlx_hotswap_pool::HotSwapPool;
use test_helpers::maybe_start_logging;
use crate::postgres::test_utils::{maybe_skip_integration, setup_db_no_migration};
use super::*;
#[tokio::test]
async fn test_lock_id_deterministic() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let first = conn.generate_lock_id().await.unwrap();
let second = conn.generate_lock_id().await.unwrap();
assert_eq!(first, second);
}
#[tokio::test]
async fn test_lock_unlock_twice() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let lock_id = conn.generate_lock_id().await.unwrap();
<PgConnection as IOxMigrate>::lock(conn, lock_id)
.await
.unwrap();
<PgConnection as IOxMigrate>::unlock(conn, lock_id)
.await
.unwrap();
<PgConnection as IOxMigrate>::lock(conn, lock_id)
.await
.unwrap();
<PgConnection as IOxMigrate>::unlock(conn, lock_id)
.await
.unwrap();
}
#[tokio::test]
async fn test_lock_prevents_2nd_lock() {
maybe_skip_integration!();
let pool = setup_pool().await;
let mut conn1 = pool.acquire().await.unwrap();
let conn1 = &mut *conn1;
let mut conn2 = pool.acquire().await.unwrap();
let conn2 = &mut *conn2;
let lock_id = conn1.generate_lock_id().await.unwrap();
<PgConnection as IOxMigrate>::lock(conn1, lock_id)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(1), async {
<PgConnection as IOxMigrate>::lock(conn2, lock_id)
.await
.unwrap();
})
.await
.unwrap_err();
<PgConnection as IOxMigrate>::unlock(conn1, lock_id)
.await
.unwrap();
<PgConnection as IOxMigrate>::lock(conn2, lock_id)
.await
.unwrap();
<PgConnection as IOxMigrate>::unlock(conn2, lock_id)
.await
.unwrap();
}
#[tokio::test]
async fn test_locks_are_scoped() {
maybe_skip_integration!();
let pool = setup_pool().await;
let mut conn1 = pool.acquire().await.unwrap();
let conn1 = &mut *conn1;
let mut conn2 = pool.acquire().await.unwrap();
let conn2 = &mut *conn2;
let lock_id1 = conn1.generate_lock_id().await.unwrap();
let lock_id2 = !lock_id1;
<PgConnection as IOxMigrate>::lock(conn1, lock_id1)
.await
.unwrap();
<PgConnection as IOxMigrate>::lock(conn1, lock_id2)
.await
.unwrap();
<PgConnection as IOxMigrate>::unlock(conn1, lock_id1)
.await
.unwrap();
// id2 is still lock (i.e. unlock is also scoped)
tokio::time::timeout(Duration::from_secs(1), async {
<PgConnection as IOxMigrate>::lock(conn2, lock_id2)
.await
.unwrap();
})
.await
.unwrap_err();
<PgConnection as IOxMigrate>::unlock(conn1, lock_id2)
.await
.unwrap();
}
#[tokio::test]
async fn test_unlock_without_lock_fails() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let lock_id = conn.generate_lock_id().await.unwrap();
let err = <PgConnection as IOxMigrate>::unlock(conn, lock_id)
.await
.unwrap_err();
assert_starts_with(
&err.to_string(),
"while resolving migrations: did not own lock:",
);
}
#[tokio::test]
async fn test_step_sql_statement_no_transaction() {
maybe_skip_integration!();
for in_transaction in [false, true] {
println!("in_transaction: {in_transaction}");
let mut conn = setup().await;
let conn = &mut *conn;
conn.execute("CREATE TABLE t (x INT);").await.unwrap();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "CREATE INDEX CONCURRENTLY i ON t (x);".into(),
in_transaction,
}]
.into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let res = migrator.run_direct(conn).await;
match in_transaction {
false => {
assert_eq!(res.unwrap(), HashSet::from([1]),);
}
true => {
// `CREATE INDEX CONCURRENTLY` is NOT possible w/ a transaction. Verify that.
assert_eq!(
res.unwrap_err().to_string(),
"while executing migrations: error returned from database: \
CREATE INDEX CONCURRENTLY cannot run inside a transaction block",
);
}
}
}
}
#[tokio::test]
async fn test_migrator_happy_path() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([
IOxMigration {
version: 1,
description: "".into(),
steps: [
IOxMigrationStep::SqlStatement {
sql: "CREATE TABLE t (x INT);".into(),
in_transaction: false,
},
IOxMigrationStep::SqlStatement {
sql: "INSERT INTO t (x) VALUES (1); INSERT INTO t (x) VALUES (10);"
.into(),
in_transaction: true,
},
]
.into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 2,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "INSERT INTO t (x) VALUES (100);".into(),
in_transaction: true,
}]
.into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
},
])
.unwrap();
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(applied, HashSet::from([1, 2]));
let r: i32 = query_scalar("SELECT SUM(x)::INT AS r FROM t;")
.fetch_one(conn)
.await
.unwrap();
assert_eq!(r, 111);
}
#[tokio::test]
async fn test_migrator_only_apply_new_migrations() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
// NOT idempotent!
sql: "CREATE TABLE t (x INT);".into(),
in_transaction: false,
}]
.into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(applied, HashSet::from([1]));
let migrator = IOxMigrator::try_new(
migrator.migrations.iter().cloned().chain([IOxMigration {
version: 2,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
// NOT idempotent!
sql: "CREATE TABLE s (x INT);".into(),
in_transaction: false,
}]
.into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}]),
)
.unwrap();
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(applied, HashSet::from([2]));
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(applied, HashSet::from([]));
}
#[tokio::test]
async fn test_migrator_fail_clean_migration_missing() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"migration 1 was previously applied but is missing in the resolved migrations"
);
}
#[tokio::test]
async fn test_migrator_fail_dirty_migration_missing() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "foo".into(),
in_transaction: false,
}]
.into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap_err();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"migration 1 was previously applied but is missing in the resolved migrations"
);
}
#[tokio::test]
async fn test_migrator_fail_clean_checksum_mismatch() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"migration 1 was previously applied but has been modified"
);
}
#[tokio::test]
async fn test_migrator_fail_dirty_checksum_mismatch() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "foo".into(),
in_transaction: false,
}]
.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap_err();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "foo".into(),
in_transaction: false,
}]
.into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"migration 1 was previously applied but has been modified"
);
}
#[tokio::test]
async fn test_migrator_other_compatible_checksum() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [[1, 2, 3].into()].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap();
}
/// Migrations may have the same checksum.
///
/// This is helpful if you want to revert a change later, e.g.:
///
/// 1. add a index
/// 2. remove the index
/// 3. decide that you actually need the index again
#[tokio::test]
async fn test_migrator_migrations_can_have_same_checksum() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([
IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
},
])
.unwrap();
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(applied, HashSet::from([1, 2]));
}
#[tokio::test]
async fn test_migrator_recover_dirty_same() {
test_migrator_recover_dirty_inner(RecoverFromDirtyMode::Same).await;
}
#[tokio::test]
async fn test_migrator_recover_dirty_fix_non_transactional() {
test_migrator_recover_dirty_inner(RecoverFromDirtyMode::FixNonTransactional).await;
}
#[tokio::test]
async fn test_migrator_recover_dirty_fix_transactional() {
test_migrator_recover_dirty_inner(RecoverFromDirtyMode::FixTransactional).await;
}
/// Modes for [`test_migrator_recover_dirty_inner`]
#[derive(Debug)]
enum RecoverFromDirtyMode {
/// Recover from a fluke.
///
/// The checksum of the migration stays the same and it is non-transactional (otherwise we wouldn't have
/// ended up in a dirty state to begin with).
Same,
/// Recover using a fixed version, the fix is still non-transactional.
FixNonTransactional,
/// Recover using a fixed version, the fix is transactional (in contrast to the original version).
FixTransactional,
}
impl RecoverFromDirtyMode {
fn same_checksum(&self) -> bool {
match self {
Self::Same => true,
Self::FixNonTransactional => false,
Self::FixTransactional => false,
}
}
fn fix_is_transactional(&self) -> bool {
match self {
Self::Same => false,
Self::FixNonTransactional => false,
Self::FixTransactional => true,
}
}
}
async fn test_migrator_recover_dirty_inner(mode: RecoverFromDirtyMode) {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
conn.execute("CREATE TABLE t (x INT);").await.unwrap();
let test_query = "SELECT COALESCE(SUM(x), 0)::INT AS r FROM t;";
let steps_ok = vec![
IOxMigrationStep::SqlStatement {
sql: "INSERT INTO t VALUES (1);".into(),
// set to NO transaction, otherwise the migrator will happily wrap the migration bookkeeping and the
// migration script itself into a single transaction to avoid the "dirty" state
in_transaction: mode.fix_is_transactional(),
},
IOxMigrationStep::SqlStatement {
sql: "INSERT INTO t VALUES (2);".into(),
in_transaction: mode.fix_is_transactional(),
},
];
let mut steps_broken = steps_ok.clone();
steps_broken[0] = IOxMigrationStep::SqlStatement {
sql: "foo".into(),
// set to NO transaction, otherwise the migrator will happily wrap the migration bookkeeping and the
// migration script itself into a single transaction to avoid the "dirty" state
in_transaction: false,
};
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: steps_broken.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap_err();
let r: i32 = query_scalar(test_query)
.fetch_one(&mut *conn)
.await
.unwrap();
assert_eq!(r, 0);
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: steps_ok.into(),
checksum: if mode.same_checksum() {
[1, 2, 3].into()
} else {
[4, 5, 6].into()
},
other_compatible_checksums: if mode.same_checksum() {
[].into()
} else {
[[1, 2, 3].into()].into()
},
}])
.unwrap();
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(applied, HashSet::from([1]));
let r: i32 = query_scalar(test_query)
.fetch_one(&mut *conn)
.await
.unwrap();
assert_eq!(r, 3);
}
#[tokio::test]
async fn test_migrator_uses_single_transaction_when_possible() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
conn.execute("CREATE TABLE t (x INT);").await.unwrap();
let steps_ok = vec![
IOxMigrationStep::SqlStatement {
sql: "INSERT INTO t VALUES (1);".into(),
in_transaction: true,
},
IOxMigrationStep::SqlStatement {
sql: "INSERT INTO t VALUES (2);".into(),
in_transaction: true,
},
IOxMigrationStep::SqlStatement {
sql: "INSERT INTO t VALUES (3);".into(),
in_transaction: true,
},
];
// break in-between step that is sandwiched by two valid ones
let mut steps_broken = steps_ok.clone();
steps_broken[1] = IOxMigrationStep::SqlStatement {
sql: "foo".into(),
in_transaction: true,
};
let test_query = "SELECT COALESCE(SUM(x), 0)::INT AS r FROM t;";
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: steps_broken.into(),
// use a placeholder checksum (normally this would be calculated based on the steps)
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
migrator.run_direct(conn).await.unwrap_err();
// all or nothing: nothing
let r: i32 = query_scalar(test_query)
.fetch_one(&mut *conn)
.await
.unwrap();
assert_eq!(r, 0);
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: steps_ok.into(),
// same checksum, but now w/ valid steps (to simulate a once failed SQL statement)
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(applied, HashSet::from([1]),);
// all or nothing: all
let r: i32 = query_scalar(test_query).fetch_one(conn).await.unwrap();
assert_eq!(r, 6);
}
/// Tests that `CREATE INDEX CONCURRENTLY` doesn't deadlock.
///
/// Originally we used SQLx to acquire the locks which uses `pg_advisory_lock`. However this seems to acquire a
/// global "shared lock". Other migration frameworks faced the same issue and use `pg_try_advisory_lock`
/// instead. Also see:
///
/// - <https://github.com/flyway/flyway/issues/1654>
/// - <https://github.com/flyway/flyway/commit/4a185ebcddfb7dac875b7afa5fa270aca621ce1d>
#[tokio::test]
async fn test_locking() {
const N_TABLES_AND_INDICES: usize = 10;
const N_CONCURRENT_MIGRATIONS: usize = 100;
maybe_skip_integration!();
maybe_start_logging();
let pool = setup_pool().await;
let migrator = Arc::new(
IOxMigrator::try_new((0..N_TABLES_AND_INDICES).map(|i| {
IOxMigration {
version: i as i64,
description: "".into(),
steps: [
IOxMigrationStep::SqlStatement {
sql: format!("CREATE TABLE t{i} (x INT);").into(),
in_transaction: false,
},
IOxMigrationStep::SqlStatement {
sql: format!("CREATE INDEX CONCURRENTLY i{i} ON t{i} (x);").into(),
in_transaction: false,
},
]
.into(),
checksum: [].into(),
other_compatible_checksums: [].into(),
}
}))
.unwrap(),
);
let mut futures: FuturesUnordered<_> = (0..N_CONCURRENT_MIGRATIONS)
.map(move |_| {
let migrator = Arc::clone(&migrator);
let pool = pool.clone();
async move {
// pool might timeout, so add another retry loop around it
let mut conn = loop {
let pool = pool.clone();
if let Ok(conn) = pool.acquire().await {
break conn;
}
};
let conn = &mut *conn;
migrator.run_direct(conn).await.unwrap();
}
})
.collect();
while futures.next().await.is_some() {}
}
/// This tests that:
///
/// - indexes are sanity-checked
/// - sanity checks are applied after each new/dirty migration and we keep the migration dirty until the checks
/// pass
/// - we can manually recover the database and make the non-idempotent migration pass
#[tokio::test]
async fn test_sanity_checks_index_1() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
conn.execute("CREATE TABLE t (x INT, y INT);")
.await
.unwrap();
conn.execute("INSERT INTO t VALUES (1, 1);").await.unwrap();
conn.execute("INSERT INTO t VALUES (1, 2);").await.unwrap();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS i ON t (x);".into(),
in_transaction: false,
}]
.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
// fails because is not unique
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while executing migrations: error returned from database: could not create unique index \"i\""
);
// re-applying fails due to sanity checks
// NOTE: Even though the actual migration script passes, the sanity checks DO NOT and hence the migration is
// still considered dirty. It will be re-applied after the manual intervention below.
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: Found invalid indexes: i"
);
// fix data and wipe index
conn.execute("DELETE FROM t WHERE y = 2;").await.unwrap();
conn.execute("DROP INDEX i;").await.unwrap();
// applying works
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(HashSet::from([1]), applied);
}
/// This tests that:
///
/// - indexes are sanity-checked
/// - we can fix a data error and a proper, idempotent migration will eventually pass
#[tokio::test]
async fn test_sanity_checks_index_2() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
conn.execute("CREATE TABLE t (x INT, y INT);")
.await
.unwrap();
conn.execute("INSERT INTO t VALUES (1, 1);").await.unwrap();
conn.execute("INSERT INTO t VALUES (1, 2);").await.unwrap();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [
IOxMigrationStep::SqlStatement {
sql: "DROP INDEX IF EXISTS i;".into(),
in_transaction: false,
},
IOxMigrationStep::SqlStatement {
sql: "CREATE UNIQUE INDEX CONCURRENTLY i ON t (x);".into(),
in_transaction: false,
},
]
.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
// fails because is not unique
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while executing migrations: error returned from database: could not create unique index \"i\""
);
// re-applying fails with same error (index is wiped but fails w/ same error)
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while executing migrations: error returned from database: could not create unique index \"i\""
);
// fix data issue
conn.execute("UPDATE t SET x = 2 WHERE y = 2")
.await
.unwrap();
// now it works
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(HashSet::from([1]), applied);
}
#[tokio::test]
async fn test_migrator_fail_new_migration_before_applied() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migration_1 = IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
};
let migration_2 = IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
};
let migrator = IOxMigrator::try_new([migration_2.clone()]).unwrap();
let applied = migrator.run_direct(conn).await.unwrap();
assert_eq!(HashSet::from([2]), applied);
let migrator = IOxMigrator::try_new([migration_1, migration_2]).unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: new migration (1) goes before last applied migration (2), \
this should not have been merged!",
);
}
#[tokio::test]
async fn test_migrator_fail_new_migration_before_dirty() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migration_1 = IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
};
let migration_2 = IOxMigration {
version: 2,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "foo".into(),
in_transaction: false,
}]
.into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
};
let migrator = IOxMigrator::try_new([migration_2.clone()]).unwrap();
migrator.run_direct(conn).await.unwrap_err();
let migrator = IOxMigrator::try_new([migration_1, migration_2]).unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: new migration (1) goes before dirty version (2), \
this should not have been merged!",
);
}
#[tokio::test]
async fn test_migrator_bug_selftest_multiple_dirty_migrations() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([
IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
},
])
.unwrap();
migrator.run_direct(conn).await.unwrap();
conn.execute("UPDATE _sqlx_migrations SET success = FALSE;")
.await
.unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: there are multiple dirty versions, \
this should not happen and is considered a bug: [1, 2]",
);
}
#[tokio::test]
async fn test_migrator_bug_selftest_applied_after_dirty() {
maybe_skip_integration!();
let mut conn = setup().await;
let conn = &mut *conn;
let migrator = IOxMigrator::try_new([
IOxMigration {
version: 1,
description: "".into(),
steps: [].into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 2,
description: "".into(),
steps: [].into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
},
])
.unwrap();
migrator.run_direct(conn).await.unwrap();
conn.execute("UPDATE _sqlx_migrations SET success = FALSE WHERE version = 1;")
.await
.unwrap();
let err = migrator.run_direct(conn).await.unwrap_err();
assert_eq!(
err.to_string(),
"while resolving migrations: dirty version (1) is not the last applied version (2), this is a bug",
);
}
#[tokio::test]
async fn test_tester_finds_invalid_migration() {
maybe_skip_integration!();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "foo".into(),
in_transaction: true,
}]
.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let err = test_utils::test_migration(&migrator, setup_pool)
.await
.unwrap_err();
assert_eq!(
err.to_string(),
"while executing migrations: error returned from database: syntax error at or near \"foo\"",
);
}
#[tokio::test]
async fn test_tester_finds_non_idempotent_migration_package() {
maybe_skip_integration!();
let migrator = IOxMigrator::try_new([IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "CREATE TABLE t (x INT);".into(),
// do NOT run this in a transaction, otherwise this is automatically idempotent
in_transaction: false,
}]
.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
}])
.unwrap();
let err = test_utils::test_migration(&migrator, setup_pool)
.await
.unwrap_err();
assert_eq!(
err.to_string(),
"while executing migrations: error returned from database: relation \"t\" already exists",
);
}
#[tokio::test]
async fn test_tester_finds_non_idempotent_migration_step() {
maybe_skip_integration!();
let migrator = IOxMigrator::try_new([
IOxMigration {
version: 1,
description: "".into(),
steps: [IOxMigrationStep::SqlStatement {
sql: "CREATE TABLE t (x INT);".into(),
in_transaction: true,
}]
.into(),
checksum: [1, 2, 3].into(),
other_compatible_checksums: [].into(),
},
IOxMigration {
version: 2,
description: "".into(),
steps: [
IOxMigrationStep::SqlStatement {
sql: "DROP TABLE t;".into(),
// do NOT run this in a transaction, otherwise this is automatically idempotent
in_transaction: false,
},
IOxMigrationStep::SqlStatement {
sql: "CREATE TABLE t (x INT);".into(),
// do NOT run this in a transaction, otherwise this is automatically idempotent
in_transaction: false,
},
]
.into(),
checksum: [4, 5, 6].into(),
other_compatible_checksums: [].into(),
},
])
.unwrap();
let err = test_utils::test_migration(&migrator, setup_pool)
.await
.unwrap_err();
assert_eq!(
err.to_string(),
"while executing migrations: error returned from database: table \"t\" does not exist",
);
}
async fn setup_pool() -> HotSwapPool<Postgres> {
maybe_start_logging();
setup_db_no_migration().await.into_pool()
}
async fn setup() -> PoolConnection<Postgres> {
let pool = setup_pool().await;
pool.acquire().await.unwrap()
}
#[track_caller]
fn assert_starts_with(s: &str, prefix: &str) {
if !s.starts_with(prefix) {
panic!("'{s}' does not start with '{prefix}'");
}
}
}
}
|
//! Vault
//!
//! This module is responsible for keeping track of the Hifi users that have open
//! positions and monitoring their debt healthiness.
use crate::EthersResult;
use ethers::prelude::*;
use hifi_liquidator_bindings::{BalanceSheet, OpenVaultFilter};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Arc};
use tracing::{debug, debug_span};
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
/// Borrower's vault from BalanceSheet
pub struct Vault {
/// The borrower's debt recorded in fyTokens. Obtained by calling `getVaultDebt` on the BalanceSheet.
pub debt: U256,
/// The borrower's debt recorded in underlying. Obtained by dividing `debt` by the underlying precision scalar.
pub debt_in_underlying: U256,
/// Is the vault liquidatable? Obtained by calling `isAccountUnderwater` on the BalanceSheet.
pub is_account_underwater: bool,
/// The borrower's currently locked collateral. Obtained by calling `getVaultLockedCollateral`
/// on the BalanceSheet.
pub locked_collateral: U256,
}
impl Vault {
pub fn new_empty() -> Self {
Self {
debt: U256::zero(),
debt_in_underlying: U256::zero(),
is_account_underwater: false,
locked_collateral: U256::zero(),
}
}
}
#[derive(Clone)]
pub struct VaultsContainer<M> {
/// The BalanceSheet smart contract
pub balance_sheet: BalanceSheet<M>,
/// The fyTokens to monitor.
pub fy_tokens: Vec<Address>,
/// We use Multicall to batch together calls and have reduced stress on our RPC endpoint.
multicall: Multicall<M>,
/// Mapping of the Hifi accounts that have taken loans and might be liquidatable. The first address
/// is the FyToken, the second the borrower's account.
pub vaults: HashMap<Address, HashMap<Address, Vault>>,
}
impl<M: Middleware> VaultsContainer<M> {
/// Constructor
pub async fn new(
balance_sheet: Address,
client: Arc<M>,
fy_tokens: Vec<Address>,
multicall: Option<Address>,
vaults: HashMap<Address, HashMap<Address, Vault>>,
) -> Self {
let multicall = Multicall::new(client.clone(), multicall)
.await
.expect("Could not initialize Multicall");
VaultsContainer {
balance_sheet: BalanceSheet::new(balance_sheet, client),
fy_tokens,
multicall,
vaults,
}
}
pub fn get_vault(&self, fy_token: &Address, borrower: &Address) -> Option<&Vault> {
if let Some(inner_hash_map) = self.vaults.get(fy_token) {
inner_hash_map.get(borrower)
} else {
None
}
}
pub fn get_vaults_iterator(&self) -> impl Iterator<Item = (&Address, &Address, &Vault)> {
let mut vaults_iterator: Vec<(&Address, &Address, &Vault)> = vec![];
for (fy_token, inner_hash_map) in self.vaults.iter() {
for (borrower, vault) in inner_hash_map.iter() {
vaults_iterator.push((fy_token, borrower, vault));
}
}
vaults_iterator.into_iter()
}
/// Updates the vault's details by calling:
///
/// 1. getVaultDebt
/// 2. isAccountUnderwater
/// 3. getVaultLockedCollateral
pub async fn query_vault(&mut self, fy_token: Address, borrower: Address) -> EthersResult<Vault, M> {
let debt_call = self.balance_sheet.get_vault_debt(fy_token, borrower);
let is_account_underwater_call = self.balance_sheet.is_account_underwater(fy_token, borrower);
let locked_collateral_call = self.balance_sheet.get_vault_locked_collateral(fy_token, borrower);
// Batch the calls together.
let multicall: &mut Multicall<M> = self
.multicall
.clear_calls()
.add_call(debt_call)
.add_call(is_account_underwater_call)
.add_call(locked_collateral_call);
let (debt, is_account_underwater, locked_collateral): (U256, bool, U256) = multicall.call().await?;
// Scale the debt down by the underlying precision scalar. E.g. USDC has 6 decimals, so the debt is scaled
// from 1e20 (100 fYUSDC) to 1e8 (100 USDC). There is a loss of precision when scaling down, but we can
// safely neglect it.
let usdc_precision_scalar =
U256::from_dec_str("1000000000000").expect("Creating U256 from decimal string must work");
let debt_in_underlying = debt / usdc_precision_scalar;
Ok(Vault {
debt,
debt_in_underlying,
is_account_underwater,
locked_collateral,
})
}
/// Indexes any new vaults which may have been opened since we last made this call. Then, it proceeds
/// to get the latest account details for each user.
pub async fn update_vaults(&mut self, from_block: U64, to_block: U64) -> EthersResult<(), M> {
let span = debug_span!("Monitoring");
let _enter = span.enter();
// 1. Get all new vaults (TODO: find a way to query only the whitelisted fyTokens).
let new_vault_tuples: Vec<OpenVaultFilter> = self
.balance_sheet
.open_vault_filter()
.from_block(from_block)
.to_block(to_block)
.query()
.await?;
// 2. Filter the vaults that don't belong to the fyTokens whitelisted the config.
let new_vault_tuples: Vec<(Address, Address)> = new_vault_tuples
.into_iter()
.filter_map(|event_log| {
if self.fy_tokens.contains(&event_log.fy_token) {
Some((event_log.fy_token, event_log.borrower))
} else {
None
}
})
.collect::<Vec<_>>();
// 3. Merge the new vaults with the existing vaults.
for new_vault_tuple in new_vault_tuples.iter() {
let fy_token = new_vault_tuple.0;
let borrower = new_vault_tuple.1;
self.insert_vault_if_not_exists(fy_token, borrower);
}
// 4. Update all vaults.
for (fy_token, inner_hash_map) in self.vaults.clone().iter() {
for borrower in inner_hash_map.keys().into_iter() {
let vault = self.query_vault(*fy_token, *borrower).await?;
self.vaults
.get_mut(fy_token)
.expect("Inner hash map must exist since we're iterating over the map")
.insert(*borrower, vault);
}
}
Ok(())
}
}
/// Private methods for the VaultsContainer struct
impl<M: Middleware> VaultsContainer<M> {
/// Insert the vault in the hash map if it doesn't exist.
fn insert_vault_if_not_exists(&mut self, fy_token: Address, borrower: Address) {
if let Some(inner_hash_map) = self.vaults.get_mut(&fy_token) {
if inner_hash_map.get(&borrower).is_none() {
inner_hash_map.insert(borrower, Vault::new_empty());
debug!(new_borrower = %borrower, in_fy_token = %fy_token);
}
} else {
let mut inner_hash_map = HashMap::<Address, Vault>::new();
inner_hash_map.insert(borrower, Vault::new_empty());
self.vaults.insert(fy_token, inner_hash_map);
debug!(new_fy_token = %fy_token);
debug!(new_borrower = %borrower, in_fy_token = %fy_token);
}
}
}
|
use chrono::NaiveDateTime;
use diesel;
use diesel::expression::dsl;
use diesel::prelude::*;
use models::{Organization, Region};
use schema::{organization_users, organizations, venues};
use utils::errors::ConvertToDatabaseError;
use utils::errors::DatabaseError;
use utils::errors::ErrorCode;
use uuid::Uuid;
use validator::{ValidationError, ValidationErrors};
#[derive(
Clone,
Associations,
Identifiable,
Queryable,
AsChangeset,
Serialize,
Deserialize,
PartialEq,
Debug,
)]
#[belongs_to(Region)]
#[table_name = "venues"]
pub struct Venue {
pub id: Uuid,
pub region_id: Option<Uuid>,
pub organization_id: Option<Uuid>,
pub is_private: bool,
pub name: String,
pub address: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub postal_code: Option<String>,
pub phone: Option<String>,
pub created_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
}
#[derive(AsChangeset, Default, Deserialize)]
#[table_name = "venues"]
pub struct VenueEditableAttributes {
pub region_id: Option<Uuid>,
pub name: Option<String>,
pub address: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub postal_code: Option<String>,
pub phone: Option<String>,
}
#[derive(Default, Insertable, Serialize, Deserialize, PartialEq, Debug)]
#[table_name = "venues"]
pub struct NewVenue {
pub name: String,
pub region_id: Option<Uuid>,
pub organization_id: Option<Uuid>,
pub address: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub postal_code: Option<String>,
pub phone: Option<String>,
}
impl NewVenue {
pub fn commit(&self, connection: &PgConnection) -> Result<Venue, DatabaseError> {
DatabaseError::wrap(
ErrorCode::InsertError,
"Could not create new venue",
diesel::insert_into(venues::table)
.values(self)
.get_result(connection),
)
}
}
impl Venue {
pub fn create(name: &str, region_id: Option<Uuid>, organization_id: Option<Uuid>) -> NewVenue {
NewVenue {
name: String::from(name),
region_id,
organization_id,
..Default::default()
}
}
pub fn update(
&self,
attributes: VenueEditableAttributes,
conn: &PgConnection,
) -> Result<Venue, DatabaseError> {
DatabaseError::wrap(
ErrorCode::UpdateError,
"Could not update venue",
diesel::update(self)
.set((attributes, venues::updated_at.eq(dsl::now)))
.get_result(conn),
)
}
pub fn find(id: Uuid, conn: &PgConnection) -> Result<Venue, DatabaseError> {
DatabaseError::wrap(
ErrorCode::QueryError,
"Error loading venue",
venues::table.find(id).first::<Venue>(conn),
)
}
pub fn find_by_ids(
venue_ids: Vec<Uuid>,
conn: &PgConnection,
) -> Result<Vec<Venue>, DatabaseError> {
venues::table
.filter(venues::id.eq_any(venue_ids))
.order_by(venues::name)
.select(venues::all_columns)
.order_by(venues::id.asc())
.load(conn)
.to_db_error(ErrorCode::QueryError, "Unable to load venues by ids")
}
pub fn all(user_id: Option<Uuid>, conn: &PgConnection) -> Result<Vec<Venue>, DatabaseError> {
let query = match user_id {
Some(u) => venues::table
.left_join(
organization_users::table.on(venues::organization_id
.eq(organization_users::organization_id.nullable())
.and(organization_users::user_id.eq(u))),
).left_join(
organizations::table
.on(venues::organization_id.eq(organizations::id.nullable())),
).filter(
organization_users::user_id
.eq(u)
.or(organizations::owner_user_id.eq(u))
.or(venues::is_private.eq(false)),
).order_by(venues::name)
.select(venues::all_columns)
.load(conn),
None => venues::table
.filter(venues::is_private.eq(false))
.order_by(venues::name)
.select(venues::all_columns)
.load(conn),
};
query.to_db_error(ErrorCode::QueryError, "Unable to load all venues")
}
pub fn find_for_organization(
user_id: Option<Uuid>,
organization_id: Uuid,
conn: &PgConnection,
) -> Result<Vec<Venue>, DatabaseError> {
let query = match user_id {
Some(u) => venues::table
.left_join(
organization_users::table.on(venues::organization_id
.eq(organization_users::organization_id.nullable())
.and(organization_users::user_id.eq(u))),
).left_join(
organizations::table
.on(venues::organization_id.eq(organizations::id.nullable())),
).filter(
organization_users::user_id
.eq(u)
.or(organizations::owner_user_id.eq(u))
.or(venues::is_private.eq(false)),
).filter(venues::organization_id.eq(organization_id))
.order_by(venues::name)
.select(venues::all_columns)
.load(conn),
None => venues::table
.filter(venues::is_private.eq(false))
.filter(venues::organization_id.eq(organization_id))
.order_by(venues::name)
.select(venues::all_columns)
.load(conn),
};
query.to_db_error(ErrorCode::QueryError, "Unable to load all venues")
}
pub fn add_to_organization(
self,
organization_id: &Uuid,
conn: &PgConnection,
) -> Result<Venue, DatabaseError> {
//Should I make sure that this venue doesn't already have one here even though there is logic
//for that in the bn-api layer?
diesel::update(&self)
.set(venues::organization_id.eq(organization_id))
.get_result(conn)
.to_db_error(ErrorCode::UpdateError, "Could not update venue")
}
pub fn set_privacy(
&self,
is_private: bool,
conn: &PgConnection,
) -> Result<Venue, DatabaseError> {
DatabaseError::wrap(
ErrorCode::UpdateError,
"Could not update is_private for artist",
diesel::update(self)
.set((
venues::is_private.eq(is_private),
venues::updated_at.eq(dsl::now),
)).get_result(conn),
)
}
pub fn organization(&self, conn: &PgConnection) -> Result<Option<Organization>, DatabaseError> {
match self.organization_id {
Some(organization_id) => Ok(Some(Organization::find(organization_id, conn)?)),
None => Ok(None),
}
}
pub fn validate_for_publish(&self) -> Result<(), ValidationErrors> {
let mut res = ValidationErrors::new();
if self.address.is_none() {
res.add(
"venue.address",
ValidationError::new("Address is required before publishing"),
);
}
if self.city.is_none() {
res.add(
"venue.city",
ValidationError::new("City is required before publishing"),
);
}
if self.country.is_none() {
res.add(
"venue.country",
ValidationError::new("Country is required before publishing"),
);
}
if self.postal_code.is_none() {
res.add(
"venue.postal_code",
ValidationError::new("Postal code is required before publishing"),
);
}
if self.state.is_none() {
res.add(
"venue.state",
ValidationError::new("State is required before publishing"),
);
}
if !res.is_empty() {
return Err(res);
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct DisplayVenue {
pub id: Uuid,
pub name: String,
pub address: Option<String>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub postal_code: Option<String>,
pub phone: Option<String>,
}
impl From<Venue> for DisplayVenue {
fn from(venue: Venue) -> Self {
DisplayVenue {
id: venue.id,
name: venue.name,
address: venue.address,
city: venue.city,
state: venue.state,
country: venue.country,
postal_code: venue.postal_code,
phone: venue.phone,
}
}
}
|
#![no_std]
#![feature(test)]
#[macro_use]
extern crate crypto_tests;
extern crate magma;
bench_block_cipher!(magma::Magma, 32);
|
use log::{debug, error, info};
use slack::api::rtm::StartResponse;
use slack::api::{Channel, Message, MessageStandard, User};
use slack::{Event, RtmClient};
use std::collections::HashMap;
use std::vec::Vec;
use crate::db;
use crate::util;
struct SlackHandler {
api_key: String,
server_base_url: String,
direct_msg_prefix: char,
user_id: String,
real_name: String,
reply_pattern: String,
users_cache: HashMap<String, String>,
}
impl SlackHandler {
fn should_reply(&self, event_text: &str) -> bool {
event_text.starts_with(&self.reply_pattern)
}
fn is_direct_msg(&self, channel_id: &str) -> bool {
channel_id.starts_with(self.direct_msg_prefix)
}
fn is_public_key(&self, event_text: &str, channel_id: &str) -> bool {
self.is_direct_msg(channel_id)
&& event_text.starts_with("-----BEGIN PUBLIC KEY-----")
&& event_text.ends_with("-----END PUBLIC KEY-----")
}
}
impl slack::EventHandler for SlackHandler {
fn on_event(&mut self, cli: &RtmClient, event: Event) {
let mut event_text: String = String::new();
let mut sender: String = String::new();
let mut channel_id: String = String::new();
debug!(
"\n\n################################# Event\n{:?}\n\n",
event
);
match event {
Event::Hello => {
info!("################################# Event::Hello");
}
Event::Message(message) => match *message {
Message::Standard(MessageStandard {
ref text,
ref user,
ref channel,
..
}) => {
event_text.push_str(text.as_ref().unwrap());
sender.push_str(user.as_ref().unwrap());
channel_id.push_str(channel.as_ref().unwrap());
}
_ => debug!("Message not decoded, ignore it."),
},
Event::DesktopNotification {
ref content,
ref subtitle,
ref channel,
..
} => {
event_text.push_str(content.as_ref().unwrap());
sender.push_str(subtitle.as_ref().unwrap());
channel_id.push_str(channel.as_ref().unwrap());
debug!("################################# Event::DesktopNotification");
return;
}
Event::Goodbye => {
info!("################################# Event::Goodbye");
start(self)
}
_ => debug!("Event not decoded, ignore it."),
}
// listen for commands
if (&event_text == "init" || &event_text == "help") && self.is_direct_msg(&channel_id) {
let mut response: String = format!(
"Run this in your terminal: `curl -sSf https://{}/init.sh | sh`",
&self.server_base_url
);
response.push_str("\n\nAfter that is done, please paste your public key found at `~/.slackrypt/key.pem.pub`");
let _ = cli.sender().send_message(&channel_id, &response);
}
if self.is_public_key(&event_text.trim(), &channel_id) {
let user_name: String = match self.users_cache.get(&sender) {
Some(name) => name.clone(),
None => "FIXME".to_string(),
};
// FIXME Error when new user is added to the Slack org after this Slackbot connects (i.e. initial load of users).
// thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'.
// Just check in the cache first, then manually add (i.e. when new user joins Slack workspace after launch).
// Problem is Event::Message doesn't have the correct user name and Event::DesktopNotification doesn't have the user id.
// This might have to be a PR to upstream slack crate.
let _ = db::upsert_pubkey(&sender, &user_name, event_text.trim()).unwrap();
let response: String =
format!("Thank you. If you're curious, your Slack id is {}", &sender);
let _ = cli.sender().send_message(&channel_id, &response);
}
if self.should_reply(&event_text) {
let args: Vec<&str> = event_text.split(' ').collect();
debug!("args are {:?}", args);
if args.len() > 1 {
//add DM commands here that need action
if args[1] == "help" {
let _ = cli
.sender()
.send_message(&channel_id, "DM me with the command 'init' to get started.");
} else {
let response: String =
format!("I haven't learned how to execute '{}' yet.", args[1]);
let _ = cli.sender().send_message(&channel_id, &response);
}
}
}
}
fn on_close(&mut self, _cli: &RtmClient) {
info!("on_close");
}
fn on_connect(&mut self, cli: &RtmClient) {
info!("on_connect");
let channel_name: String = util::get_env_var("SLACK_CHANNEL_NAME", "general");
let resp: &StartResponse = cli.start_response();
let users: &Vec<User> = resp.users.as_ref().expect("Could not get users");
let channels: &Vec<Channel> = resp.channels.as_ref().expect("Could not get channels");
// find the channel id from the `StartResponse`
let channel: &Channel = channels
.iter()
.find(|c| match c.name {
None => false,
Some(ref name) => name == &channel_name,
})
.unwrap();
let channel_id: String = channel.id.as_ref().unwrap().to_string();
// find all human users to persist initial info
let mut user_info: Vec<(&str, &str, &str)> = Vec::new(); //FIXME Make a struct in db.rs
for u in users {
if !u.is_bot.unwrap() && !u.deleted.unwrap() {
user_info.push((u.id.as_ref().unwrap(), u.name.as_ref().unwrap(), ""));
self.users_cache.insert(
u.id.as_ref().unwrap().to_string(),
u.name.as_ref().unwrap().to_string(),
);
}
}
db::insert_pubkeys(&user_info).unwrap();
// find bot user id
let this_bot_user: &User = users
.iter()
.find(|u| match u.profile {
None => false,
Some(ref up) => {
up.real_name.as_ref().unwrap() == &self.real_name
&& u.is_bot.unwrap()
&& !u.deleted.unwrap()
}
})
.unwrap();
assert!(this_bot_user.is_bot.unwrap());
assert!(!this_bot_user.deleted.unwrap());
self.user_id = this_bot_user.id.as_ref().unwrap().to_string();
// set the String pattern to look for when responding to @Slackrypt <command>
self.reply_pattern = "<@".to_string() + &self.user_id + "> ";
// Send connected message to channel
let connection_msg: String =
String::from("I'm up! Simply DM me with 'init' to get started.");
let _ = cli.sender().send_message(&channel_id, &connection_msg);
}
}
pub fn init(server_base_url: &str) {
info!("Initializing Slack RTM client...");
let api_key: String = util::get_env_var("BOTUSER_AUTH_ACCESS_TOKEN", "");
let botuser_name: String = util::get_env_var("BOTUSER_REAL_NAME", "Slackrypt");
let hash_map = HashMap::new();
let mut slack_handler = SlackHandler {
api_key,
server_base_url: server_base_url.to_string(),
direct_msg_prefix: 'D',
user_id: "unknown".to_string(),
real_name: botuser_name,
reply_pattern: "unknown".to_string(),
users_cache: hash_map,
};
start(&mut slack_handler)
}
fn start(slack_handler: &mut SlackHandler) {
info!("Starting Slack RTM client...");
match RtmClient::login_and_run(&slack_handler.api_key.to_string(), slack_handler) {
Ok(()) => {
info!("RTM client login_and_run successfully closed!");
}
Err(err) => {
error!("Error when attempting to login and run!");
panic!("Err: Could not login and start slack client! {}", err)
}
}
}
|
use crate::parser::*;
use anyhow::{bail, Result};
use common::*;
mod assembler;
mod parser;
pub fn assemble(text: &str) -> Result<Vec<u8>> {
let lines = text.lines().map(|s| s.to_string()).collect::<Vec<_>>();
let mut statements = Vec::new();
statements.push((
Statement::Operation(Operation {
src: Source::Accumulator,
dest: Destination::Accumulator,
cond_carry: false,
cond_1: false,
}),
0,
));
for (line_number, line) in lines.iter().enumerate() {
let line_number = line_number + 1;
match parse_line(&line) {
Err(e) => bail!("Parser error on line {}; {:?}", line_number, e),
Ok((_, Some(s))) => statements.push((s, line_number)),
_ => (),
}
}
Ok(assembler::assemble(statements.as_slice())?)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_assembler() {
let text = "
im_a_label:
5F -> LED
00 -> PC.latch : if_1
lo@im_a_label -> PC.latch
hi@im_a_label -> PC
55 -> RAM.low : if_carry | if_1
FF -> RAM.high : if_1 | if_carry
im_also_a_label:
lo@im_also_a_label -> PC.latch";
let expected_bytecode = vec![
0b01001100, 0b11100100, 0b01011111, 0b11010010, 0b00000000, 0b11010000, 0b00000001,
0b11010100, 0b00000000, 0b11011011, 0b01010101, 0b11011111, 0b11111111, 0b11010000,
0b00001101,
];
assert_eq!(assemble(&text).unwrap(), expected_bytecode);
}
#[test]
fn test_assembler2() {
let text = "
00 -> PC.latch
00 -> RAM.high
00 -> RAM.low
00 -> ACC
ACC -> RAM
main_loop:
00 -> ACC
ACC -> carry.reset
delay_loop:
01 -> ACC.plus
lo@out_of_loop -> PC : if_1
lo@delay_loop -> PC
out_of_loop:
RAM -> ACC
ACC -> LED
ACC -> carry.reset
01 -> ACC.plus
ACC -> RAM
lo@main_loop -> PC";
let binary = vec![
0b01_0011_00,
0b11_0100_00,
0b00_0000_00,
0b11_0111_00,
0b00_0000_00,
0b11_0110_00,
0b00_0000_00,
0b11_0011_00,
0b00_0000_00,
0b01_0000_00,
0b11_0011_00,
0b00_0000_00,
0b01_1011_00,
0b11_0001_00,
0b00_0000_01,
0b11_0101_10,
0b00_0100_11,
0b11_0101_00,
0b00_0011_01,
0b10_0011_00,
0b01_1001_00,
0b01_1011_00,
0b11_0001_00,
0b00_0000_01,
0b01_0000_00,
0b11_0101_00,
0b00_0010_10,
];
assert_eq!(assemble(&text).unwrap(), binary);
}
#[test]
#[should_panic]
fn test_assembler_err() {
assemble("8F -> RAM").unwrap();
}
#[test]
#[should_panic]
fn test_assembler_err2() {
assemble("ACC.plus -> LED").unwrap();
}
#[test]
#[should_panic]
fn test_assembler_err3() {
assemble(
"loop
lo@loop -> RAM",
)
.unwrap();
}
}
|
// Do something like to store the position of a string fragment,
// then give the next state to receive the next text segment.
//
// Compound state can be generated via the latest transferring:
//
// ListBegin -> AtomSymbol -> AtomSymbol -> ... -> ListEnd -> List
//
// The latest List get created because the chain successfully reach ListEnd.
//
use node::Node;
// The problem is State cannot be a return value.
// The size is undefined, unlike a structure (trait is a static thing).
//
// Also, Rust is designed to know the concrete item after a function call,
// during compilation time:
//
// let x = instance.foo();
//
// So if struct instance a, b both implemenet the trait T and the foo() is a T,
// Rust cannot know which concrete item it is.
//
// http://www.ncameron.org/blog/abstract-return-types-aka-%60impl-trait%60/
//
// Doc mentions it here:
//
// https://doc.rust-lang.org/book/trait-objects.html
//
// Not directly, but in the "Dynamic dispatch" chapter, the "either &Foo or Box<Foo>"
// statement describes the same issue here.
//
pub trait State {
fn transfer(&self, node: State) -> State;
fn extract(&self) -> Node; // TODO: a ref? a copy-instance?
}
|
extern crate serde_codegen;
use std::env;
use std::path::Path;
fn main () {
let out_dir =
env::var_os (
"OUT_DIR"
).unwrap ();
let input =
Path::new (
"src/database/serde_types.in.rs");
let output =
Path::new (
& out_dir,
).join (
"serde_types.rs",
);
serde_codegen::expand (
& input,
& output,)
.unwrap ();
}
|
use crate::mir::{Expression, Id};
use rustc_hash::FxHashMap;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PurenessInsights {
// TODO: Simplify to `FxHashSet<Id>`s.
definition_pureness: FxHashMap<Id, bool>,
definition_constness: FxHashMap<Id, bool>,
}
impl PurenessInsights {
/// Whether the expression defined at the given ID is pure.
///
/// E.g., a function definition is pure even if the defined function is not
/// pure.
pub fn is_definition_pure(&self, expression: &Expression) -> bool {
match expression {
Expression::Int(_)
| Expression::Text(_)
| Expression::Tag { .. }
| Expression::Builtin(_) // TODO: Check if the builtin is pure.
| Expression::List(_)
| Expression::Struct(_)
| Expression::Reference(_)
| Expression::HirId(_)
| Expression::Function { .. }
| Expression::Parameter => true,
// TODO: Check whether executing the function with the given arguments is pure when we inspect data flow.
Expression::Call { .. } | Expression::UseModule { .. } | Expression::Panic { .. } => {
false
}
Expression::TraceCallStarts { .. }
| Expression::TraceCallEnds { .. }
| Expression::TraceExpressionEvaluated { .. }
| Expression::TraceFoundFuzzableFunction { .. } => false,
}
}
/// Whether the value of this expression is pure and known at compile-time.
///
/// This is useful for moving expressions around without changing the
/// semantics.
pub fn is_definition_const(&self, expression: &Expression) -> bool {
self.is_definition_pure(expression)
&& expression.captured_ids().iter().all(|id| {
*self
.definition_constness
.get(id)
.unwrap_or_else(|| panic!("Missing pureness information for {id}"))
})
}
// Called after all optimizations are done for this `expression`.
pub(super) fn visit_optimized(&mut self, id: Id, expression: &Expression) {
let is_pure = self.is_definition_pure(expression);
self.definition_pureness.insert(id, is_pure);
let is_const = self.is_definition_const(expression);
self.definition_constness.insert(id, is_const);
// TODO: Don't optimize lifted constants again.
// Then, we can also add asserts here about not visiting them twice.
}
pub(super) fn enter_function(&mut self, parameters: &[Id], responsible_parameter: Id) {
self.definition_pureness
.extend(parameters.iter().map(|id| (*id, true)));
let _existing = self.definition_pureness.insert(responsible_parameter, true);
// TODO: Handle lifted constants properly.
// assert!(existing.is_none());
self.definition_constness
.extend(parameters.iter().map(|id| (*id, false)));
let _existing = self
.definition_constness
.insert(responsible_parameter, false);
// TODO: Handle lifted constants properly.
// assert!(existing.is_none());
}
pub(super) fn on_normalize_ids(&mut self, mapping: &FxHashMap<Id, Id>) {
fn update(values: &mut FxHashMap<Id, bool>, mapping: &FxHashMap<Id, Id>) {
*values = values
.iter()
.filter_map(|(original_id, value)| {
let new_id = mapping.get(original_id)?;
Some((*new_id, *value))
})
.collect();
}
update(&mut self.definition_pureness, mapping);
update(&mut self.definition_constness, mapping);
}
pub(super) fn include(&mut self, other: &PurenessInsights, mapping: &FxHashMap<Id, Id>) {
fn insert(
source: &FxHashMap<Id, bool>,
mapping: &FxHashMap<Id, Id>,
target: &mut FxHashMap<Id, bool>,
) {
for (id, source) in source {
assert!(target.insert(mapping[id], *source).is_none());
}
}
// TODO: Can we avoid some of the cloning?
insert(
&other.definition_pureness,
mapping,
&mut self.definition_pureness,
);
insert(
&other.definition_constness,
mapping,
&mut self.definition_constness,
);
}
}
|
use super::node_value::{NodeValue, NodeValueType};
use std::fmt;
/// A NodeDef represents a type of function that can be called in an evaluation graph.
/// These functions, like Rust's own functions, have a name and defined input and output
/// types (note that NodeDefs can explicitly have multiple outputs). Unlike Rust functions,
/// NodeDefs must execute without causing any side effects, ever. The type system is also
/// unique to Proton in order to better fit the domain and to keep the door open for
/// non-Rust plugins in the future.
#[derive(Debug, PartialEq)]
pub struct NodeDef {
pub desc: NodeDefBasicDescription,
pub inputs: Vec<NodeInputDef>,
pub outputs: Vec<NodeOutputDef>,
pub runner: NodeDefRunner,
}
/// Represents a single input to a NodeDef function.
#[derive(Debug, PartialEq)]
pub struct NodeInputDef {
pub desc: NodeDefBasicDescription,
pub allowed_types: Vec<NodeValueType>,
pub required: bool,
}
/// Represents a single output of a NodeDef function.
#[derive(Debug, PartialEq)]
pub struct NodeOutputDef {
pub desc: NodeDefBasicDescription,
pub output_type: NodeValueType,
}
/// Human-readable information about a node or its inputs or outputs.
#[derive(Debug, PartialEq)]
pub struct NodeDefBasicDescription {
pub name: String,
pub description: String,
}
/// Options for executing a Node, as specified in a NodeDef.
pub enum NodeDefRunner {
Function(fn(Vec<&NodeValue>) -> Vec<NodeValue>),
Executor(fn() -> Box<dyn NodeExecutor>),
OutputDevice(NodeDefOutputRunner),
}
pub struct NodeDefOutputRunner {
pub run: fn(Vec<&NodeValue>),
pub device: OutputDevice,
}
/// Information about an output device
#[derive(Debug, PartialEq)]
pub struct OutputDevice {
pub name: String,
}
impl fmt::Debug for NodeDefRunner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[Node Runner]")
}
}
impl std::cmp::PartialEq for NodeDefRunner {
fn eq(&self, _: &Self) -> bool {
// TODO (see if there's a way to actually make this work)
true
}
}
pub trait NodeExecutor: Send + Sync {
fn prepare(&self, enabled_outputs: &Vec<bool>);
fn execute(&self, inputs: Vec<&NodeValue>) -> Vec<NodeValue>;
}
|
use embedded_hal::blocking::{
delay::DelayMs,
i2c::{Read, Write},
};
use core::{fmt::Debug, marker::PhantomData};
const NUNCHUCK_ADDR: u8 = 0xA4;
#[derive(Debug)]
pub enum DataError<I2CERROR: Debug> {
I2CError(I2CERROR),
InvalidData,
}
#[derive(Debug, Copy, Clone)]
pub struct Data {
pub buttons: u8,
pub joy: [u8; 2],
pub accel: [u16; 3],
}
pub struct Nunchuck<I2C, ERROR> {
_i2c: PhantomData<*const I2C>,
_error: PhantomData<*const ERROR>,
}
impl<I2C: Read<Error = ERROR> + Write<Error = ERROR>, ERROR: Debug> Nunchuck<I2C, ERROR> {
pub fn init<DELAY>(i2c: &mut I2C, timer: &mut DELAY) -> Result<Self, ERROR>
where
DELAY: DelayMs<u32>,
{
timer.delay_ms(20u32);
i2c.write(NUNCHUCK_ADDR, &[0xF0, 0x55, 0xFB, 0x00])?;
timer.delay_ms(20u32);
Ok(Nunchuck {
_i2c: PhantomData,
_error: PhantomData,
})
}
pub fn read<DELAY>(
&mut self,
i2c: &mut I2C,
timer: &mut DELAY,
) -> Result<Data, DataError<ERROR>>
where
I2C: Write<Error = ERROR> + Read<Error = ERROR>,
DELAY: DelayMs<u32>,
{
let mut buffer = [0u8; 6];
i2c.write(NUNCHUCK_ADDR, &[0x00])
.map_err(|e| DataError::I2CError(e))?;
timer.delay_ms(3u32);
i2c.read(NUNCHUCK_ADDR, &mut buffer)
.map_err(|e| DataError::I2CError(e))?;
if (buffer[1] == 0x00
&& buffer[2] == 0x00
&& buffer[3] == 0x00
&& buffer[4] == 0x00
&& buffer[5] == 0x00)
|| (buffer[1] == 0xff
&& buffer[2] == 0xff
&& buffer[3] == 0xff
&& buffer[4] == 0xff
&& buffer[5] == 0xff)
{
return Err(DataError::InvalidData);
}
Ok(Data {
buttons: (!buffer[5] & 0x03),
joy: [buffer[0], buffer[1]],
accel: [
((buffer[2] as u16) << 2) | (((buffer[5] as u16) >> 2) & 0x03),
((buffer[3] as u16) << 2) | (((buffer[5] as u16) >> 4) & 0x03),
((buffer[4] as u16) << 2) | (((buffer[5] as u16) >> 6) & 0x03),
],
})
}
}
|
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use web_sys::*;
use web_sys::WebGlRenderingContext as GL;
#[macro_use]
extern crate lazy_static;
mod app_state;
mod common_funcs;
mod gl_setup;
mod programs;
mod shaders;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
#[wasm_bindgen(js_namespace = console)]
fn alert(s: &str);
}
#[wasm_bindgen]
pub struct RustClient {
gl: WebGlRenderingContext,
program_color_2d: programs::Color2D,
program_color_2d_gradient: programs::Color2DGradient,
colors: [f32; 16],
time: f32
}
#[wasm_bindgen]
impl RustClient {
#[wasm_bindgen(constructor)]
pub fn new() -> RustClient {
log("Initializing Rust Client...");
console_error_panic_hook::set_once();
let gl = gl_setup::initialize_webgl_context().unwrap();
let colors: [f32; 16] = [
1., 0., 0., 1.,
0., 1., 0., 1.,
0., 0., 1., 1.,
0., 1., 1., 1.,
];
RustClient {
program_color_2d: programs::Color2D::new(&gl),
program_color_2d_gradient: programs::Color2DGradient::new(&gl),
gl,
colors,
time: 0.
}
}
fn update_colors(&mut self, time: f32) {
self.time = self.time + (time * 0.25);
for i in 0..4 {
self.colors[(i * 4)] = (self.time * (i + 1) as f32).sin().abs();
self.colors[(i * 4) + 1] = ((self.time * 1.15) * (i + 1) as f32).sin().abs();
self.colors[(i * 4) + 2] = ((self.time * 1.3) * (i + 1) as f32).sin().abs();
}
}
pub fn update(&mut self, time: f32, width: f32, height: f32) -> Result<(), JsValue> {
app_state::update_dynamic_data(time, width, height);
self.update_colors(time);
Ok(())
}
pub fn draw(&self) {
self.gl.clear(GL::COLOR_BUFFER_BIT | GL::DEPTH_BUFFER_BIT);
let curr_state = app_state::get_current_state();
self.program_color_2d.draw(
&self.gl,
0.,
250.,
0.,
250.,
curr_state.canvas_width,
curr_state.canvas_height,
);
self.program_color_2d_gradient.draw(
&self.gl,
250.,
750.,
250.,
750.,
curr_state.canvas_width,
curr_state.canvas_height,
self.colors
);
}
} |
//
// MIT License
//
// Copyright (c) 2016, 2018 Yago Mouriño Mendaña <contacto@ylabs.es>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
extern crate getopts;
extern crate rand;
extern crate walkdir;
use getopts::Options;
use rand::Rng;
use std::env;
use std::process::Command;
use walkdir::WalkDir;
fn usage(opts: Options) {
// Get the current executable name, without the path.
let prog = env::current_exe().expect("ERROR: can't get current exe.");
let prog = prog.as_path()
.file_name()
.expect("ERROR: can't get current exe.")
.to_str()
.unwrap();
// Show the usage message.
let usage = format!("Usage: {} [options]", prog);
println!("{}", opts.usage(&usage));
}
fn main() {
// Prepare program options...
let mut opts = Options::new();
opts.optflag("h", "help", "prints this help screen");
opts.optopt("i", "input", "defines the input directory", "DIR");
opts.optopt("c", "count", "how many files should we get?", "COUNT");
opts.optflag("p", "play", "should we play the selected file?");
// ...and parse them.
let parsed = opts.parse(env::args())
.expect("ERROR: can't parse arguments.");
// Is the usage message requested?
if parsed.opt_present("h") {
usage(opts);
return;
}
// Get the input directory.
let directory = parsed.opt_str("i");
let directory = directory.as_ref().map(String::as_ref).unwrap_or(".");
// Get the contents of that directory and get only multimedia files.
let mut entries = vec![];
let extensions = vec![
"avi", "flac", "flv", "mkv", "mov", "mp3", "mp4", "mpeg", "mpg", "ogg", "wav", "wmv"
];
for entry in WalkDir::new(directory) {
let entry = entry.unwrap();
if entry.path().is_file() && entry.path().extension() != None {
if extensions.contains(&entry.path().extension().unwrap().to_str().unwrap()) {
entries.push(entry);
}
}
}
// How many files are in the collection?
let entries_count = entries.len();
// Avoid errors if there are 0 files.
if entries_count > 0 {
// Get how many files the user wants.
let count = parsed.opt_str("c");
let count = count.as_ref().map(String::as_ref).unwrap_or("1");
let count = count.parse::<i32>().expect("ERROR: can't count files.");
if count == 1 {
// Get a random file.
let selected = rand::thread_rng().gen_range(0, entries_count);
let selected = entries[selected].path();
// Should we play it?
if parsed.opt_present("p") {
Command::new("vlc")
.arg(selected.to_str().unwrap())
.spawn()
.expect("Command Not Found");
} else {
// If not, show its name.
println!("{}", selected.display());
}
} else if count > 1 && count < 6 {
for i in 0..count {
let selected = rand::thread_rng().gen_range(0, entries_count - i as usize);
println!("{}", entries.remove(selected).path().display())
}
} else {
println!("ERROR: 5 files max.");
}
} else {
println!("ERROR: files not found.");
}
}
|
use crossterm::style::Color;
use printer::buffer::Buffer;
use printer::printer::{PrintQueue, PrinterItem};
use theme::Theme;
pub mod theme;
const PAREN_COLORS: [&str; 4] = ["red", "yellow", "green", "blue"];
pub fn highlight(buffer: &Buffer, theme: &Theme) -> PrintQueue {
let mut print_queue = PrintQueue::default();
let buffer = buffer.to_string();
let rc_buf = std::rc::Rc::new(buffer.clone());
let mut token_range = 0..0;
let tokens: Vec<_> = rustc_lexer::tokenize(&buffer).collect();
let mut paren_idx = 0_isize;
macro_rules! push_to_printer {
($color: expr) => {{
let color = theme::theme_color_to_term_color($color).unwrap_or(Color::White);
print_queue.push(PrinterItem::RcString(
rc_buf.clone(),
token_range.clone(),
color,
));
}};
}
for (idx, token) in tokens.iter().enumerate() {
token_range.start = token_range.end;
token_range.end += token.len;
let text = &buffer[token_range.clone()];
use rustc_lexer::TokenKind::*;
match token.kind {
Ident if KEYWORDS.contains(&text) => {
push_to_printer!(&theme.keyword[..]);
}
Ident if KEYWORDS2.contains(&text) => {
push_to_printer!(&theme.keyword2[..]);
}
Ident if TYPES.contains(&text) => {
push_to_printer!(&theme.r#type[..]);
}
// const
Ident if text.chars().all(char::is_uppercase) => {
push_to_printer!(&theme.r#const[..]);
}
// macro
Ident
if matches!(
peek_first_non_white_sapce(&tokens[idx + 1..]).map(|(_, k)| k),
Some(Bang)
) =>
{
push_to_printer!(&theme.r#macro[..]);
}
// function
Ident if is_function(&tokens[idx + 1..]) => {
push_to_printer!(&theme.function[..]);
}
UnknownPrefix | Unknown | Ident | RawIdent | Whitespace => {
push_to_printer!(&theme.ident[..]);
}
LineComment { .. } | BlockComment { .. } => {
push_to_printer!(&theme.comment[..]);
}
Literal { .. } => {
push_to_printer!(&theme.literal[..])
}
Lifetime { .. } => {
push_to_printer!(&theme.lifetime[..])
}
Colon | At | Pound | Tilde | Question | Dollar | Semi | Comma | Dot | Eq | Bang
| Lt | Gt | Minus | And | Or | Plus | Star | Slash | Caret | Percent | OpenBrace
| OpenBracket | CloseBrace | CloseBracket => {
push_to_printer!(&theme.symbol[..]);
}
OpenParen => {
if theme.paren_rainbow {
push_to_printer!(PAREN_COLORS[paren_idx.unsigned_abs() % 4]);
} else {
print_queue.push(PrinterItem::Char('(', Color::White));
}
paren_idx += 1;
}
CloseParen => {
paren_idx -= 1;
if theme.paren_rainbow {
push_to_printer!(PAREN_COLORS[paren_idx.unsigned_abs() % 4]);
} else {
print_queue.push(PrinterItem::Char(')', Color::White));
}
}
};
}
print_queue
}
fn peek_first_non_white_sapce(
tokens: &[rustc_lexer::Token],
) -> Option<(usize, rustc_lexer::TokenKind)> {
for (idx, token) in tokens.iter().enumerate() {
if token.kind != rustc_lexer::TokenKind::Whitespace {
return Some((idx, token.kind));
}
}
None
}
fn is_function(tokens: &[rustc_lexer::Token]) -> bool {
let (idx, kind) = match peek_first_non_white_sapce(tokens) {
Some((i, k)) => (i, k),
None => return false,
};
use rustc_lexer::TokenKind::*;
match kind {
OpenParen => true,
Lt => true,
Colon => is_function(&tokens[idx + 1..]),
_ => false,
}
}
// Splitting keywords for a nicer coloring
// red blue green blue red white
// exp: pub fn hello() let mut var
const KEYWORDS: &[&str] = &[
"async", "await", "while", "use", "super", "self", "Self", "for", "impl", "trait", "type",
"pub", "in", "const", "static", "match", "use", "mut", "continue", "loop", "break", "if",
"else", "macro",
];
const KEYWORDS2: &[&str] = &["unsafe", "move", "fn", "let", "struct", "enum", "dyn"];
const TYPES: &[&str] = &[
"bool", "char", "usize", "isize", "u8", "i8", "u32", "i32", "u64", "i64", "u128", "i128",
"str", "String",
];
|
use std::fs;
extern crate inkwell;
mod lexer;
mod parser;
mod compiler;
mod consts {
pub const ANONYMOUS_FUNCTION_NAME: &str = "anonymous";
}
fn main() {
let mut prec: std::collections::HashMap<char, i32> = std::collections::HashMap::new();
prec.insert('*', 20);
prec.insert('/', 20);
prec.insert('+', 10);
prec.insert('-', 10);
let y: &str = &fs::read_to_string("ex.txt").unwrap();
let mut x = parser::Parser::new(y, "ex.txt", prec);
println!(": {:?}", x.parse_toplevel_expr().unwrap());
// println!(": {:?}", x.parse_toplevel_expr().unwrap());
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[doc(hidden)]
pub struct IServiceDeviceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IServiceDeviceStatics {
type Vtable = IServiceDeviceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa88214e1_59c7_4a20_aba6_9f6707937230);
}
#[repr(C)]
#[doc(hidden)]
pub struct IServiceDeviceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, servicetype: ServiceDeviceType, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, serviceid: ::windows::core::GUID, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IStorageDeviceStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IStorageDeviceStatics {
type Vtable = IStorageDeviceStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5ece44ee_1b23_4dd2_8652_bc164f003128);
}
#[repr(C)]
#[doc(hidden)]
pub struct IStorageDeviceStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
pub struct ServiceDevice {}
impl ServiceDevice {
pub fn GetDeviceSelector(servicetype: ServiceDeviceType) -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IServiceDeviceStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), servicetype, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn GetDeviceSelectorFromServiceId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(serviceid: Param0) -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IServiceDeviceStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), serviceid.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IServiceDeviceStatics<R, F: FnOnce(&IServiceDeviceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ServiceDevice, IServiceDeviceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for ServiceDevice {
const NAME: &'static str = "Windows.Devices.Portable.ServiceDevice";
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct ServiceDeviceType(pub i32);
impl ServiceDeviceType {
pub const CalendarService: ServiceDeviceType = ServiceDeviceType(0i32);
pub const ContactsService: ServiceDeviceType = ServiceDeviceType(1i32);
pub const DeviceStatusService: ServiceDeviceType = ServiceDeviceType(2i32);
pub const NotesService: ServiceDeviceType = ServiceDeviceType(3i32);
pub const RingtonesService: ServiceDeviceType = ServiceDeviceType(4i32);
pub const SmsService: ServiceDeviceType = ServiceDeviceType(5i32);
pub const TasksService: ServiceDeviceType = ServiceDeviceType(6i32);
}
impl ::core::convert::From<i32> for ServiceDeviceType {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ServiceDeviceType {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for ServiceDeviceType {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Portable.ServiceDeviceType;i4)");
}
impl ::windows::core::DefaultType for ServiceDeviceType {
type DefaultType = Self;
}
pub struct StorageDevice {}
impl StorageDevice {
#[cfg(feature = "Storage")]
pub fn FromId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Storage::StorageFolder> {
Self::IStorageDeviceStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Storage::StorageFolder>(result__)
})
}
pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IStorageDeviceStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IStorageDeviceStatics<R, F: FnOnce(&IStorageDeviceStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<StorageDevice, IStorageDeviceStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for StorageDevice {
const NAME: &'static str = "Windows.Devices.Portable.StorageDevice";
}
|
use clap::{AppSettings, Clap};
/// This doc string acts as a help message when the user runs '--help'
/// as do all doc strings on fields
#[derive(Clap)]
#[clap(version = "1.0", author = "Kevin K. <kbknapp@gmail.com>")]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
/// Sets a custom config file. Could have been an Option<T> with no default too
#[clap(short, long, default_value = "default.conf")]
config: String,
/// Some input. Because this isn't an Option<T> it's required to be used
input: String,
/// A level of verbosity, and can be used multiple times
#[clap(short, long, parse(from_occurrences))]
verbose: i32,
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Clap)]
enum SubCommand {
#[clap(version = "1.3", author = "Someone E. <someone_else@other.com>")]
Test(Test),
}
/// A subcommand for controlling testing
#[derive(Clap)]
struct Test {
/// Print debug info
#[clap(short)]
debug: bool
}
fn main() {
let opts: Opts = Opts::parse();
// Gets a value for config if supplied by user, or defaults to "default.conf"
println!("Value for config: {}", opts.config);
println!("Using input file: {}", opts.input);
// Vary the output based on how many times the user used the "verbose" flag
// (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
match opts.verbose {
0 => println!("No verbose info"),
1 => println!("Some verbose info"),
2 => println!("Tons of verbose info"),
3 | _ => println!("Don't be crazy"),
}
// You can handle information about subcommands by requesting their matches by name
// (as below), requesting just the name used, or both at the same time
match opts.subcmd {
SubCommand::Test(t) => {
//if t.debug {
// println!("Printing debug info...");
//} else {
// println!("Printing normally...");
//}
}
}
// more program logic goes here...
} |
#[cfg(feature = "chrono")] extern crate chrono;
#[macro_use] extern crate clap;
#[cfg(feature = "git2")] extern crate git2;
#[cfg(feature = "flame")] extern crate flame;
mod cli;
mod format;
mod module;
mod segments;
mod theme;
#[cfg(feature = "chrono")] use chrono::Local;
#[cfg(feature = "chrono")] use chrono::prelude::*;
#[cfg(feature = "chrono")] use std::fmt::Write;
#[cfg(unix)] use std::ffi::CString;
#[cfg(unix)] use std::os::raw::*;
use format::*;
use module::Module;
use segments::Segment;
use std::env;
use theme::Theme;
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum Shell {
Bare,
Ion,
Bash,
Zsh
}
pub struct Powerline {
segments: Vec<Segment>,
theme: Theme,
#[cfg(feature = "git2")]
git: Option<git2::Repository>,
#[cfg(feature = "git2")]
git_statuses: Option<Vec<git2::Status>>
}
#[cfg(unix)]
extern "C" {
fn access(pathname: *const c_char, mode: c_int) -> c_int;
fn getuid() -> c_int;
fn getpid() -> c_int; // std::process::id() is unstable
}
fn main() {
#[cfg(feature = "flame")]
flame::start("clap-rs");
let matches = cli::build_cli().get_matches();
#[cfg(feature = "flame")]
flame::end("clap-rs");
#[cfg(feature = "flame")]
flame::start("parse arguments");
let cwd_max_depth = value_t_or_exit!(matches, "cwd-max-depth", u8);
let cwd_max_dir_size = value_t_or_exit!(matches, "cwd-max-dir-size", u8);
let error = value_t_or_exit!(matches, "error", u8);
#[cfg(feature = "flame")]
flame::start("parse theme");
let theme = if let Some(file) = matches.value_of("theme") {
if let Ok(theme) = theme::load(file) {
theme
} else {
eprintln!("Invalid theme.");
theme::DEFAULT
}
} else { theme::DEFAULT };
#[cfg(feature = "flame")]
flame::end("parse theme");
#[cfg(feature = "flame")]
flame::start("parse modules");
let modules: Vec<_> = matches.values_of("modules").unwrap()
.map(|module| module.parse().unwrap())
.collect();
#[cfg(feature = "flame")]
flame::end("parse modules");
let shell = match matches.value_of("shell").unwrap() {
"bare" => Shell::Bare,
"bash" => Shell::Bash,
"ion" => Shell::Ion,
"zsh" => Shell::Zsh,
_ => unreachable!()
};
#[cfg(feature = "flame")]
flame::end("parse arguments");
#[cfg(feature = "flame")]
flame::start("main");
let mut p = Powerline {
segments: Vec::with_capacity(16), // just a guess
theme: theme,
#[cfg(feature = "git2")]
git: None,
#[cfg(feature = "git2")]
git_statuses: None
};
for module in modules {
match module {
Module::Cwd => segments::segment_cwd(&mut p, cwd_max_depth, cwd_max_dir_size),
Module::Git => { #[cfg(feature = "git2")] segments::segment_git(&mut p) },
Module::GitStage => { #[cfg(feature = "git2")] segments::segment_gitstage(&mut p) },
Module::Ps => segments::segment_ps(&mut p),
Module::Host => {
let (bg, fg) = (p.theme.hostname_bg, p.theme.hostname_fg);
if shell == Shell::Bare {
p.segments.push(
Segment::new(bg, fg, env::var("HOSTNAME")
.unwrap_or_else(|_| String::from("error")))
);
continue;
}
p.segments.push(Segment::new(bg, fg, match shell {
Shell::Bare => unreachable!(),
Shell::Bash => "\\h",
Shell::Ion => "\\h",
Shell::Zsh => "%m"
}).dont_escape());
},
Module::Jobs => {
p.segments.push(match shell {
Shell::Bare => continue,
Shell::Bash =>
Segment::new(p.theme.jobs_bg, p.theme.jobs_fg, "\\j")
.with_before(r#"$(test -n "$(jobs -p)" && echo -n ""#)
.with_after(r#"")"#),
Shell::Ion =>
Segment::new(p.theme.jobs_bg, p.theme.jobs_fg, "\\j")
.with_before(r#"$(test -n "$(jobs -p)" && echo -n ""#)
.with_after(r#"")"#),
Shell::Zsh =>
Segment::new(p.theme.jobs_bg, p.theme.jobs_fg, "%j")
.with_before("%(1j.")
.with_after(".)"),
}.as_conditional().dont_escape());
},
Module::Perms => {
#[cfg(unix)]
{
let path = CString::new(".").unwrap();
if unsafe { access(path.as_ptr(), 0x2) } != 0 {
p.segments.push(Segment::new(p.theme.ro_bg, p.theme.ro_fg, ""));
}
}
},
Module::Ssh => {
if env::var("SSH_CLIENT").is_ok() {
p.segments.push(Segment::new(p.theme.ssh_bg, p.theme.ssh_fg, ""));
}
},
Module::Time => {
let (bg, fg) = (p.theme.time_bg, p.theme.time_fg);
if shell == Shell::Bare {
#[cfg(feature = "chrono")]
{
let time = Local::now();
let (ampm, hour) = time.hour12();
let ampm = if ampm { "AM" } else { "PM" };
let mut formatted = String::with_capacity(2 + 1 + 2 + 1 + 2);
write!(formatted, "{:02}:{:02} {}", hour, time.minute(), ampm).unwrap();
p.segments.push(Segment::new(bg, fg, formatted));
}
continue;
}
p.segments.push(Segment::new(bg, fg, match shell {
Shell::Bare => unreachable!(),
Shell::Bash => "\\@",
Shell::Ion => "\\@",
Shell::Zsh => "%@"
}).dont_escape())
},
Module::User => {
let (mut bg, fg) = (p.theme.username_bg, p.theme.username_fg);
#[cfg(unix)]
{
if unsafe { getuid() } == 0 {
bg = p.theme.username_root_bg;
}
}
if shell == Shell::Bare {
// Yeah the optimal approach wouldn't be to use environment variables
// but then again it would be a lot more code (even if from a library),
// therefore *probably* slower.
// But then again I don't know.
p.segments.push(Segment::new(bg, fg,
env::var("USER").unwrap_or_else(|_| String::from("error"))));
continue;
}
p.segments.push(Segment::new(bg, fg, match shell {
Shell::Bare => unreachable!(),
Shell::Bash => "\\u",
Shell::Ion => "\\u",
Shell::Zsh => "%n"
}).dont_escape());
},
Module::Root => {
let (mut bg, mut fg) = (p.theme.cmd_passed_bg, p.theme.cmd_passed_fg);
if error != 0 {
bg = p.theme.cmd_failed_bg;
fg = p.theme.cmd_failed_fg;
}
p.segments.push(Segment::new(bg, fg, root(shell)).dont_escape());
},
}
}
#[cfg(feature = "flame")]
flame::end("main");
#[cfg(feature = "flame")]
flame::start("print");
for i in 0..p.segments.len() {
p.segments[i].escape(shell);
p.segments[i].print(p.segments.get(i+1), shell, &p.theme);
}
if matches.is_present("newline") {
println!();
} else {
print!(" ");
}
#[cfg(feature = "flame")]
flame::end("print");
#[cfg(feature = "flame")]
{
use std::fs::File;
flame::dump_html(&mut File::create("profile.html").unwrap()).unwrap();
}
}
|
#[doc = "Reader of register PMTCTLSTAT"]
pub type R = crate::R<u32, super::PMTCTLSTAT>;
#[doc = "Writer for register PMTCTLSTAT"]
pub type W = crate::W<u32, super::PMTCTLSTAT>;
#[doc = "Register PMTCTLSTAT `reset()`'s with value 0"]
impl crate::ResetValue for super::PMTCTLSTAT {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `PWRDWN`"]
pub type PWRDWN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PWRDWN`"]
pub struct PWRDWN_W<'a> {
w: &'a mut W,
}
impl<'a> PWRDWN_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 `MGKPKTEN`"]
pub type MGKPKTEN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MGKPKTEN`"]
pub struct MGKPKTEN_W<'a> {
w: &'a mut W,
}
impl<'a> MGKPKTEN_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 `WUPFREN`"]
pub type WUPFREN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WUPFREN`"]
pub struct WUPFREN_W<'a> {
w: &'a mut W,
}
impl<'a> WUPFREN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `MGKPRX`"]
pub type MGKPRX_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MGKPRX`"]
pub struct MGKPRX_W<'a> {
w: &'a mut W,
}
impl<'a> MGKPRX_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `WUPRX`"]
pub type WUPRX_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WUPRX`"]
pub struct WUPRX_W<'a> {
w: &'a mut W,
}
impl<'a> WUPRX_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `GLBLUCAST`"]
pub type GLBLUCAST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GLBLUCAST`"]
pub struct GLBLUCAST_W<'a> {
w: &'a mut W,
}
impl<'a> GLBLUCAST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `RWKPTR`"]
pub type RWKPTR_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `RWKPTR`"]
pub struct RWKPTR_W<'a> {
w: &'a mut W,
}
impl<'a> RWKPTR_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 << 24)) | (((value as u32) & 0x07) << 24);
self.w
}
}
#[doc = "Reader of field `WUPFRRST`"]
pub type WUPFRRST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `WUPFRRST`"]
pub struct WUPFRRST_W<'a> {
w: &'a mut W,
}
impl<'a> WUPFRRST_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 - Power Down"]
#[inline(always)]
pub fn pwrdwn(&self) -> PWRDWN_R {
PWRDWN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Magic Packet Enable"]
#[inline(always)]
pub fn mgkpkten(&self) -> MGKPKTEN_R {
MGKPKTEN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Wake-Up Frame Enable"]
#[inline(always)]
pub fn wupfren(&self) -> WUPFREN_R {
WUPFREN_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 5 - Magic Packet Received"]
#[inline(always)]
pub fn mgkprx(&self) -> MGKPRX_R {
MGKPRX_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Wake-Up Frame Received"]
#[inline(always)]
pub fn wuprx(&self) -> WUPRX_R {
WUPRX_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 9 - Global Unicast"]
#[inline(always)]
pub fn glblucast(&self) -> GLBLUCAST_R {
GLBLUCAST_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bits 24:26 - Remote Wake-Up FIFO Pointer"]
#[inline(always)]
pub fn rwkptr(&self) -> RWKPTR_R {
RWKPTR_R::new(((self.bits >> 24) & 0x07) as u8)
}
#[doc = "Bit 31 - Wake-Up Frame Filter Register Pointer Reset"]
#[inline(always)]
pub fn wupfrrst(&self) -> WUPFRRST_R {
WUPFRRST_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Power Down"]
#[inline(always)]
pub fn pwrdwn(&mut self) -> PWRDWN_W {
PWRDWN_W { w: self }
}
#[doc = "Bit 1 - Magic Packet Enable"]
#[inline(always)]
pub fn mgkpkten(&mut self) -> MGKPKTEN_W {
MGKPKTEN_W { w: self }
}
#[doc = "Bit 2 - Wake-Up Frame Enable"]
#[inline(always)]
pub fn wupfren(&mut self) -> WUPFREN_W {
WUPFREN_W { w: self }
}
#[doc = "Bit 5 - Magic Packet Received"]
#[inline(always)]
pub fn mgkprx(&mut self) -> MGKPRX_W {
MGKPRX_W { w: self }
}
#[doc = "Bit 6 - Wake-Up Frame Received"]
#[inline(always)]
pub fn wuprx(&mut self) -> WUPRX_W {
WUPRX_W { w: self }
}
#[doc = "Bit 9 - Global Unicast"]
#[inline(always)]
pub fn glblucast(&mut self) -> GLBLUCAST_W {
GLBLUCAST_W { w: self }
}
#[doc = "Bits 24:26 - Remote Wake-Up FIFO Pointer"]
#[inline(always)]
pub fn rwkptr(&mut self) -> RWKPTR_W {
RWKPTR_W { w: self }
}
#[doc = "Bit 31 - Wake-Up Frame Filter Register Pointer Reset"]
#[inline(always)]
pub fn wupfrrst(&mut self) -> WUPFRRST_W {
WUPFRRST_W { w: self }
}
}
|
use std::ops::{Index, IndexMut};
use std::ptr::NonNull;
use cranelift_entity::EntityRef;
use intrusive_collections::linked_list::{Cursor, CursorMut, LinkedList};
use intrusive_collections::{intrusive_adapter, LinkedListLink, UnsafeRef};
use firefly_arena::TypedArena;
/// This struct holds the data for each node in an ArenaMap/OrderedArenaMap
#[derive(Clone)]
pub struct LayoutNode<K: EntityRef, V: Clone> {
pub link: LinkedListLink,
key: K,
value: V,
}
impl<K: EntityRef, V: Clone> LayoutNode<K, V> {
pub fn new(key: K, value: V) -> Self {
Self {
link: LinkedListLink::default(),
key,
value,
}
}
#[inline(always)]
pub fn key(&self) -> K {
self.key
}
#[inline(always)]
pub fn value(&self) -> &V {
&self.value
}
#[inline(always)]
pub fn value_mut(&mut self) -> &mut V {
&mut self.value
}
}
intrusive_adapter!(pub LayoutAdapter<K, V> = UnsafeRef<LayoutNode<K, V>>: LayoutNode<K, V> { link: LinkedListLink } where K: EntityRef, V: Clone);
/// ArenaMap provides similar functionality to other kinds of maps:
///
/// # Pros
///
/// * Once allocated, values stored in the map have a stable location, this can be useful for when you
/// expect to store elements of the map in an intrusive collection.
/// * Keys can be more efficiently sized, i.e. rather than pointers/usize keys, you can choose arbitrarily
/// small bitwidths, as long as there is sufficient keyspace for your use case.
/// * Attempt to keep data in the map as contiguous in memory as possible. This is again useful for when
/// the data is also linked into an intrusive collection, like a linked list, where traversing the list
/// will end up visiting many of the nodes in the map. If each node was its own Box, this would cause
/// thrashing of the cache - ArenaMap sidesteps this by allocating values in chunks of memory that are
/// friendlier to the cache.
///
/// # Cons
///
/// * Memory allocated for data stored in the map is not released until the map is dropped. This is
/// a tradeoff made to ensure that the data has a stable location in memory, but the flip side of that
/// is increased memory usage for maps that stick around for a long time. In our case, these maps are
/// relatively short-lived, so it isn't a problem in practice.
/// * It doesn't provide as rich of an API as HashMap and friends
pub struct ArenaMap<K: EntityRef, V: Clone> {
keys: Vec<Option<NonNull<V>>>,
arena: TypedArena<V>,
_marker: core::marker::PhantomData<K>,
}
impl<K: EntityRef, V: Clone> Drop for ArenaMap<K, V> {
fn drop(&mut self) {
self.keys.clear()
}
}
impl<K: EntityRef, V: Clone> Clone for ArenaMap<K, V> {
fn clone(&self) -> Self {
let mut cloned = Self::new();
for opt in self.keys.iter() {
match opt {
None => cloned.keys.push(None),
Some(nn) => {
let value = unsafe { nn.as_ref() };
cloned.push(value.clone());
}
}
}
cloned
}
}
impl<K: EntityRef, V: Clone> Default for ArenaMap<K, V> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<K: EntityRef, V: Clone> ArenaMap<K, V> {
/// Creates a new, empty ArenaMap
pub fn new() -> Self {
Self {
arena: TypedArena::default(),
keys: vec![],
_marker: core::marker::PhantomData,
}
}
/// Returns the total number of actively linked items in the map
pub fn len(&self) -> usize {
self.keys.iter().filter(|item| item.is_some()).count()
}
/// Returns true if this map contains `key`
pub fn contains(&self, key: K) -> bool {
self.keys
.get(key.index())
.map(|item| item.is_some())
.unwrap_or(false)
}
/// Adds a new entry to the map, returning the key it is associated to
pub fn push(&mut self, value: V) -> K {
let key = self.alloc_key();
self.alloc_node(key, value);
key
}
/// Used in conjunction with `alloc_key` to associate data with the allocated key
pub fn append(&mut self, key: K, value: V) {
self.alloc_node(key, value);
}
/// Returns a reference to the value associated with the given key
pub fn get(&self, key: K) -> Option<&V> {
self.keys
.get(key.index())
.and_then(|item| item.map(|nn| unsafe { nn.as_ref() }))
}
/// Returns a mutable reference to the value associated with the given key
pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
self.keys
.get_mut(key.index())
.and_then(|item| item.map(|mut nn| unsafe { nn.as_mut() }))
}
/// Takes the value that was stored at the given key
pub fn take(&mut self, key: K) -> Option<NonNull<V>> {
self.keys[key.index()].take()
}
pub fn iter<'a>(&'a self) -> impl Iterator<Item = Option<NonNull<V>>> + 'a {
self.keys.iter().copied()
}
/// Removes the value associated with the given key
///
/// NOTE: This function will panic if the key is invalid/unbound
pub fn remove(&mut self, key: K) {
self.keys[key.index()].take();
}
/// Clears all of the data from the map
pub fn clear(&mut self) {
self.keys.clear();
self.arena.clear();
}
pub fn alloc_key(&mut self) -> K {
let id = self.keys.len();
let key = K::new(id);
self.keys.push(None);
key
}
fn alloc_node(&mut self, key: K, value: V) -> NonNull<V> {
let value = self.arena.alloc(value);
let nn = unsafe { NonNull::new_unchecked(value) };
self.keys[key.index()].replace(nn);
nn
}
}
impl<K: EntityRef, V: Clone> Index<K> for ArenaMap<K, V> {
type Output = V;
#[inline]
fn index(&self, index: K) -> &Self::Output {
self.get(index).unwrap()
}
}
impl<K: EntityRef, V: Clone> IndexMut<K> for ArenaMap<K, V> {
#[inline]
fn index_mut(&mut self, index: K) -> &mut Self::Output {
self.get_mut(index).unwrap()
}
}
/// OrderedArenaMap is an extension of ArenaMap that provides for arbitrary ordering of keys/values
///
/// This is done using an intrusive linked list alongside an ArenaMap. The list is used to link one
/// key/value pair to the next, so any ordering you wish to implement is possible. This is particularly
/// useful for layout of blocks in a function, or instructions within blocks, as you can precisely position
/// them relative to other blocks/instructions.
///
/// Because the linked list is intrusive, it is virtually free in terms of space, but comes with the
/// standard overhead for traversals. That said, there are a couple of niceties that give it good overall
/// performance:
///
/// * It is a doubly-linked list, so you can traverse equally efficiently front-to-back or back-to-front,
/// * It has O(1) indexing; given a key, we can directly obtain a reference to a node, and with that,
/// obtain a cursor over the list starting at that node.
pub struct OrderedArenaMap<K: EntityRef, V: Clone> {
list: LinkedList<LayoutAdapter<K, V>>,
map: ArenaMap<K, LayoutNode<K, V>>,
}
impl<K: EntityRef, V: Clone> Drop for OrderedArenaMap<K, V> {
fn drop(&mut self) {
self.list.fast_clear();
}
}
impl<K: EntityRef, V: Clone> Clone for OrderedArenaMap<K, V> {
fn clone(&self) -> Self {
let mut cloned = Self::new();
for opt in self.map.iter() {
match opt {
None => {
cloned.map.alloc_key();
}
Some(nn) => {
let value = unsafe { nn.as_ref() }.value();
cloned.push(value.clone());
}
}
}
cloned
}
}
impl<K: EntityRef, V: Clone> Default for OrderedArenaMap<K, V> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<K: EntityRef, V: Clone> OrderedArenaMap<K, V> {
pub fn new() -> Self {
Self {
map: ArenaMap::new(),
list: LinkedList::new(LayoutAdapter::new()),
}
}
pub fn clear(&mut self) {
self.list.fast_clear();
self.map.clear();
}
/// Returns the total number of actively linked items in the map
pub fn len(&self) -> usize {
self.map.len()
}
/// Returns true if this map contains the given key and its value has been linked
#[inline]
pub fn contains(&self, key: K) -> bool {
self.map.contains(key)
}
/// Returns a reference to the value associated with the given key, if present and linked
pub fn get(&self, key: K) -> Option<&V> {
self.map.get(key).map(|data| data.value())
}
/// Returns a mutable reference to the value associated with the given key, if present and linked
pub fn get_mut(&mut self, key: K) -> Option<&mut V> {
self.map.get_mut(key).map(|data| data.value_mut())
}
/// Allocates a key, but does not link the data
#[inline]
pub fn create(&mut self) -> K {
self.map.alloc_key()
}
/// Used with `create` when ready to associate data with the allocated key, linking it in to the end of the list
pub fn append(&mut self, key: K, value: V) {
debug_assert!(!self.contains(key));
let data = self.alloc_node(key, value);
self.list.push_back(data);
}
/// Like `append`, but inserts the node before `before` in the list
///
/// NOTE: This function will panic if `before` is not present in the list
pub fn insert_before(&mut self, key: K, before: K, value: V) {
let value_opt = self.get_mut(key);
debug_assert!(value_opt.is_none());
let data = self.alloc_node(key, value);
let mut cursor = self.cursor_mut_at(before);
cursor.insert_before(data);
}
/// Like `append`, but inserts the node after `after` in the list
///
/// NOTE: This function will panic if `after` is not present in the list
pub fn insert_after(&mut self, key: K, after: K, value: V) {
let value_opt = self.get_mut(key);
debug_assert!(value_opt.is_none());
let data = self.alloc_node(key, value);
let mut cursor = self.cursor_mut_at(after);
cursor.insert_after(data);
}
/// Allocates a key and links data in the same operation
pub fn push(&mut self, value: V) -> K {
let key = self.alloc_key();
self.append(key, value);
key
}
/// Unlinks the value associated with the given key from this map
///
/// NOTE: Removal does not result in deallocation of the underlying data, this
/// happens when the map is dropped. To perform early garbage collection, you can
/// clone the map, and drop the original.
pub fn remove(&mut self, key: K) {
if let Some(nn) = self.map.take(key) {
let mut cursor = unsafe { self.list.cursor_mut_from_ptr(nn.as_ptr()) };
cursor.remove();
}
}
/// Returns the first node in the map
pub fn first(&self) -> Option<&LayoutNode<K, V>> {
self.list.front().get()
}
/// Returns the last node in the map
pub fn last(&self) -> Option<&LayoutNode<K, V>> {
self.list.back().get()
}
/// Returns a cursor which can be used to traverse the map in order (front to back)
pub fn cursor(&self) -> Cursor<'_, LayoutAdapter<K, V>> {
self.list.front()
}
/// Returns a cursor which can be used to traverse the map mutably, in order (front to back)
pub fn cursor_mut(&mut self) -> CursorMut<'_, LayoutAdapter<K, V>> {
self.list.front_mut()
}
/// Returns a cursor which can be used to traverse the map in order (front to back), starting
/// at the key given.
pub fn cursor_at(&self, key: K) -> Cursor<'_, LayoutAdapter<K, V>> {
let ptr = &self.map[key] as *const LayoutNode<K, V>;
unsafe { self.list.cursor_from_ptr(ptr) }
}
/// Returns a cursor which can be used to traverse the map mutably, in order (front to back), starting
/// at the key given.
pub fn cursor_mut_at(&mut self, key: K) -> CursorMut<'_, LayoutAdapter<K, V>> {
let ptr = &self.map[key] as *const LayoutNode<K, V>;
unsafe { self.list.cursor_mut_from_ptr(ptr) }
}
/// Returns an iterator over the key/value pairs in the map, in order (front to back)
pub fn iter<'a>(&'a self) -> impl Iterator<Item = (K, &'a V)> {
self.list.iter().map(|item| (item.key(), item.value()))
}
/// Returns an iterator over the keys in the map, in order (front to back)
pub fn keys<'a>(&'a self) -> impl Iterator<Item = K> + 'a {
self.list.iter().map(|item| item.key())
}
/// Returns an iterator over the values in the map, in order (front to back)
pub fn values<'a>(&'a self) -> impl Iterator<Item = &'a V> {
self.list.iter().map(|item| item.value())
}
#[inline]
fn alloc_key(&mut self) -> K {
self.map.alloc_key()
}
fn alloc_node(&mut self, key: K, value: V) -> UnsafeRef<LayoutNode<K, V>> {
let nn = self.map.alloc_node(key, LayoutNode::new(key, value));
unsafe { UnsafeRef::from_raw(nn.as_ptr()) }
}
}
impl<K: EntityRef, V: Clone> Index<K> for OrderedArenaMap<K, V> {
type Output = V;
#[inline]
fn index(&self, index: K) -> &Self::Output {
self.get(index).unwrap()
}
}
impl<K: EntityRef, V: Clone> IndexMut<K> for OrderedArenaMap<K, V> {
#[inline]
fn index_mut(&mut self, index: K) -> &mut Self::Output {
self.get_mut(index).unwrap()
}
}
|
use crate::color_util::ColorUtil;
use crate::state::Position;
use druid::{widget::*, *};
pub struct Tile<T: druid::Data, R: Widget<T>> {
position: Position,
inner: R,
_t: std::marker::PhantomData<T>,
}
impl<T: druid::Data, R: Widget<T>> Tile<T, R> {
pub fn new(position: Position, inner: R) -> Self {
Self {
position,
inner,
_t: std::marker::PhantomData::default(),
}
}
pub fn on_click(
self,
f: impl Fn(&mut EventCtx, &mut T, &Env) + 'static,
) -> ControllerHost<Self, Click<T>> {
ControllerHost::new(self, Click::new(f))
}
}
impl<T: druid::Data, R: Widget<T>> Widget<T> for Tile<T, R> {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut T, _env: &Env) {
match event {
Event::MouseDown(_) => {
ctx.set_active(true);
ctx.request_paint();
}
Event::MouseUp(_) => {
if ctx.is_active() {
ctx.set_active(false);
ctx.request_paint();
}
}
_ => (),
}
}
fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) {
self.inner.lifecycle(ctx, event, data, env);
}
fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) {
self.inner.update(ctx, old_data, data, env);
}
fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size {
self.inner.layout(ctx, &bc, data, env);
bc.max()
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) {
let pos = self.position;
let checkerboard = pos.0 % 2 == pos.1 % 2;
let bounds = ctx.size().to_rect();
let is_active = ctx.is_active();
let colo = ColorUtil::hsl(
0.1,
0.2,
if is_active {
0.53
} else if checkerboard {
0.3
} else {
0.4
},
);
ctx.fill(bounds, &colo);
self.inner.paint(ctx, data, env);
// ctx.with_save(|ctx| {
// ctx.transform(Affine::translate(Vec2::from((8.0, 7.0))));
// self.label.paint(ctx, data, env);
// });
}
}
|
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::{ContentType, Header, Method};
use rocket::{Request, Response};
use std::io::Cursor;
use std::path::PathBuf;
pub struct CORS();
#[options("/<_params..>")]
pub fn cors(_params: PathBuf) -> String {
"".to_owned()
}
impl Fairing for CORS {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to requests",
kind: Kind::Response,
}
}
fn on_response(&self, request: &Request, response: &mut Response) {
if request.method() == Method::Options || response.content_type() == Some(ContentType::JSON)
{
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
response.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, PUT, OPTIONS",
));
response.set_header(Header::new(
"Access-Control-Allow-Headers",
"Content-Type, X-API-KEY",
));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
if request.method() == Method::Options {
response.set_header(ContentType::Plain);
response.set_sized_body(Cursor::new(""));
}
}
}
|
use examples_shared::{
self as es,
anyhow::{self, Context as _},
ds, tokio, tracing,
};
use structopt::StructOpt;
use ds::{activity, lobby, overlay, relations};
#[derive(StructOpt, Debug)]
enum LobbyCmd {
Create {
#[structopt(long, default_value = "4")]
capacity: u32,
},
Update {
#[structopt(long, default_value = "4")]
capacity: u32,
},
Delete,
Connect {
#[structopt(long)]
id: String,
#[structopt(long)]
secret: String,
},
Disconnect {
#[structopt(long)]
id: String,
},
Msg {
#[structopt(long)]
id: String,
msg: String,
},
Print,
Search,
}
#[derive(StructOpt, Debug)]
struct ActivityUpdateCmd {
#[structopt(long, default_value = "repling")]
state: String,
#[structopt(long, default_value = "having fun")]
details: String,
}
#[derive(StructOpt, Debug)]
enum ActivityCmd {
Invite {
/// The message to send to the user in the invite
#[structopt(long, default_value = "please join")]
msg: String,
/// Invite to spectate, if not provided, invites to join instead
#[structopt(long)]
spectate: bool,
/// The unique identifier for the user
id: String,
},
Accept,
Reply {
#[structopt(long)]
accept: bool,
},
Update(ActivityUpdateCmd),
}
#[derive(StructOpt, Debug)]
enum OverlayCmd {
Open,
Close,
Invite {
#[structopt(long)]
join: bool,
},
Voice,
GuildInvite {
code: String,
},
}
#[derive(StructOpt, Debug)]
enum RelationsCmd {
Print,
}
#[derive(StructOpt, Debug)]
enum Cmd {
Lobby(LobbyCmd),
Activity(ActivityCmd),
Overlay(OverlayCmd),
Relations(RelationsCmd),
Exit,
}
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let client = es::make_client(ds::Subscriptions::ALL).await;
//let user = client.user;
let wheel = client.wheel;
let discord = client.discord;
let (invites_tx, invites_rx) = ds::cc::unbounded();
let (joins_tx, joins_rx) = ds::cc::unbounded();
let mut activity_events = wheel.activity().0;
tokio::task::spawn(async move {
use activity::events::ActivityEvent;
while let Ok(ae) = activity_events.recv().await {
match ae {
ActivityEvent::Invite(invite) => {
if invites_tx.send(invite).is_err() {
break;
}
}
ActivityEvent::JoinRequest(jre) => {
tracing::info!("Received join request from {}", jre.user);
if joins_tx.send(jre.user.id).is_err() {
break;
}
}
_ => {}
}
}
});
let mut lobby_events = wheel.lobby().0;
let lobby_states = std::sync::Arc::new(lobby::state::LobbyStates::new());
let ls = lobby_states.clone();
tokio::task::spawn(async move {
while let Ok(le) = lobby_events.recv().await {
tracing::info!(event = ?le, "lobby event");
ls.on_event(le);
}
});
let relationships = discord.get_relationships().await?;
let mut rl_events = wheel.relationships().0;
let relationships = std::sync::Arc::new(relations::state::Relationships::new(relationships));
let rs = relationships.clone();
tokio::task::spawn(async move {
while let Ok(re) = rl_events.recv().await {
tracing::info!(event = ?re, "relationship event");
rs.on_event(re);
}
});
struct ReplState {
invites_rx: ds::cc::Receiver<activity::events::InviteEvent>,
joins_rx: ds::cc::Receiver<ds::user::UserId>,
created_lobby: Option<lobby::Lobby>,
lobbies: std::sync::Arc<lobby::state::LobbyStates>,
relationships: std::sync::Arc<relations::state::Relationships>,
}
let mut repl_state = ReplState {
invites_rx,
joins_rx,
created_lobby: None,
lobbies: lobby_states,
relationships,
};
let mut line = String::new();
loop {
line.clear();
let _ = std::io::stdin().read_line(&mut line);
line.pop();
match Cmd::from_iter_safe(std::iter::once("repl").chain(line.split(' '))) {
Ok(cmd) => {
if let Cmd::Exit = &cmd {
break;
}
async fn process(
discord: &ds::Discord,
cmd: &Cmd,
state: &mut ReplState,
) -> anyhow::Result<()> {
match cmd {
Cmd::Exit => unreachable!(),
Cmd::Lobby(lobby) => match lobby {
LobbyCmd::Create { capacity } => {
if let Some(lobby) = &state.created_lobby {
anyhow::bail!("Lobby {:#?} already exists", lobby);
}
let lobby = discord
.create_lobby(
ds::lobby::CreateLobbyBuilder::new()
.capacity(std::num::NonZeroU32::new(*capacity)),
)
.await?;
tracing::info!(lobby = ?lobby, "created");
discord.connect_lobby_voice(lobby.id).await?;
state.created_lobby = Some(lobby);
}
LobbyCmd::Delete => match &mut state.created_lobby {
Some(lobby) => {
discord.delete_lobby(lobby.id).await?;
state.created_lobby = None;
}
None => {
anyhow::bail!("No lobby to delete");
}
},
LobbyCmd::Connect { id, secret } => {
let id: lobby::LobbyId = id.parse().context("invalid lobby id")?;
discord
.connect_lobby(ds::lobby::ConnectLobby {
id,
secret: secret.clone(),
})
.await?;
discord.connect_lobby_voice(id).await?;
}
LobbyCmd::Update { capacity } => match &mut state.created_lobby {
Some(lobby) => {
let args = discord
.update_lobby(
lobby::UpdateLobbyBuilder::new(lobby)
.capacity(std::num::NonZeroU32::new(*capacity)),
)
.await?;
args.modify(lobby);
}
None => {
anyhow::bail!("No lobby to update");
}
},
LobbyCmd::Disconnect { id } => {
let id: lobby::LobbyId = id.parse().context("invalid lobby id")?;
discord.disconnect_lobby(id).await?;
}
LobbyCmd::Msg { id, msg } => {
let id: lobby::LobbyId = id.parse().context("invalid lobby id")?;
discord
.send_lobby_message(id, lobby::LobbyMessage::Text(msg.clone()))
.await?;
}
LobbyCmd::Search => {
let query = ds::lobby::search::SearchQuery::default();
let lobbies = discord.search_lobbies(query).await?;
tracing::info!("found lobbies: {:#?}", lobbies);
}
LobbyCmd::Print => {
tracing::info!("{:#?}", state.lobbies.lobbies.read());
}
},
Cmd::Activity(activity) => match activity {
ActivityCmd::Accept => {
let invite =
state.invites_rx.try_recv().context("no pending invites")?;
discord.accept_invite(&invite).await?;
}
ActivityCmd::Reply { accept } => {
let user = state
.joins_rx
.try_recv()
.context("no pending join requests")?;
discord.send_join_request_reply(user, *accept).await?;
}
ActivityCmd::Invite { id, msg, spectate } => {
let user_id = id.parse().context("invalid user id")?;
discord
.invite_user(
user_id,
msg,
if *spectate {
activity::ActivityActionKind::Spectate
} else {
activity::ActivityActionKind::Join
},
)
.await?;
}
ActivityCmd::Update(update) => {
let ab = activity::ActivityBuilder::new()
.state(&update.state)
.details(&update.details)
.party(
format!("repl-{}", std::process::id()),
std::num::NonZeroU32::new(1),
std::num::NonZeroU32::new(2),
activity::PartyPrivacy::Private,
)
.secrets(ds::activity::Secrets {
join: Some("joinme".to_owned()),
spectate: Some("spectateme".to_owned()),
r#match: None,
});
discord.update_activity(ab).await?;
}
},
Cmd::Overlay(overlay) => match overlay {
OverlayCmd::Open => {
discord
.set_overlay_visibility(overlay::Visibility::Visible)
.await?;
}
OverlayCmd::Close => {
discord
.set_overlay_visibility(overlay::Visibility::Hidden)
.await?;
}
OverlayCmd::Invite { join } => {
discord
.open_activity_invite(if *join {
overlay::InviteAction::Join
} else {
overlay::InviteAction::Spectate
})
.await?;
}
OverlayCmd::Voice => {
tracing::warn!(
"Not sending the overlay voice settings RPC as Discord will crash"
);
//client.open_voice_settings().await?;
}
OverlayCmd::GuildInvite { code } => {
discord.open_guild_invite(code).await?;
}
},
Cmd::Relations(rc) => match rc {
RelationsCmd::Print => {
tracing::info!("{:#?}", state.relationships.relationships.read());
}
},
}
Ok(())
}
if let Err(e) = process(&discord, &cmd, &mut repl_state).await {
tracing::error!("{:#?} failed - {:#}", cmd, e);
}
}
Err(e) => {
tracing::error!("{}", e);
continue;
}
}
}
discord.disconnect().await;
Ok(())
}
|
//!
//! Channel Library
//!
#![deny(
bad_style,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features
)]
#![cfg_attr(not(debug_assertions), deny(warnings))]
pub mod api;
pub mod iota_channels_lite;
pub mod security;
pub mod types;
use crate::security::keystore::calculate_hash;
fn authenticate(key: &str, hash: String) -> bool {
calculate_hash(key.to_string()) == hash
}
use std::time::{SystemTime, UNIX_EPOCH};
fn timestamp_in_sec() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
|
use super::*;
use crate::support::*;
/// Represents a function in LLVM IR
///
/// Functions are subtypes of llvm::Value, llvm::GlobalValue, and llvm::GlobalObject
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct Function(ValueBase);
impl Constant for Function {}
impl Value for Function {
fn base(&self) -> ValueBase {
self.0
}
}
impl GlobalValue for Function {}
impl GlobalObject for Function {}
impl Function {
pub fn arity(self) -> usize {
extern "C" {
fn LLVMCountParams(fun: Function) -> u32;
}
unsafe { LLVMCountParams(self) as usize }
}
pub fn arguments(self) -> Vec<ArgumentValue> {
extern "C" {
fn LLVMGetParams(fun: Function, args: *mut ArgumentValue);
}
let len = self.arity();
let mut args = Vec::with_capacity(len);
unsafe {
LLVMGetParams(self, args.as_mut_ptr());
args.set_len(len);
}
args
}
pub fn delete(self) {
extern "C" {
fn LLVMDeleteFunction(fun: Function);
}
unsafe { LLVMDeleteFunction(self) }
}
pub fn has_personality_fn(self) -> bool {
extern "C" {
fn LLVMHasPersonalityFn(fun: Function) -> bool;
}
unsafe { LLVMHasPersonalityFn(self) }
}
pub fn personality_fn(self) -> Function {
extern "C" {
fn LLVMGetPersonalityFn(fun: Function) -> Function;
}
unsafe { LLVMGetPersonalityFn(self) }
}
pub fn set_personality_fn(self, personality: Function) {
extern "C" {
fn LLVMSetPersonalityFn(fun: Function, personality: Function);
}
unsafe { LLVMSetPersonalityFn(self, personality) }
}
/// Get this function's calling convention
pub fn calling_convention(self) -> CallConv {
extern "C" {
fn LLVMGetFunctionCallConv(fun: Function) -> u32;
}
unsafe { LLVMGetFunctionCallConv(self) }.into()
}
/// Set this function's calling convention
pub fn set_calling_convention(self, cc: CallConv) {
extern "C" {
fn LLVMSetFunctionCallConv(fun: Function, cc: u32);
}
unsafe { LLVMSetFunctionCallConv(self, cc.into()) }
}
/// Get the name of the garbage collector strategy to use during codegen, if set
pub fn gc(self) -> Option<StringRef> {
extern "C" {
fn LLVMGetGC(fun: Function) -> *const std::os::raw::c_char;
}
unsafe {
let ptr = LLVMGetGC(self);
if ptr.is_null() {
None
} else {
Some(StringRef::from_ptr(ptr))
}
}
}
/// Set the name of the garbage collector strategy for this function
pub fn set_gc<S: Into<StringRef>>(self, gc: S) {
extern "C" {
fn LLVMSetGC(fun: Function, name: *const std::os::raw::c_char);
}
let gc = gc.into();
let c_str = gc.to_cstr();
unsafe { LLVMSetGC(self, c_str.as_ptr()) }
}
pub fn num_blocks(self) -> usize {
extern "C" {
fn LLVMCountBasicBlocks(fun: Function) -> u32;
}
unsafe { LLVMCountBasicBlocks(self) as usize }
}
pub fn entry(self) -> Option<Block> {
extern "C" {
fn LLVMGetEntryBasicBlock(fun: Function) -> Block;
}
let block = unsafe { LLVMGetEntryBasicBlock(self) };
if block.is_null() {
None
} else {
Some(block)
}
}
pub fn blocks(self) -> impl Iterator<Item = Block> {
BlockIter::new(self)
}
pub fn append_block(self, block: Block) {
extern "C" {
fn LLVMAppendExistingBasicBlock(fun: Function, bb: Block);
}
unsafe { LLVMAppendExistingBasicBlock(self, block) }
}
/// Set an attribute on this function at the given index
pub fn add_attribute_at_index<A: Attribute>(self, attr: A, index: AttributePlace) {
attr.add(self, index)
}
/// Adds `attr` to this function
pub fn add_attribute<A: Attribute>(self, attr: A) {
self.add_attribute_at_index(attr, AttributePlace::Function);
}
/// Adds `attr` to the `n`th parameter of this function
pub fn add_param_attribute<A: Attribute>(self, n: u32, attr: A) {
self.add_attribute_at_index(attr, AttributePlace::Argument(n))
}
/// Adds `attr` to the return value of this function
pub fn add_return_attribute<A: Attribute>(self, attr: A) {
self.add_attribute_at_index(attr, AttributePlace::ReturnValue)
}
/// Removes `attr` from this function at the given index
pub fn remove_attribute_at_index<A: Attribute>(self, attr: A, index: AttributePlace) {
attr.remove(self, index)
}
/// Removes `attr` from the function
pub fn remove_attribute<A: Attribute>(self, attr: A) {
self.remove_attribute_at_index(attr, AttributePlace::Function)
}
/// Removes `attr` from the `n`th parameter of this function
pub fn remove_param_attribute<A: Attribute>(self, n: u32, attr: A) {
self.remove_attribute_at_index(attr, AttributePlace::Argument(n))
}
/// Removes `attr` from the return value of this function
pub fn remove_return_attribute<A: Attribute>(self, attr: A) {
self.remove_attribute_at_index(attr, AttributePlace::ReturnValue)
}
/// Set the debug info subprogram attached to this function
pub fn set_di_subprogram(self, subprogram: Metadata) {
extern "C" {
fn LLVMSetSubprogram(fun: Function, subprogram: Metadata);
}
unsafe { LLVMSetSubprogram(self, subprogram) }
}
}
impl TryFrom<ValueBase> for Function {
type Error = InvalidTypeCastError;
fn try_from(value: ValueBase) -> Result<Self, Self::Error> {
match value.kind() {
ValueKind::Function => Ok(Self(value)),
_ => Err(InvalidTypeCastError),
}
}
}
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct ArgumentValue(ValueBase);
impl Value for ArgumentValue {
fn base(&self) -> ValueBase {
self.0
}
}
impl ArgumentValue {
pub fn parent(self) -> Function {
extern "C" {
fn LLVMGetParamParent(arg: ArgumentValue) -> Function;
}
unsafe { LLVMGetParamParent(self) }
}
pub fn set_alignment(self, align: usize) {
extern "C" {
fn LLVMSetParamAlignment(arg: ArgumentValue, align: u32);
}
unsafe { LLVMSetParamAlignment(self, align.try_into().unwrap()) }
}
}
impl TryFrom<ValueBase> for ArgumentValue {
type Error = InvalidTypeCastError;
fn try_from(value: ValueBase) -> Result<Self, Self::Error> {
match value.kind() {
ValueKind::Argument => Ok(Self(value)),
_ => Err(InvalidTypeCastError),
}
}
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum CallConv {
C = 0,
Fast = 8,
Cold = 9,
GHC = 10,
HiPE = 11,
WebkitJS = 12,
AnyReg = 13,
PreserveMost = 14,
PreserveAll = 15,
Swift = 16,
CXX_FastTLS = 17,
X86_Stdcall = 64,
X86_Fastcall = 65,
ARMAPCS = 66,
ARMAAPCS = 67,
ARMAAPCSVFP = 68,
MSP430INTR = 69,
X86_ThisCall = 70,
PTXKernel = 71,
PTXDevice = 72,
SPIRFUNC = 75,
SPIRKERNEL = 76,
IntelOCLBI = 77,
X8664SysV = 78,
Win64 = 79,
X86_VectorCall = 80,
HHVM = 81,
HHVMC = 82,
X86INTR = 83,
AVRINTR = 84,
AVRSIGNAL = 85,
AVRBUILTIN = 86,
AMDGPUVS = 87,
AMDGPUGS = 88,
AMDGPUPS = 89,
AMDGPUCS = 90,
AMDGPUKERNEL = 91,
X86_RegCall = 92,
AMDGPUHS = 93,
MSP430BUILTIN = 94,
AMDGPULS = 95,
AMDGPUES = 96,
Other(u32),
}
impl Into<u32> for CallConv {
fn into(self) -> u32 {
match self {
Self::C => 0,
Self::Fast => 8,
Self::Cold => 9,
Self::GHC => 10,
Self::HiPE => 11,
Self::WebkitJS => 12,
Self::AnyReg => 13,
Self::PreserveMost => 14,
Self::PreserveAll => 15,
Self::Swift => 16,
Self::CXX_FastTLS => 17,
Self::X86_Stdcall => 64,
Self::X86_Fastcall => 65,
Self::ARMAPCS => 66,
Self::ARMAAPCS => 67,
Self::ARMAAPCSVFP => 68,
Self::MSP430INTR => 69,
Self::X86_ThisCall => 70,
Self::PTXKernel => 71,
Self::PTXDevice => 72,
Self::SPIRFUNC => 75,
Self::SPIRKERNEL => 76,
Self::IntelOCLBI => 77,
Self::X8664SysV => 78,
Self::Win64 => 79,
Self::X86_VectorCall => 80,
Self::HHVM => 81,
Self::HHVMC => 82,
Self::X86INTR => 83,
Self::AVRINTR => 84,
Self::AVRSIGNAL => 85,
Self::AVRBUILTIN => 86,
Self::AMDGPUVS => 87,
Self::AMDGPUGS => 88,
Self::AMDGPUPS => 89,
Self::AMDGPUCS => 90,
Self::AMDGPUKERNEL => 91,
Self::X86_RegCall => 92,
Self::AMDGPUHS => 93,
Self::MSP430BUILTIN => 94,
Self::AMDGPULS => 95,
Self::AMDGPUES => 96,
Self::Other(cc) => cc,
}
}
}
impl From<u32> for CallConv {
fn from(cc: u32) -> Self {
match cc {
0 => Self::C,
8 => Self::Fast,
9 => Self::Cold,
10 => Self::GHC,
11 => Self::HiPE,
12 => Self::WebkitJS,
13 => Self::AnyReg,
14 => Self::PreserveMost,
15 => Self::PreserveAll,
16 => Self::Swift,
17 => Self::CXX_FastTLS,
64 => Self::X86_Stdcall,
65 => Self::X86_Fastcall,
66 => Self::ARMAPCS,
67 => Self::ARMAAPCS,
68 => Self::ARMAAPCSVFP,
69 => Self::MSP430INTR,
70 => Self::X86_ThisCall,
71 => Self::PTXKernel,
72 => Self::PTXDevice,
75 => Self::SPIRFUNC,
76 => Self::SPIRKERNEL,
77 => Self::IntelOCLBI,
78 => Self::X8664SysV,
79 => Self::Win64,
80 => Self::X86_VectorCall,
81 => Self::HHVM,
82 => Self::HHVMC,
83 => Self::X86INTR,
84 => Self::AVRINTR,
85 => Self::AVRSIGNAL,
86 => Self::AVRBUILTIN,
87 => Self::AMDGPUVS,
88 => Self::AMDGPUGS,
89 => Self::AMDGPUPS,
90 => Self::AMDGPUCS,
91 => Self::AMDGPUKERNEL,
92 => Self::X86_RegCall,
93 => Self::AMDGPUHS,
94 => Self::MSP430BUILTIN,
95 => Self::AMDGPULS,
96 => Self::AMDGPUES,
n => Self::Other(n),
}
}
}
|
use piston_window::*;
use piston_window::types::Color;
use rand::{thread_rng, Rng};
use direction::Direction;
use snake::Snake;
use draw::{draw_pixel, draw_square};
const BORDER_COLOR: Color = [0.5, 0.0, 0.5, 1.0];
const APPLE_COLOR: Color = [0.8, 0.1, 0.1, 1.0];
const GAMEOVER_COLOR: Color = [0.8, 0.0, 0.2, 0.5];
const INITIAL_PERIOD: f64 = 0.2;
const MINIMAL_PERIOD: f64 = 0.08;
const RESTART_TIME: f64 = 1.0;
pub struct Game {
snake: Snake,
apple_exists: bool,
apple_x: i32,
apple_y: i32,
width: i32,
height: i32,
period: f64,
game_over: bool,
waiting_time: f64,
}
impl Game {
pub fn new(width: i32, height: i32) -> Game {
let mut random = thread_rng();
Game {
snake: Snake::new(2,2),
waiting_time: 0.0,
apple_exists: true,
apple_x: random.gen_range(2, width-5),
apple_y: random.gen_range(2, height-5),
width,
height,
period: INITIAL_PERIOD,
game_over: false
}
}
// private functions
fn check_if_eating(&mut self){
let (head_x, head_y): (i32, i32) = self.snake.head_position();
if self.apple_exists && self.apple_x == head_x && self.apple_y == head_y {
self.apple_exists = false;
self.snake.restore_tail();
}
}
fn check_if_snake_alive(&self, direction: Option<Direction>) -> bool{
let (new_x, new_y) = self.snake.next_head(direction);
if self.snake.tail_collision(new_x, new_y){
return false;
}
new_x > 0 && new_y > 0 && new_x < self.width -1 && new_y < self.height -1
}
fn new_apple(&mut self) {
let mut random = thread_rng();
let mut new_x = random.gen_range(1, self.width-1);
let mut new_y = random.gen_range(1, self.height-1);
while self.snake.tail_collision(new_x, new_y){
new_x = random.gen_range(1, self.width-1);
new_y = random.gen_range(1, self.height-1);
}
self.apple_x = new_x;
self.apple_y = new_y;
self.apple_exists = true;
}
fn update_snake(&mut self, direction: Option<Direction>) {
if self.check_if_snake_alive(direction) {
self.snake.move_forward(direction);
self.check_if_eating();
}else{
self.game_over = true;
}
self.waiting_time = 0.0;
}
fn restart(&mut self){
let mut random = thread_rng();
self.snake = Snake::new(2,2);
self.waiting_time = 0.0;
self.apple_exists = true;
self.apple_x = random.gen_range(2, self.width-5);
self.apple_y = random.gen_range(2, self.height-5);
self.period = INITIAL_PERIOD;
self.game_over = false;
}
// public functions
pub fn draw(&self, con: &Context, graphics: &mut G2d) {
self.snake.draw(con, graphics);
if self.apple_exists {
draw_pixel(APPLE_COLOR, self.apple_x, self.apple_y, con, graphics);
}
draw_square(BORDER_COLOR, 0, 0, self.width,1,con,graphics);
draw_square(BORDER_COLOR, 0, self.height -1,self.width,1,con,graphics);
draw_square(BORDER_COLOR, 0, 0, 1, self.height,con,graphics);
draw_square(BORDER_COLOR, self.width - 1, 0,1, self.height, con,graphics);
if self.game_over {
draw_square(GAMEOVER_COLOR, 0, 0, self.width,self.height,con,graphics);
}
}
pub fn update(&mut self, delta_time: f64) {
self.waiting_time += delta_time;
if self.game_over {
if self.waiting_time > RESTART_TIME {
self.restart();
}
return;
}
if self.waiting_time > self.period{
self.update_snake(None);
}
if !self.apple_exists {
self.new_apple();
if self.period > MINIMAL_PERIOD {
//incrementar la velocidad del juego
self.period-=0.01;
}
}
}
pub fn key_pressed(&mut self, key: Key){
if self.game_over {
return;
}
let direction = match key {
Key::Up => Some(Direction::Up),
Key::Down => Some(Direction::Down),
Key::Left => Some(Direction::Left),
Key::Right => Some(Direction::Right),
_ => None
};
//si la tecla corresponde a una dirección
if direction != None {
if direction.unwrap() == self.snake.head_direction().get_inverse(){
return;
}
self.update_snake(direction);
}
}
} |
#[allow(unused_imports)]
use log::info;
use luminance_glfw::GlfwSurface;
use luminance_windowing::{CursorMode, WindowOpt};
use std::process::exit;
use spacegame::game::{Game, GameBuilder};
use spacegame::config::{load_config, AudioConfig, GameEngineConfig, InputConfig, PlayerConfig};
use spacegame::gameplay::inventory::Inventory;
use spacegame::gameplay::level::difficulty::DifficultyConfig;
use spacegame::gameplay::Action;
use spacegame::paths::get_assets_path;
use spacegame::save::read_saved_data;
use spacegame::scene::loading::LoadingScene;
#[allow(unused_imports)]
use spacegame::scene::main_menu::MainMenu;
#[allow(unused_imports)]
use spacegame::scene::particle_scene::ParticleScene;
use spacegame::DIMENSIONS;
fn main() {
let surface = GlfwSurface::new_gl33(
"EverFight",
WindowOpt::default()
.set_cursor_mode(CursorMode::Invisible)
.set_dim(DIMENSIONS),
);
match surface {
Ok(surface) => main_loop(surface),
Err(e) => {
eprintln!("Error = {}", e);
exit(1);
}
}
}
fn main_loop(mut surface: GlfwSurface) {
dotenv::dotenv().ok();
pretty_env_logger::init();
let base_path = get_assets_path();
let player_config_path = base_path.join("config/player_controller.json");
let player_config: PlayerConfig = load_config(&player_config_path).unwrap_or_else(|e| {
log::info!("Will use default PlayerConfig because = {:?}", e);
PlayerConfig::default()
});
let engine_config_path = base_path.join("config/engine.json");
let engine_config: GameEngineConfig = load_config(&engine_config_path).unwrap_or_else(|e| {
log::info!("Will use default GameEngineConfig because = {:?}", e);
GameEngineConfig::default()
});
let difficulty_config_path = base_path.join("config/difficulty.json");
let difficulty_config: DifficultyConfig =
load_config(&difficulty_config_path).unwrap_or_else(|e| {
log::info!("Will use default Difficulty because = {:?}", e);
DifficultyConfig::default()
});
let input_config_path = base_path.join("config/input.json");
let input_config: Result<InputConfig, _> = load_config(&input_config_path);
let audio_config_path = base_path.join("config/audio.json");
let audio_config: Result<AudioConfig, _> = load_config(&audio_config_path);
let saved_data = read_saved_data();
let mut builder: GameBuilder<Action> = GameBuilder::new(&mut surface)
.for_scene(Box::new(LoadingScene::new(
vec![],
vec![
"music/spacelifeNo14.ogg".to_string(),
"music/Finding-Flora.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_09.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_01.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_02.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_03.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_04.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_05.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_06.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_07.wav".to_string(),
"sounds/scifi_kit/Laser/Laser_08.wav".to_string(),
"sounds/explosion.wav".to_string(),
"sounds/powerUp2.mp3".to_string(),
],
MainMenu::default(),
)))
.with_resource(saved_data)
.with_resource(player_config)
.with_resource(engine_config)
.with_resource(difficulty_config)
.with_resource(Inventory::default());
if let Ok(input_config) = input_config {
let (km, mm) = input_config.input_maps();
builder = builder.with_input_config(km, mm);
}
if let Ok(audio_config) = audio_config {
builder = builder.with_audio_config(audio_config);
}
let mut game: Game<Action> = builder.build();
game.run();
}
|
#[macro_use] extern crate criterion;
use dsrv::server;
use criterion::Criterion;
pub fn init_server(c: &mut Criterion) {
c.bench_function("init_server", |b| b.iter(|| server::Server::new()));
}
criterion_group!(init_server_bench, init_server);
criterion_main!(init_server_bench);
|
use actix_web::{web, Error, HttpResponse};
use juniper_actix::{graphql_handler, playground_handler};
use std::sync::Mutex;
pub async fn graphiql() -> Result<HttpResponse, Error> {
playground_handler("/graphql", None).await
}
pub async fn graphql(
req: actix_web::HttpRequest,
payload: actix_web::web::Payload,
app_data: web::Data<Mutex<crate::AppData>>,
) -> Result<HttpResponse, Error> {
let jwt_claims = crate::auth::service::verify_session(&req);
let app_data = app_data
.lock()
.map_err(|err| println!("{:#?}", err))
.unwrap();
let context = super::Context {
client: app_data.datastore_client.clone(),
jwt_claims,
};
graphql_handler(&app_data.graphql_schema, &context, req, payload).await
}
|
use parser::types::{Pass, ProgramError, Statement, Expression, Literal, SourceCodeLocation, TokenType, DataKeyword, Type, StatementType, ExpressionType, FunctionHeader};
use smoked::instruction::{Instruction, InstructionType};
use std::collections::{BTreeMap, HashMap, HashSet};
use crate::lambda_lifting::{variable_or_module_name, leak_reference};
use std::iter::FromIterator;
#[derive(Debug, PartialEq)]
pub enum ConstantValues<'a> {
Literal(Literal<'a>),
Function {
arity: usize,
ip: usize,
name: &'a str,
context_variables: &'a [&'a str],
},
Class {
name: &'a str,
}
}
#[derive(Clone, Copy)]
pub enum BufferSelection {
DryRun,
Rom,
Function,
}
type CompilerResult<'a, R> = Result<R, Vec<ProgramError<'a>>>;
#[derive(Debug)]
pub struct ClassMembers<'a> {
methods: HashMap<&'a str, &'a str>,
getters: HashMap<&'a str, &'a str>,
setters: HashMap<&'a str, &'a str>,
static_methods: HashMap<&'a str, &'a str>,
}
pub struct TraitMembers<'a> {
methods: &'a [FunctionHeader<'a>],
getters: &'a [FunctionHeader<'a>],
setters: &'a [FunctionHeader<'a>],
static_methods: &'a [FunctionHeader<'a>],
}
impl<'a> ClassMembers<'a> {
pub(crate) fn length(&self) -> usize {
self.methods.len() + self.getters.len() + self.setters.len() + self.static_methods.len()
}
pub(crate) fn for_each_member<F: FnMut(&'a str, &'a str) -> ()>(&self, mut action: F) {
for ms in vec![&self.methods, &self.getters, &self.setters, &self.static_methods] {
for (key, value) in ms {
action(key, value);
}
}
}
pub(crate) fn for_each_member_in_order<F: FnMut(&'a str, &'a str) -> ()>(&self, mut action: F) {
let mut ordered_map = BTreeMap::default();
for ms in vec![&self.methods, &self.getters, &self.setters, &self.static_methods] {
for (key, value) in ms {
ordered_map.insert(key, value);
}
}
for (key, value) in ordered_map {
action(*key, *value)
}
}
}
pub struct Compiler<'a> {
pub constants: Vec<ConstantValues<'a>>,
buffer: Vec<Instruction>,
pub class_members: HashMap<&'a str, ClassMembers<'a>>,
traits: HashMap<&'a str, TraitMembers<'a>>,
function_instructions: Vec<Instruction>,
instructions: Vec<Instruction>,
locals: HashMap<usize, usize>,
pub locations: Vec<SourceCodeLocation<'a>>,
scopes: Vec<HashMap<&'a str, usize>>,
toggle_selection: BufferSelection,
}
impl<'a> Compiler<'a> {
pub fn new(locals: HashMap<usize, usize>) -> Compiler<'a> {
Compiler {
buffer: vec![],
class_members: HashMap::default(),
constants: vec![],
function_instructions: vec![],
instructions: vec![],
locations: vec![],
scopes: vec![HashMap::default()],
toggle_selection: BufferSelection::Rom,
traits: HashMap::default(),
locals,
}
}
}
impl<'a> Compiler<'a> {
fn constant_from_literal(&mut self, value: ConstantValues<'a>) -> usize {
match self.constants.iter().position(|i| i == &value) {
Some(i) => i,
None => {
self.constants.push(value);
self.constants.len() - 1
}
}
}
#[cfg(target_os = "macos")]
fn get_write_syscall_number_constant(&mut self) -> usize {
self.constant_from_literal(ConstantValues::Literal(Literal::Integer(4)))
}
#[cfg(not(target_os = "macos"))]
fn get_write_syscall_number_constant(&mut self) -> usize {
self.constant_from_literal(ConstantValues::Literal(Literal::Integer(1)))
}
fn toggle_selection(&mut self, selection: BufferSelection) {
self.toggle_selection = selection;
}
fn add_instruction(&mut self, instruction: Instruction) {
(match self.toggle_selection {
BufferSelection::DryRun => &mut self.buffer,
BufferSelection::Function => &mut self.function_instructions,
BufferSelection::Rom => &mut self.instructions,
}).push(instruction)
}
fn drain_buffer(&mut self) {
let buffer = match self.toggle_selection {
BufferSelection::DryRun => panic!("WHAT YOU DOING"),
BufferSelection::Function => &mut self.function_instructions,
BufferSelection::Rom => &mut self.instructions,
};
buffer.extend_from_slice(&self.buffer);
self.buffer.clear();
}
fn add_function<I: Iterator<Item=&'a Statement<'a>>>(
&mut self,
name: &'a str,
arguments: &'a [&'a str],
body: I,
context_variables: &'a [&'a str],
) -> CompilerResult<'a, usize> {
let constant = self.constant_from_literal(ConstantValues::Function {
arity: arguments.len(),
ip: self.function_instructions.len(),
context_variables,
name,
});
let previous = self.toggle_selection;
let prev_functions_size = self.function_instructions.len(); self.toggle_selection(BufferSelection::Function);
let mut new_scope = HashMap::default();
for (i, n) in arguments.iter().cloned().enumerate() {
new_scope.insert(n, i);
}
for (i, n) in context_variables.iter().cloned().enumerate() {
new_scope.insert(n, i+arguments.len());
}
self.scopes.push(new_scope);
for s in body {
self.pass(s)?;
}
if prev_functions_size != self.function_instructions.len() &&
self.function_instructions.last().map(|i| i.instruction_type != InstructionType::Return)
.unwrap_or(true) {
self.pass_return(&None)?;
}
self.scopes.pop();
self.toggle_selection(previous);
Ok(constant)
}
fn add_set_instruction(&mut self, scope_id: usize, var_id: usize) {
if scope_id == 0 {
self.add_instruction(Instruction {
instruction_type: InstructionType::SetGlobal(var_id),
location: self.locations.len() - 1,
});
} else {
self.add_instruction(Instruction {
instruction_type: InstructionType::SetLocal(var_id),
location: self.locations.len() - 1,
});
}
}
fn class_members_to_vec(&mut self, statements: &'a [Box<Statement<'a>>], prefix: Option<&'static str>) -> CompilerResult<'a, HashMap<&'a str, &'a str>> {
let mut members = HashMap::default();
for s in statements {
if let StatementType::Expression { expression, .. } = &s.statement_type {
if let ExpressionType::Binary {
right: box Expression {
expression_type: ExpressionType::VariableLiteral { identifier: name },
..
},
operator: TokenType::Comma,
left: box Expression {
expression_type: ExpressionType::VariableLiteral { identifier: new_name },
..
}
} = &expression.expression_type {
let _ = self.constant_from_literal(ConstantValues::Literal(
Literal::QuotedString(*new_name)
));
let storing_name = leak_reference(format!("{}{}", prefix.unwrap_or(""), name)).as_str();
let _ = self.constant_from_literal(ConstantValues::Literal(
Literal::QuotedString(*name)
));
let _ = self.constant_from_literal(ConstantValues::Literal(
Literal::QuotedString(storing_name)
));
members.insert(storing_name, *new_name);
} else {
return Err(self.create_single_error("Expected variable literal on class member".to_string()))
}
} else {
return Err(self.create_single_error("Expected expression statement on class member".to_string()))
}
}
Ok(members)
}
fn validate_trait_functions(
&self,
trait_functions: &'a [FunctionHeader<'a>],
class_functions: &'a [Box<Statement<'a>>],
) -> CompilerResult<'a, ()> {
let trait_functions_set: HashSet<&str> = HashSet::from_iter(
trait_functions.iter()
.map(|tf| tf.name)
);
let functions_in_implementation = HashSet::from_iter(
class_functions.iter()
.map(|s|
if let StatementType::Expression { expression } = &s.statement_type {
if let ExpressionType::Binary { right, ..} = &expression.expression_type {
if let ExpressionType::VariableLiteral { identifier } = &right.expression_type {
identifier.clone()
} else {
panic!("Variable Literal expected, got {:?}", right);
}
} else {
panic!("Binary expression expected, got {:?}", expression);
}
} else {
panic!("Expression statement expected, got {:?}", s);
}
)
);
if trait_functions_set != functions_in_implementation {
Err(self.create_single_error(format!(
"Expected functions: {:?}, got {:?}", trait_functions_set, functions_in_implementation
)))
} else {
Ok(())
}
}
fn validate_trait_implementation(
&self,
trait_info: &TraitMembers<'a>,
methods: &'a [Box<Statement<'a>>],
getters: &'a [Box<Statement<'a>>],
setters: &'a [Box<Statement<'a>>],
static_methods: &'a [Box<Statement<'a>>],
) -> CompilerResult<'a, ()> {
self.validate_trait_functions(trait_info.methods, methods)?;
self.validate_trait_functions(trait_info.getters, getters)?;
self.validate_trait_functions(trait_info.setters, setters)?;
self.validate_trait_functions(trait_info.static_methods, static_methods)?;
Ok(())
}
fn update_class(
&mut self,
class_name: &'a str,
methods: &HashMap<&'a str, &'a str>,
) -> CompilerResult<'a, ()> {
let class_global = self.scopes[0].get(class_name).unwrap().clone();
let location = self.locations.len() - 1;
for (method_name, global_name) in methods {
let function_global = self.scopes[0].get(global_name).unwrap().clone();
let method_name_constant = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString(method_name)));
self.add_instruction(Instruction {
instruction_type: InstructionType::GetGlobal(function_global),
location,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(method_name_constant),
location,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::GetGlobal(class_global),
location,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectSet,
location,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::SetGlobal(class_global),
location,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location,
});
}
Ok(())
}
fn store_class_members(
&mut self,
class_name: &'a str,
methods: &'a [Box<Statement<'a>>],
getters: &'a [Box<Statement<'a>>],
setters: &'a [Box<Statement<'a>>],
static_methods: &'a [Box<Statement<'a>>],
) -> CompilerResult<'a, ()> {
let methods = self.class_members_to_vec(methods, None)?;
let getters = self.class_members_to_vec(getters, Some("@getter_"))?;
let setters = self.class_members_to_vec(setters, Some("@setter_"))?;
let static_methods = self.class_members_to_vec(static_methods, Some("@static_"))?;
let members = ClassMembers { methods, getters, setters, static_methods };
self.class_members.insert(class_name, members);
Ok(())
}
fn create_single_error(&self, message: String) -> Vec<ProgramError<'a>> {
vec![ProgramError {
location: self.locations.last().unwrap().clone(),
message
}]
}
fn new_global(&mut self, name: &'a str) -> usize {
if let Some(global_index) = self.scopes[0].get(name) {
*global_index
} else {
let global_index = self.scopes[0].len();
self.scopes[0].insert(name, global_index);
global_index
}
}
fn expression_or_nil(&mut self, expression: &'a Option<Expression<'a>>) -> CompilerResult<'a, ()> {
if let Some(e) = expression {
self.pass_expression(e)?;
} else {
let c0 = self.constant_from_literal(ConstantValues::Literal(Literal::Keyword(DataKeyword::Nil)));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(c0),
location: self.locations.len() - 1,
});
}
Ok(())
}
fn save_trait_constants(&mut self, headers: &[FunctionHeader], prefix: Option<&'a str>) {
for fh in headers.iter() {
let storing_name = leak_reference(format!("{}{}", prefix.unwrap_or(""), fh.name)).as_str();
self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString(
storing_name
)));
}
}
}
impl<'a> Pass<'a, Vec<Instruction>> for Compiler<'a> {
fn run(&mut self, ss: &'a [Statement<'a>]) -> Result<Vec<Instruction>, Vec<ProgramError<'a>>> {
for s in ss {
if let StatementType::VariableDeclaration { name, .. } = s.statement_type {
let var_id = self.scopes[0].len();
self.scopes[0].insert(name, var_id);
}
}
for s in ss {
self.pass(s)?;
}
self.add_instruction(Instruction {
instruction_type: InstructionType::Return,
location: self.locations.len() - 1,
});
let mut instructions = self.instructions.clone();
for constant in self.constants.iter_mut() {
if let ConstantValues::Function { ip, .. } = constant {
*ip += self.instructions.len();
}
}
instructions.extend_from_slice(&self.function_instructions);
Ok(instructions)
}
fn before_pass(&mut self, s: &Statement<'a>) {
if !self.locations.contains(&s.location) {
self.locations.push(s.location.clone());
}
}
fn pass_expression_statement(
&mut self,
expression: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
self.pass_expression(expression)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_expression_literal(&mut self, value: &'a Literal<'a>) -> Result<(), Vec<ProgramError<'a>>> {
let constant_index = self.constant_from_literal(ConstantValues::Literal(value.clone()));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(constant_index),
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_uplift_class_variables(&mut self, name: &'a str) -> Result<(), Vec<ProgramError<'a>>> {
let nil_constant = self.constant_from_literal(ConstantValues::Literal(Literal::Keyword(DataKeyword::Nil)));
let class_constant = self.constant_from_literal(ConstantValues::Class { name });
let members = self.class_members.get(name).ok_or(self.create_single_error(format!("Class {} not declared yet", name)))?;
let mut names = vec![];
members.for_each_member(|k, m| {
names.push((k.clone(), m.clone()));
});
for (key, name) in names {
let key_constant = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString(key)));
self.pass_uplift_function_variables(name)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::Duplicate,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(4),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(key_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(class_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectSet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
}
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(nil_constant),
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_uplift_function_variables(
&mut self,
name: &'a str,
) -> Result<(), Vec<ProgramError<'a>>> {
let nil_constant = self.constant_from_literal(ConstantValues::Literal(Literal::Keyword(DataKeyword::Nil)));
let global = match self.scopes[0].iter().filter_map(|(fname, value)| {
if *fname == name {
Some(value)
} else {
None
}
}).next() {
Some(i) => *i,
None => {
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(nil_constant),
location: self.locations.len() - 1,
});
return Ok(())
},
};
let constant = match self.constants.iter().position(|i| {
return if let ConstantValues::Function { name: fname, context_variables, .. } = i {
*fname == name && context_variables.len() > 0
} else {
false
};
}) {
Some(i) => i,
None => {
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(nil_constant),
location: self.locations.len() - 1,
});
return Ok(())
},
};
let context_variables = if let ConstantValues::Function { context_variables, .. } = &self.constants[constant] {
*context_variables
} else {
return Err(vec![ProgramError {
location: self.locations.last().unwrap().clone(),
message: "Constant is not a function".to_string()
}]);
};
let array_size = self.constant_from_literal(ConstantValues::Literal(Literal::Integer(context_variables.len() as _)));
for context_variable in context_variables {
let local_in_scope = (&self.scopes[1..]).iter().rev()
.find(|scope| scope.get(context_variable).is_some())
.map(|scope| *scope.get(context_variable).unwrap());
if let Some(local) = local_in_scope {
self.add_instruction(Instruction {
instruction_type: InstructionType::Uplift(local),
location: self.locations.len() - 1,
});
} else {
return Err(vec![ProgramError {
location: self.locations.last().unwrap().clone(),
message: format!("Context variable {} was not found", context_variable),
}]);
}
}
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(array_size),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ArrayAlloc,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::MultiArraySet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::AttachArray(global),
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_variable_declaration(
&mut self,
identifier: &'a str,
expression: &'a Option<Expression<'a>>,
_statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let scope_id = self.scopes.len() - 1;
let var_id = if scope_id > 0 {
self.scopes[scope_id].len()
} else {
self.scopes[scope_id][identifier]
};
if scope_id > 0 {
self.scopes[scope_id].insert(identifier, var_id);
}
self.expression_or_nil(expression)?;
self.add_set_instruction(scope_id, var_id);
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_class_declaration(
&mut self,
name: &'a str,
properties: &'a [Box<Statement<'a>>],
methods: &'a [Box<Statement<'a>>],
static_methods: &'a [Box<Statement<'a>>],
setters: &'a [Box<Statement<'a>>],
getters: &'a [Box<Statement<'a>>],
superclass: &'a Option<Expression<'a>>,
_statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
self.store_class_members(name, methods, getters, setters, static_methods)?;
let constant = self.constant_from_literal(ConstantValues::Class {
name,
});
let name_constant = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString(name)));
let class_constant = self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("@class")),
);
let global_index = self.scopes[0].len();
self.scopes[0].insert(name, global_index);
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(name_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(class_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::AddTag,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::AddTag,
location: self.locations.len() - 1,
});
if let Some(e) = superclass {
let super_constant = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString("super")));
let class_constant = self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("@class")),
);
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(class_constant),
location: self.locations.len() - 1,
});
self.pass_expression(e)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::RemoveTag,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Call,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(super_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectSet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectMerge,
location: self.locations.len() - 1,
});
}
for property in properties {
if let StatementType::VariableDeclaration { expression, name} = &property.statement_type {
self.locations.push(property.location.clone());
self.expression_or_nil(expression)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
let property_constant = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString(name)));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(property_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectSet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
} else {
Err(self.create_single_error("Expecting variable declaration statement".to_owned()))?;
}
}
self.add_instruction(Instruction {
instruction_type: InstructionType::SetGlobal(global_index),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_trait_declaration(
&mut self,
name: &'a str,
statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
if let StatementType::TraitDeclaration {
methods, getters, setters, static_methods, ..
} = &statement.statement_type {
self.save_trait_constants(methods, None);
self.save_trait_constants(getters, Some("@getter_"));
self.save_trait_constants(setters, Some("@setter_"));
self.save_trait_constants(static_methods, Some("@static_"));
self.traits.insert(name, TraitMembers {
methods, getters, setters, static_methods,
});
let trait_constant = self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("@trait")),
);
let zero_constant = self.constant_from_literal(
ConstantValues::Literal(Literal::Integer(0)),
);
let global_index = self.new_global(name);
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(trait_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(zero_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectAlloc,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::AddTag,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::SetGlobal(global_index),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
}
Ok(())
}
fn pass_trait_implementation(
&mut self,
class_name: &'a Expression<'a>,
trait_name: &'a Expression<'a>,
methods: &'a [Box<Statement<'a>>],
static_methods: &'a [Box<Statement<'a>>],
setters: &'a [Box<Statement<'a>>],
getters: &'a [Box<Statement<'a>>],
_statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
if let Some(trait_info) = self.traits.get(variable_or_module_name(trait_name)?) {
self.validate_trait_implementation(trait_info, methods, getters, setters, static_methods)?;
} else {
Err(self.create_single_error(format!("Trait does not exist: {:?}", trait_name)))?;
}
let new_methods = self.class_members_to_vec(methods, None)?;
let new_getters = self.class_members_to_vec(getters, Some("@getter_"))?;
let new_setters = self.class_members_to_vec(setters, Some("@setter_"))?;
let new_static_methods = self.class_members_to_vec(static_methods, Some("@static_"))?;
let class_name_value = variable_or_module_name(class_name)?;
if let Some(class_members) = self.class_members.get_mut(class_name_value) {
class_members.methods.extend(new_methods.iter());
class_members.getters.extend(new_getters.iter());
class_members.setters.extend(new_setters.iter());
class_members.static_methods.extend(new_static_methods.iter());
self.update_class(class_name_value, &new_methods)?;
self.update_class(class_name_value, &new_getters)?;
self.update_class(class_name_value, &new_setters)?;
self.update_class(class_name_value, &new_static_methods)?;
let class_name_value = variable_or_module_name(class_name)?;
let trait_name_value = variable_or_module_name(trait_name)?;
let global = *self.scopes[0].get(class_name_value).unwrap();
let trait_constant = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString(
trait_name_value
)));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(trait_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::GetGlobal(global),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::AddTag,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::SetGlobal(global),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
Ok(())
} else {
Err(self.create_single_error(format!("class does not exist {:?}", class_name)))
}
}
fn pass_function_declaration(
&mut self,
name: &'a str,
arguments: &'a [&'a str],
body: &'a [Box<Statement<'a>>],
_statement: &'a Statement<'a>,
context_variables: &'a [&'a str],
) -> Result<(), Vec<ProgramError<'a>>> {
if self.scopes.len() == 1 {
let constant = self.add_function(name, arguments, body.iter().map(|i| i.as_ref()), context_variables)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(constant),
location: self.locations.len() - 1,
});
let global_index = self.new_global(name);
self.add_instruction(Instruction {
instruction_type: InstructionType::SetGlobal(global_index),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
}
Ok(())
}
fn pass_print(&mut self, expression: &'a Expression<'a>) -> Result<(), Vec<ProgramError<'a>>> {
let c0 = self.constant_from_literal(ConstantValues::Literal(Literal::Integer(1)));
let syscall = self.get_write_syscall_number_constant();
let c1 = self.constant_from_literal(ConstantValues::Literal(Literal::Integer(3)));
let newline = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString("\n")));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(newline),
location: self.locations.len() - 1,
});
self.pass_expression(expression)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::ToStr,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::StringConcat,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Push,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Strlen,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(c0),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(c1),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(syscall),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Syscall,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_return(&mut self, expression: &'a Option<Expression<'a>>) -> Result<(), Vec<ProgramError<'a>>> {
if let Some(e) = expression {
self.pass_expression(e)?;
} else {
let constant = self.constant_from_literal(ConstantValues::Literal(Literal::Keyword(DataKeyword::Nil)));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(constant),
location: self.locations.len() - 1,
})
};
self.add_instruction(Instruction {
instruction_type: InstructionType::Return,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_while(
&mut self,
condition: &'a Expression<'a>,
action: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let current_selection = self.toggle_selection;
self.toggle_selection(BufferSelection::DryRun);
self.pass_expression(condition)?;
self.toggle_selection(current_selection);
let condition_length = self.buffer.len() + 1;
self.drain_buffer();
self.toggle_selection(BufferSelection::DryRun);
self.pass(action)?;
self.toggle_selection(current_selection);
let body_length = self.buffer.len() + 1;
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(body_length),
location: self.locations.len() - 1,
});
self.drain_buffer();
self.add_instruction(Instruction {
instruction_type: InstructionType::Loop(condition_length + body_length),
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_checked_type(
&mut self,
value: &'a Expression<'a>,
checked_type: &'a Type,
) -> Result<(), Vec<ProgramError<'a>>> {
if checked_type.is_object_type() {
let tag_constant = match checked_type {
Type::Class => {
self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("@class"))
)
},
Type::Trait => {
self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("@trait"))
)
},
Type::UserDefined(expression) => {
self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString(
variable_or_module_name(expression)?
))
)
},
_ => panic!("Type is not object, as expected"),
};
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(tag_constant),
location: self.locations.len() - 1,
});
self.pass_expression(value)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::CheckTag,
location: self.locations.len() - 1,
});
} else {
self.pass_expression(value)?;
let type_index = match checked_type {
Type::Nil => 0,
Type::Boolean => 1,
Type::Integer => 2,
Type::Float => 3,
Type::String => 4,
Type::Function => 5,
Type::Array => 6,
_ => {
return Err(vec![ProgramError {
location: self.locations.last().unwrap().clone(),
message: format!("Type checking for {:?} not implemented yet", checked_type),
}]);
}
};
self.add_instruction(Instruction {
instruction_type: InstructionType::CheckType(type_index),
location: self.locations.len() - 1,
});
}
Ok(())
}
fn pass_get(&mut self, callee: &'a Expression<'a>, property: &'a str) -> Result<(), Vec<ProgramError<'a>>> {
let constant = self.constant_from_literal(ConstantValues::Literal(Literal::QuotedString(property)));
let class_constant = self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("@class")),
);
let static_constant = self.constant_from_literal(ConstantValues::Literal(
Literal::QuotedString(
leak_reference(format!("{}{}", "@static_", property)).as_str()
)
));
let getter_constant = self.constant_from_literal(ConstantValues::Literal(
Literal::QuotedString(
leak_reference(format!("{}{}", "@getter_", property)).as_str()
)
));
self.pass_expression(callee)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::Duplicate,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(class_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::CheckTag,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(4),
location: self.locations.len() - 1,
});
// Logic for static
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(static_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectGet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Jmp(12),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(getter_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectHas,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(5),
location: self.locations.len() - 1,
});
// logic for getter
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(getter_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectGet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Call,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Jmp(3),
location: self.locations.len() - 1,
});
// logic for property
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectGet,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_set(
&mut self,
callee: &'a Expression<'a>,
value: &'a Expression<'a>,
property: &'a str,
) -> Result<(), Vec<ProgramError<'a>>> {
let property_constant = self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString(property)),
);
let setter_constant = self.constant_from_literal(ConstantValues::Literal(
Literal::QuotedString(
leak_reference(format!("{}{}", "@setter_", property)).as_str()
)
));
self.pass_expression(value)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(setter_constant),
location: self.locations.len() - 1,
});
self.pass_expression(callee)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectHas,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(5),
location: self.locations.len() - 1,
});
// setter logic
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(setter_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectGet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Call,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Jmp(4),
location: self.locations.len() - 1,
});
// property logic
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(property_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectSet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_variable_literal(
&mut self,
identifier: &'a str,
expression: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
if let Some(scope_id) = self.locals.get(&expression.id()).cloned() {
let var_id = *self.scopes[scope_id].get(identifier).unwrap();
if scope_id == 0 {
self.add_instruction(Instruction {
instruction_type: InstructionType::GetGlobal(var_id),
location: self.locations.len() - 1,
});
} else {
self.add_instruction(Instruction {
instruction_type: InstructionType::GetLocal(var_id),
location: self.locations.len() - 1,
});
}
Ok(())
} else {
Err(vec![ProgramError {
message: format!("Variable literal {} not declared", identifier),
location: self.locations.last().unwrap().clone(),
}])
}
}
fn pass_variable_assignment(
&mut self,
identifier: &'a str,
expression_value: &'a Expression<'a>,
expression: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
if let Some(scope_id) = self.locals.get(&expression.id()).cloned() {
let var_id = match self.scopes[scope_id].get(identifier) {
Some(id) => *id,
None => {
let id = self.scopes[scope_id].len();
self.scopes[scope_id].insert(identifier, id);
id
}
};
self.pass_expression(expression_value)?;
self.add_set_instruction(scope_id, var_id);
Ok(())
} else {
Err(vec![ProgramError {
message: format!("Variable {} not declared on assignment", identifier),
location: self.locations.last().unwrap().clone(),
}])
}
}
fn pass_binary(
&mut self,
left: &'a Expression<'a>,
right: &'a Expression<'a>,
operator: &'a TokenType<'a>
) -> Result<(), Vec<ProgramError<'a>>> {
self.pass_expression(left)?;
self.pass_expression(right)?;
match operator {
TokenType::Plus => self.add_instruction(Instruction {
instruction_type: InstructionType::Plus,
location: self.locations.len() - 1,
}),
TokenType::Minus => self.add_instruction(Instruction {
instruction_type: InstructionType::Minus,
location: self.locations.len() - 1,
}),
TokenType::Slash => self.add_instruction(Instruction {
instruction_type: InstructionType::Div,
location: self.locations.len() - 1,
}),
TokenType::Star => self.add_instruction(Instruction {
instruction_type: InstructionType::Mult,
location: self.locations.len() - 1,
}),
TokenType::Greater => self.add_instruction(Instruction {
instruction_type: InstructionType::Greater,
location: self.locations.len() - 1,
}),
TokenType::GreaterEqual => self.add_instruction(Instruction {
instruction_type: InstructionType::GreaterEqual,
location: self.locations.len() - 1,
}),
TokenType::Less => self.add_instruction(Instruction {
instruction_type: InstructionType::Less,
location: self.locations.len() - 1,
}),
TokenType::LessEqual => self.add_instruction(Instruction {
instruction_type: InstructionType::LessEqual,
location: self.locations.len() - 1,
}),
TokenType::EqualEqual => self.add_instruction(Instruction {
instruction_type: InstructionType::Equal,
location: self.locations.len() - 1,
}),
TokenType::BangEqual => self.add_instruction(Instruction {
instruction_type: InstructionType::NotEqual,
location: self.locations.len() - 1,
}),
TokenType::And => self.add_instruction(Instruction {
instruction_type: InstructionType::And,
location: self.locations.len() - 1,
}),
TokenType::Or => self.add_instruction(Instruction {
instruction_type: InstructionType::Or,
location: self.locations.len() - 1,
}),
TokenType::Bar => {
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
},
t => Err(vec![ProgramError {
message: format!("Invalid operator {:?}", t),
location: self.locations.last().unwrap().clone(),
}])?,
}
Ok(())
}
fn pass_call(
&mut self,
callee: &'a Expression<'a>,
arguments: &'a [Box<Expression<'a>>],
_expression_id: usize,
) -> Result<(), Vec<ProgramError<'a>>> {
arguments
.iter()
.map(|a| self.pass_expression(a))
.collect::<Result<Vec<()>, Vec<ProgramError>>>()?;
self.pass_expression(callee)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::Duplicate,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::CheckType(7),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(19),
location: self.locations.len() - 1,
});
let class_constant = self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("@class")),
);
let init_method = self.constant_from_literal(
ConstantValues::Literal(Literal::QuotedString("init")),
);
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(init_method),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(class_constant),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::RemoveTag,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Call,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectHas,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(12),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Duplicate,
location: self.locations.len() - 1,
});
let scope_id = self.scopes.len() - 1;
let var_id = self.scopes[scope_id].len();
let identifier = leak_reference(format!("@internal{}{}", scope_id, var_id));
self.scopes[scope_id].insert(&identifier, var_id);
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(init_method),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ObjectGet,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Swap,
location: self.locations.len() - 1,
});
self.add_set_instruction(scope_id, var_id);
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Call,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Pop,
location: self.locations.len() - 1,
});
if scope_id > 0 {
self.add_instruction(Instruction {
instruction_type: InstructionType::GetLocal(var_id),
location: self.locations.len() - 1,
});
} else {
self.add_instruction(Instruction {
instruction_type: InstructionType::GetGlobal(var_id),
location: self.locations.len() - 1,
});
}
self.scopes[scope_id].remove(identifier.as_str());
self.add_instruction(Instruction {
instruction_type: InstructionType::Jmp(1),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::Call,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_conditional(
&mut self,
condition: &'a Expression<'a>,
then_branch: &'a Expression<'a>,
else_branch: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
self.pass_expression(condition)?;
let current_selection = self.toggle_selection;
self.toggle_selection(BufferSelection::DryRun);
self.pass_expression(then_branch)?;
self.toggle_selection(current_selection);
self.add_instruction(Instruction {
instruction_type: InstructionType::JmpIfFalse(self.buffer.len() + 1),
location: self.locations.len() - 1,
});
self.drain_buffer();
self.toggle_selection(BufferSelection::DryRun);
self.pass_expression(else_branch)?;
self.toggle_selection(current_selection);
self.add_instruction(Instruction {
instruction_type: InstructionType::Jmp(self.buffer.len()),
location: self.locations.len() - 1,
});
self.drain_buffer();
Ok(())
}
fn pass_unary(
&mut self,
operand: &'a Expression<'a>,
operator: &'a TokenType<'a>
) -> Result<(), Vec<ProgramError<'a>>> {
if let TokenType::Minus = operator {
let constant = self.constant_from_literal(ConstantValues::Literal(Literal::Integer(0)));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(constant),
location: self.locations.len() - 1,
});
}
self.pass_expression(operand)?;
match operator {
TokenType::Plus => self.add_instruction(Instruction {
instruction_type: InstructionType::Abs,
location: self.locations.len() - 1,
}),
TokenType::Minus => self.add_instruction(Instruction {
instruction_type: InstructionType::Minus,
location: self.locations.len() - 1,
}),
TokenType::Bang => self.add_instruction(Instruction {
instruction_type: InstructionType::Not,
location: self.locations.len() - 1,
}),
t => Err(vec![ProgramError {
message: format!("Invalid unary operator {:?}", t),
location: self.locations.last().unwrap().clone(),
}])?,
}
Ok(())
}
fn pass_anonymous_function(
&mut self,
_arguments: &'a [&'a str],
_body: &'a [Statement<'a>],
_expression: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
Ok(())
}
fn pass_repeated_element_array(&mut self, element: &'a Expression<'a>, length: &'a Expression<'a>) -> Result<(), Vec<ProgramError<'a>>> {
self.pass_expression(element)?;
self.pass_expression(length)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::ArrayAlloc,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::RepeatedArraySet,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_array(&mut self, elements: &'a [Box<Expression<'a>>]) -> Result<(), Vec<ProgramError<'a>>> {
for element in elements.iter().rev() {
self.pass_expression(element)?;
}
let c = self.constant_from_literal(ConstantValues::Literal(Literal::Integer(elements.len() as _)));
self.add_instruction(Instruction {
instruction_type: InstructionType::Constant(c),
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::ArrayAlloc,
location: self.locations.len() - 1,
});
self.add_instruction(Instruction {
instruction_type: InstructionType::MultiArraySet,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_array_element(&mut self, array: &'a Expression<'a>, index: &'a Expression<'a>) -> Result<(), Vec<ProgramError<'a>>> {
self.pass_expression(index)?;
self.pass_expression(array)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::ArrayGet,
location: self.locations.len() - 1,
});
Ok(())
}
fn pass_array_element_set(&mut self, array: &'a Expression<'a>, index: &'a Expression<'a>, value: &'a Expression<'a>) -> Result<(), Vec<ProgramError<'a>>> {
self.pass_expression(value)?;
self.pass_expression(index)?;
self.pass_expression(array)?;
self.add_instruction(Instruction {
instruction_type: InstructionType::ArraySet,
location: self.locations.len() - 1,
});
Ok(())
}
}
|
fn main() {
let s1 = String::from("hello");
// Here we are transfering ownership of s1 into print_string, so after the
// function call we should not be able to refer to s1
println!("{}", *s1)
// This should throw an error
// println!("{}", s1)
}
|
//! # Custom Errors
//!
//! The most basic error type is [`ParserError`][crate::error::ParserError]
//!
//! Optional traits include:
//! - [`AddContext`][crate::error::AddContext]
//! - [`FromExternalError`][crate::error::FromExternalError]
//!
//! # Example
//!
//!```rust
#![doc = include_str!("../../examples/custom_error.rs")]
//!```
|
mod msg;
pub use msg::*;
mod lwsframed;
pub use lwsframed::*;
mod chandshake;
pub use chandshake::*;
mod tcpframed;
pub use tcpframed::*;
|
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn AddDelBackupEntryA ( lpcszfilelist : :: windows_sys::core::PCSTR , lpcszbackupdir : :: windows_sys::core::PCSTR , lpcszbasename : :: windows_sys::core::PCSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn AddDelBackupEntryW ( lpcszfilelist : :: windows_sys::core::PCWSTR , lpcszbackupdir : :: windows_sys::core::PCWSTR , lpcszbasename : :: windows_sys::core::PCWSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn AdvInstallFileA ( hwnd : super::super::Foundation:: HWND , lpszsourcedir : :: windows_sys::core::PCSTR , lpszsourcefile : :: windows_sys::core::PCSTR , lpszdestdir : :: windows_sys::core::PCSTR , lpszdestfile : :: windows_sys::core::PCSTR , dwflags : u32 , dwreserved : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn AdvInstallFileW ( hwnd : super::super::Foundation:: HWND , lpszsourcedir : :: windows_sys::core::PCWSTR , lpszsourcefile : :: windows_sys::core::PCWSTR , lpszdestdir : :: windows_sys::core::PCWSTR , lpszdestfile : :: windows_sys::core::PCWSTR , dwflags : u32 , dwreserved : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "apphelp.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn ApphelpCheckShellObject ( objectclsid : *const :: windows_sys::core::GUID , bshimifnecessary : super::super::Foundation:: BOOL , pullflags : *mut u64 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn CancelDeviceWakeupRequest ( hdevice : super::super::Foundation:: HANDLE ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn CancelTimerQueueTimer ( timerqueue : super::super::Foundation:: HANDLE , timer : super::super::Foundation:: HANDLE ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn CloseINFEngine ( hinf : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "api-ms-win-core-realtime-l1-1-2.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn ConvertAuxiliaryCounterToPerformanceCounter ( ullauxiliarycountervalue : u64 , lpperformancecountervalue : *mut u64 , lpconversionerror : *mut u64 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "api-ms-win-core-realtime-l1-1-2.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn ConvertPerformanceCounterToAuxiliaryCounter ( ullperformancecountervalue : u64 , lpauxiliarycountervalue : *mut u64 , lpconversionerror : *mut u64 ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Security\"`*"] fn CreateWaitableTimerA ( lptimerattributes : *const super::super::Security:: SECURITY_ATTRIBUTES , bmanualreset : super::super::Foundation:: BOOL , lptimername : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: HANDLE );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Security\"`*"] fn CreateWaitableTimerExA ( lptimerattributes : *const super::super::Security:: SECURITY_ATTRIBUTES , lptimername : :: windows_sys::core::PCSTR , dwflags : u32 , dwdesiredaccess : u32 ) -> super::super::Foundation:: HANDLE );
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn DCIBeginAccess ( pdci : *mut DCISURFACEINFO , x : i32 , y : i32 , dx : i32 , dy : i32 ) -> i32 );
#[cfg(feature = "Win32_Graphics_Gdi")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCICloseProvider ( hdc : super::super::Graphics::Gdi:: HDC ) -> ( ) );
#[cfg(feature = "Win32_Graphics_Gdi")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCICreateOffscreen ( hdc : super::super::Graphics::Gdi:: HDC , dwcompression : u32 , dwredmask : u32 , dwgreenmask : u32 , dwbluemask : u32 , dwwidth : u32 , dwheight : u32 , dwdcicaps : u32 , dwbitcount : u32 , lplpsurface : *mut *mut DCIOFFSCREEN ) -> i32 );
#[cfg(feature = "Win32_Graphics_Gdi")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCICreateOverlay ( hdc : super::super::Graphics::Gdi:: HDC , lpoffscreensurf : *mut ::core::ffi::c_void , lplpsurface : *mut *mut DCIOVERLAY ) -> i32 );
#[cfg(feature = "Win32_Graphics_Gdi")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCICreatePrimary ( hdc : super::super::Graphics::Gdi:: HDC , lplpsurface : *mut *mut DCISURFACEINFO ) -> i32 );
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn DCIDestroy ( pdci : *mut DCISURFACEINFO ) -> ( ) );
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn DCIDraw ( pdci : *mut DCIOFFSCREEN ) -> i32 );
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn DCIEndAccess ( pdci : *mut DCISURFACEINFO ) -> ( ) );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCIEnum ( hdc : super::super::Graphics::Gdi:: HDC , lprdst : *mut super::super::Foundation:: RECT , lprsrc : *mut super::super::Foundation:: RECT , lpfncallback : *mut ::core::ffi::c_void , lpcontext : *mut ::core::ffi::c_void ) -> i32 );
#[cfg(feature = "Win32_Graphics_Gdi")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCIOpenProvider ( ) -> super::super::Graphics::Gdi:: HDC );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCISetClipList ( pdci : *mut DCIOFFSCREEN , prd : *mut super::super::Graphics::Gdi:: RGNDATA ) -> i32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn DCISetDestination ( pdci : *mut DCIOFFSCREEN , dst : *mut super::super::Foundation:: RECT , src : *mut super::super::Foundation:: RECT ) -> i32 );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn DCISetSrcDestClip ( pdci : *mut DCIOFFSCREEN , srcrc : *mut super::super::Foundation:: RECT , destrc : *mut super::super::Foundation:: RECT , prd : *mut super::super::Graphics::Gdi:: RGNDATA ) -> i32 );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn DelNodeA ( pszfileordirname : :: windows_sys::core::PCSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn DelNodeRunDLL32W ( hwnd : super::super::Foundation:: HWND , hinstance : super::super::Foundation:: HINSTANCE , pszparms : :: windows_sys::core::PWSTR , nshow : i32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn DelNodeW ( pszfileordirname : :: windows_sys::core::PCWSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn DnsHostnameToComputerNameA ( hostname : :: windows_sys::core::PCSTR , computername : :: windows_sys::core::PSTR , nsize : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn DnsHostnameToComputerNameW ( hostname : :: windows_sys::core::PCWSTR , computername : :: windows_sys::core::PWSTR , nsize : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn DosDateTimeToFileTime ( wfatdate : u16 , wfattime : u16 , lpfiletime : *mut super::super::Foundation:: FILETIME ) -> super::super::Foundation:: BOOL );
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn EnableProcessOptionalXStateFeatures ( features : u64 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn ExecuteCabA ( hwnd : super::super::Foundation:: HWND , pcab : *mut CABINFOA , preserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn ExecuteCabW ( hwnd : super::super::Foundation:: HWND , pcab : *mut CABINFOW , preserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn ExtractFilesA ( pszcabname : :: windows_sys::core::PCSTR , pszexpanddir : :: windows_sys::core::PCSTR , dwflags : u32 , pszfilelist : :: windows_sys::core::PCSTR , lpreserved : *mut ::core::ffi::c_void , dwreserved : u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn ExtractFilesW ( pszcabname : :: windows_sys::core::PCWSTR , pszexpanddir : :: windows_sys::core::PCWSTR , dwflags : u32 , pszfilelist : :: windows_sys::core::PCWSTR , lpreserved : *mut ::core::ffi::c_void , dwreserved : u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn FileSaveMarkNotExistA ( lpfilelist : :: windows_sys::core::PCSTR , lpdir : :: windows_sys::core::PCSTR , lpbasename : :: windows_sys::core::PCSTR ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn FileSaveMarkNotExistW ( lpfilelist : :: windows_sys::core::PCWSTR , lpdir : :: windows_sys::core::PCWSTR , lpbasename : :: windows_sys::core::PCWSTR ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn FileSaveRestoreOnINFA ( hwnd : super::super::Foundation:: HWND , psztitle : :: windows_sys::core::PCSTR , pszinf : :: windows_sys::core::PCSTR , pszsection : :: windows_sys::core::PCSTR , pszbackupdir : :: windows_sys::core::PCSTR , pszbasebackupfile : :: windows_sys::core::PCSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn FileSaveRestoreOnINFW ( hwnd : super::super::Foundation:: HWND , psztitle : :: windows_sys::core::PCWSTR , pszinf : :: windows_sys::core::PCWSTR , pszsection : :: windows_sys::core::PCWSTR , pszbackupdir : :: windows_sys::core::PCWSTR , pszbasebackupfile : :: windows_sys::core::PCWSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn FileSaveRestoreW ( hdlg : super::super::Foundation:: HWND , lpfilelist : :: windows_sys::core::PCWSTR , lpdir : :: windows_sys::core::PCWSTR , lpbasename : :: windows_sys::core::PCWSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn FileTimeToDosDateTime ( lpfiletime : *const super::super::Foundation:: FILETIME , lpfatdate : *mut u16 , lpfattime : *mut u16 ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "api-ms-win-dx-d3dkmt-l1-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GdiEntry13 ( ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetComputerNameA ( lpbuffer : :: windows_sys::core::PSTR , nsize : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetComputerNameW ( lpbuffer : :: windows_sys::core::PWSTR , nsize : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advapi32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetCurrentHwProfileA ( lphwprofileinfo : *mut HW_PROFILE_INFOA ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advapi32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetCurrentHwProfileW ( lphwprofileinfo : *mut HW_PROFILE_INFOW ) -> super::super::Foundation:: BOOL );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn GetDCRegionData ( hdc : super::super::Graphics::Gdi:: HDC , size : u32 , prd : *mut super::super::Graphics::Gdi:: RGNDATA ) -> u32 );
::windows_sys::core::link ! ( "api-ms-win-core-featurestaging-l1-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetFeatureEnabledState ( featureid : u32 , changetime : FEATURE_CHANGE_TIME ) -> FEATURE_ENABLED_STATE );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "api-ms-win-core-featurestaging-l1-1-1.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetFeatureVariant ( featureid : u32 , changetime : FEATURE_CHANGE_TIME , payloadid : *mut u32 , hasnotification : *mut super::super::Foundation:: BOOL ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetFirmwareEnvironmentVariableA ( lpname : :: windows_sys::core::PCSTR , lpguid : :: windows_sys::core::PCSTR , pbuffer : *mut ::core::ffi::c_void , nsize : u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetFirmwareEnvironmentVariableExA ( lpname : :: windows_sys::core::PCSTR , lpguid : :: windows_sys::core::PCSTR , pbuffer : *mut ::core::ffi::c_void , nsize : u32 , pdwattribubutes : *mut u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetFirmwareEnvironmentVariableExW ( lpname : :: windows_sys::core::PCWSTR , lpguid : :: windows_sys::core::PCWSTR , pbuffer : *mut ::core::ffi::c_void , nsize : u32 , pdwattribubutes : *mut u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetFirmwareEnvironmentVariableW ( lpname : :: windows_sys::core::PCWSTR , lpguid : :: windows_sys::core::PCWSTR , pbuffer : *mut ::core::ffi::c_void , nsize : u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileIntA ( lpappname : :: windows_sys::core::PCSTR , lpkeyname : :: windows_sys::core::PCSTR , ndefault : i32 , lpfilename : :: windows_sys::core::PCSTR ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileIntW ( lpappname : :: windows_sys::core::PCWSTR , lpkeyname : :: windows_sys::core::PCWSTR , ndefault : i32 , lpfilename : :: windows_sys::core::PCWSTR ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileSectionA ( lpappname : :: windows_sys::core::PCSTR , lpreturnedstring : :: windows_sys::core::PSTR , nsize : u32 , lpfilename : :: windows_sys::core::PCSTR ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileSectionNamesA ( lpszreturnbuffer : :: windows_sys::core::PSTR , nsize : u32 , lpfilename : :: windows_sys::core::PCSTR ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileSectionNamesW ( lpszreturnbuffer : :: windows_sys::core::PWSTR , nsize : u32 , lpfilename : :: windows_sys::core::PCWSTR ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileSectionW ( lpappname : :: windows_sys::core::PCWSTR , lpreturnedstring : :: windows_sys::core::PWSTR , nsize : u32 , lpfilename : :: windows_sys::core::PCWSTR ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileStringA ( lpappname : :: windows_sys::core::PCSTR , lpkeyname : :: windows_sys::core::PCSTR , lpdefault : :: windows_sys::core::PCSTR , lpreturnedstring : :: windows_sys::core::PSTR , nsize : u32 , lpfilename : :: windows_sys::core::PCSTR ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetPrivateProfileStringW ( lpappname : :: windows_sys::core::PCWSTR , lpkeyname : :: windows_sys::core::PCWSTR , lpdefault : :: windows_sys::core::PCWSTR , lpreturnedstring : :: windows_sys::core::PWSTR , nsize : u32 , lpfilename : :: windows_sys::core::PCWSTR ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetPrivateProfileStructA ( lpszsection : :: windows_sys::core::PCSTR , lpszkey : :: windows_sys::core::PCSTR , lpstruct : *mut ::core::ffi::c_void , usizestruct : u32 , szfile : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetPrivateProfileStructW ( lpszsection : :: windows_sys::core::PCWSTR , lpszkey : :: windows_sys::core::PCWSTR , lpstruct : *mut ::core::ffi::c_void , usizestruct : u32 , szfile : :: windows_sys::core::PCWSTR ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetProfileIntA ( lpappname : :: windows_sys::core::PCSTR , lpkeyname : :: windows_sys::core::PCSTR , ndefault : i32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetProfileIntW ( lpappname : :: windows_sys::core::PCWSTR , lpkeyname : :: windows_sys::core::PCWSTR , ndefault : i32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetProfileSectionA ( lpappname : :: windows_sys::core::PCSTR , lpreturnedstring : :: windows_sys::core::PSTR , nsize : u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetProfileSectionW ( lpappname : :: windows_sys::core::PCWSTR , lpreturnedstring : :: windows_sys::core::PWSTR , nsize : u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetProfileStringA ( lpappname : :: windows_sys::core::PCSTR , lpkeyname : :: windows_sys::core::PCSTR , lpdefault : :: windows_sys::core::PCSTR , lpreturnedstring : :: windows_sys::core::PSTR , nsize : u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetProfileStringW ( lpappname : :: windows_sys::core::PCWSTR , lpkeyname : :: windows_sys::core::PCWSTR , lpdefault : :: windows_sys::core::PCWSTR , lpreturnedstring : :: windows_sys::core::PWSTR , nsize : u32 ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetSystemRegistryQuota ( pdwquotaallowed : *mut u32 , pdwquotaused : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GetThreadEnabledXStateFeatures ( ) -> u64 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advapi32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetUserNameA ( lpbuffer : :: windows_sys::core::PSTR , pcbbuffer : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advapi32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetUserNameW ( lpbuffer : :: windows_sys::core::PWSTR , pcbbuffer : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetVersionFromFileA ( lpszfilename : :: windows_sys::core::PCSTR , pdwmsver : *mut u32 , pdwlsver : *mut u32 , bversion : super::super::Foundation:: BOOL ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetVersionFromFileExA ( lpszfilename : :: windows_sys::core::PCSTR , pdwmsver : *mut u32 , pdwlsver : *mut u32 , bversion : super::super::Foundation:: BOOL ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetVersionFromFileExW ( lpszfilename : :: windows_sys::core::PCWSTR , pdwmsver : *mut u32 , pdwlsver : *mut u32 , bversion : super::super::Foundation:: BOOL ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GetVersionFromFileW ( lpszfilename : :: windows_sys::core::PCWSTR , pdwmsver : *mut u32 , pdwlsver : *mut u32 , bversion : super::super::Foundation:: BOOL ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn GetWindowRegionData ( hwnd : super::super::Foundation:: HWND , size : u32 , prd : *mut super::super::Graphics::Gdi:: RGNDATA ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GlobalCompact ( dwminfree : u32 ) -> usize );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GlobalFix ( hmem : isize ) -> ( ) );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn GlobalUnWire ( hmem : isize ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GlobalUnfix ( hmem : isize ) -> ( ) );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn GlobalWire ( hmem : isize ) -> *mut ::core::ffi::c_void );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IMPGetIMEA ( param0 : super::super::Foundation:: HWND , param1 : *mut IMEPROA ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IMPGetIMEW ( param0 : super::super::Foundation:: HWND , param1 : *mut IMEPROW ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IMPQueryIMEA ( param0 : *mut IMEPROA ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IMPQueryIMEW ( param0 : *mut IMEPROW ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IMPSetIMEA ( param0 : super::super::Foundation:: HWND , param1 : *mut IMEPROA ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IMPSetIMEW ( param0 : super::super::Foundation:: HWND , param1 : *mut IMEPROW ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "api-ms-win-core-apiquery-l2-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IsApiSetImplemented ( contract : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IsBadHugeReadPtr ( lp : *const ::core::ffi::c_void , ucb : usize ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IsBadHugeWritePtr ( lp : *const ::core::ffi::c_void , ucb : usize ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IsNTAdmin ( dwreserved : u32 , lpdwreserved : *mut u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IsNativeVhdBoot ( nativevhdboot : *mut super::super::Foundation:: BOOL ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advapi32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn IsTokenUntrusted ( tokenhandle : super::super::Foundation:: HANDLE ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn LaunchINFSectionExW ( hwnd : super::super::Foundation:: HWND , hinstance : super::super::Foundation:: HINSTANCE , pszparms : :: windows_sys::core::PCWSTR , nshow : i32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn LaunchINFSectionW ( hwndowner : super::super::Foundation:: HWND , hinstance : super::super::Foundation:: HINSTANCE , pszparams : :: windows_sys::core::PWSTR , nshow : i32 ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn LocalCompact ( uminfree : u32 ) -> usize );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn LocalShrink ( hmem : isize , cbnewsize : u32 ) -> usize );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn MulDiv ( nnumber : i32 , nnumerator : i32 , ndenominator : i32 ) -> i32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NeedReboot ( dwrebootcheck : u32 ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn NeedRebootInit ( ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtClose ( handle : super::super::Foundation:: HANDLE ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtDeviceIoControlFile ( filehandle : super::super::Foundation:: HANDLE , event : super::super::Foundation:: HANDLE , apcroutine : PIO_APC_ROUTINE , apccontext : *mut ::core::ffi::c_void , iostatusblock : *mut IO_STATUS_BLOCK , iocontrolcode : u32 , inputbuffer : *mut ::core::ffi::c_void , inputbufferlength : u32 , outputbuffer : *mut ::core::ffi::c_void , outputbufferlength : u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtNotifyChangeMultipleKeys ( masterkeyhandle : super::super::Foundation:: HANDLE , count : u32 , subordinateobjects : *const OBJECT_ATTRIBUTES , event : super::super::Foundation:: HANDLE , apcroutine : PIO_APC_ROUTINE , apccontext : *const ::core::ffi::c_void , iostatusblock : *mut IO_STATUS_BLOCK , completionfilter : u32 , watchtree : super::super::Foundation:: BOOLEAN , buffer : *mut ::core::ffi::c_void , buffersize : u32 , asynchronous : super::super::Foundation:: BOOLEAN ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtOpenFile ( filehandle : *mut super::super::Foundation:: HANDLE , desiredaccess : u32 , objectattributes : *mut OBJECT_ATTRIBUTES , iostatusblock : *mut IO_STATUS_BLOCK , shareaccess : u32 , openoptions : u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtQueryMultipleValueKey ( keyhandle : super::super::Foundation:: HANDLE , valueentries : *mut KEY_VALUE_ENTRY , entrycount : u32 , valuebuffer : *mut ::core::ffi::c_void , bufferlength : *mut u32 , requiredbufferlength : *mut u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtQueryObject ( handle : super::super::Foundation:: HANDLE , objectinformationclass : OBJECT_INFORMATION_CLASS , objectinformation : *mut ::core::ffi::c_void , objectinformationlength : u32 , returnlength : *mut u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtQuerySystemInformation ( systeminformationclass : SYSTEM_INFORMATION_CLASS , systeminformation : *mut ::core::ffi::c_void , systeminformationlength : u32 , returnlength : *mut u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtQuerySystemTime ( systemtime : *mut i64 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtQueryTimerResolution ( maximumtime : *mut u32 , minimumtime : *mut u32 , currenttime : *mut u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtRenameKey ( keyhandle : super::super::Foundation:: HANDLE , newname : *const super::super::Foundation:: UNICODE_STRING ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtSetInformationKey ( keyhandle : super::super::Foundation:: HANDLE , keysetinformationclass : KEY_SET_INFORMATION_CLASS , keysetinformation : *const ::core::ffi::c_void , keysetinformationlength : u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn NtWaitForSingleObject ( handle : super::super::Foundation:: HANDLE , alertable : super::super::Foundation:: BOOLEAN , timeout : *mut i64 ) -> super::super::Foundation:: NTSTATUS );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn OpenINFEngineA ( pszinffilename : :: windows_sys::core::PCSTR , pszinstallsection : :: windows_sys::core::PCSTR , dwflags : u32 , phinf : *mut *mut ::core::ffi::c_void , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn OpenINFEngineW ( pszinffilename : :: windows_sys::core::PCWSTR , pszinstallsection : :: windows_sys::core::PCWSTR , dwflags : u32 , phinf : *mut *mut ::core::ffi::c_void , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn OpenMutexA ( dwdesiredaccess : u32 , binherithandle : super::super::Foundation:: BOOL , lpname : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: HANDLE );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn OpenSemaphoreA ( dwdesiredaccess : u32 , binherithandle : super::super::Foundation:: BOOL , lpname : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: HANDLE );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn OpenWaitableTimerA ( dwdesiredaccess : u32 , binherithandle : super::super::Foundation:: BOOL , lptimername : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: HANDLE );
::windows_sys::core::link ! ( "api-ms-win-core-realtime-l1-1-2.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn QueryAuxiliaryCounterFrequency ( lpauxiliarycounterfrequency : *mut u64 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn QueryIdleProcessorCycleTime ( bufferlength : *mut u32 , processoridlecycletime : *mut u64 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn QueryIdleProcessorCycleTimeEx ( group : u16 , bufferlength : *mut u32 , processoridlecycletime : *mut u64 ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "api-ms-win-core-realtime-l1-1-1.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn QueryInterruptTime ( lpinterrupttime : *mut u64 ) -> ( ) );
::windows_sys::core::link ! ( "api-ms-win-core-realtime-l1-1-1.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn QueryInterruptTimePrecise ( lpinterrupttimeprecise : *mut u64 ) -> ( ) );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn QueryProcessCycleTime ( processhandle : super::super::Foundation:: HANDLE , cycletime : *mut u64 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn QueryThreadCycleTime ( threadhandle : super::super::Foundation:: HANDLE , cycletime : *mut u64 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn QueryUnbiasedInterruptTime ( unbiasedtime : *mut u64 ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "api-ms-win-core-realtime-l1-1-1.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn QueryUnbiasedInterruptTimePrecise ( lpunbiasedinterrupttimeprecise : *mut u64 ) -> ( ) );
::windows_sys::core::link ! ( "api-ms-win-core-backgroundtask-l1-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn RaiseCustomSystemEventTrigger ( customsystemeventtriggerconfig : *const CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RebootCheckOnInstallA ( hwnd : super::super::Foundation:: HWND , pszinf : :: windows_sys::core::PCSTR , pszsec : :: windows_sys::core::PCSTR , dwreserved : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RebootCheckOnInstallW ( hwnd : super::super::Foundation:: HWND , pszinf : :: windows_sys::core::PCWSTR , pszsec : :: windows_sys::core::PCWSTR , dwreserved : u32 ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "api-ms-win-core-featurestaging-l1-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn RecordFeatureError ( featureid : u32 , error : *const FEATURE_ERROR ) -> ( ) );
::windows_sys::core::link ! ( "api-ms-win-core-featurestaging-l1-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn RecordFeatureUsage ( featureid : u32 , kind : u32 , addend : u32 , originname : :: windows_sys::core::PCSTR ) -> ( ) );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RegInstallA ( hmod : super::super::Foundation:: HINSTANCE , pszsection : :: windows_sys::core::PCSTR , psttable : *const STRTABLEA ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RegInstallW ( hmod : super::super::Foundation:: HINSTANCE , pszsection : :: windows_sys::core::PCWSTR , psttable : *const STRTABLEW ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Registry\"`*"] fn RegRestoreAllA ( hwnd : super::super::Foundation:: HWND , psztitlestring : :: windows_sys::core::PCSTR , hkbckupkey : super::Registry:: HKEY ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Registry\"`*"] fn RegRestoreAllW ( hwnd : super::super::Foundation:: HWND , psztitlestring : :: windows_sys::core::PCWSTR , hkbckupkey : super::Registry:: HKEY ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Registry\"`*"] fn RegSaveRestoreA ( hwnd : super::super::Foundation:: HWND , psztitlestring : :: windows_sys::core::PCSTR , hkbckupkey : super::Registry:: HKEY , pcszrootkey : :: windows_sys::core::PCSTR , pcszsubkey : :: windows_sys::core::PCSTR , pcszvaluename : :: windows_sys::core::PCSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Registry\"`*"] fn RegSaveRestoreOnINFA ( hwnd : super::super::Foundation:: HWND , psztitle : :: windows_sys::core::PCSTR , pszinf : :: windows_sys::core::PCSTR , pszsection : :: windows_sys::core::PCSTR , hhklmbackkey : super::Registry:: HKEY , hhkcubackkey : super::Registry:: HKEY , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Registry\"`*"] fn RegSaveRestoreOnINFW ( hwnd : super::super::Foundation:: HWND , psztitle : :: windows_sys::core::PCWSTR , pszinf : :: windows_sys::core::PCWSTR , pszsection : :: windows_sys::core::PCWSTR , hhklmbackkey : super::Registry:: HKEY , hhkcubackkey : super::Registry:: HKEY , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Registry"))]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Registry\"`*"] fn RegSaveRestoreW ( hwnd : super::super::Foundation:: HWND , psztitlestring : :: windows_sys::core::PCWSTR , hkbckupkey : super::Registry:: HKEY , pcszrootkey : :: windows_sys::core::PCWSTR , pcszsubkey : :: windows_sys::core::PCWSTR , pcszvaluename : :: windows_sys::core::PCWSTR , dwflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn ReplacePartitionUnit ( targetpartition : :: windows_sys::core::PCWSTR , sparepartition : :: windows_sys::core::PCWSTR , flags : u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RequestDeviceWakeup ( hdevice : super::super::Foundation:: HANDLE ) -> super::super::Foundation:: BOOL );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"] fn RtlAnsiStringToUnicodeString ( destinationstring : *mut super::super::Foundation:: UNICODE_STRING , sourcestring : *mut super::Kernel:: STRING , allocatedestinationstring : super::super::Foundation:: BOOLEAN ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RtlCharToInteger ( string : *mut i8 , base : u32 , value : *mut u32 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_System_Kernel")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_System_Kernel\"`*"] fn RtlFreeAnsiString ( ansistring : *mut super::Kernel:: STRING ) -> ( ) );
#[cfg(feature = "Win32_System_Kernel")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_System_Kernel\"`*"] fn RtlFreeOemString ( oemstring : *mut super::Kernel:: STRING ) -> ( ) );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RtlFreeUnicodeString ( unicodestring : *mut super::super::Foundation:: UNICODE_STRING ) -> ( ) );
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn RtlGetReturnAddressHijackTarget ( ) -> usize );
#[cfg(feature = "Win32_System_Kernel")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_System_Kernel\"`*"] fn RtlInitAnsiString ( destinationstring : *mut super::Kernel:: STRING , sourcestring : *mut i8 ) -> ( ) );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"] fn RtlInitAnsiStringEx ( destinationstring : *mut super::Kernel:: STRING , sourcestring : *mut i8 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_System_Kernel")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_System_Kernel\"`*"] fn RtlInitString ( destinationstring : *mut super::Kernel:: STRING , sourcestring : *mut i8 ) -> ( ) );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"] fn RtlInitStringEx ( destinationstring : *mut super::Kernel:: STRING , sourcestring : *mut i8 ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RtlInitUnicodeString ( destinationstring : *mut super::super::Foundation:: UNICODE_STRING , sourcestring : :: windows_sys::core::PCWSTR ) -> ( ) );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"] fn RtlIsNameLegalDOS8Dot3 ( name : *mut super::super::Foundation:: UNICODE_STRING , oemname : *mut super::Kernel:: STRING , namecontainsspaces : *mut super::super::Foundation:: BOOLEAN ) -> super::super::Foundation:: BOOLEAN );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RtlLocalTimeToSystemTime ( localtime : *mut i64 , systemtime : *mut i64 ) -> super::super::Foundation:: NTSTATUS );
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn RtlRaiseCustomSystemEventTrigger ( triggerconfig : *const CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RtlTimeToSecondsSince1970 ( time : *mut i64 , elapsedseconds : *mut u32 ) -> super::super::Foundation:: BOOLEAN );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"] fn RtlUnicodeStringToAnsiString ( destinationstring : *mut super::Kernel:: STRING , sourcestring : *mut super::super::Foundation:: UNICODE_STRING , allocatedestinationstring : super::super::Foundation:: BOOLEAN ) -> super::super::Foundation:: NTSTATUS );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"] fn RtlUnicodeStringToOemString ( destinationstring : *mut super::Kernel:: STRING , sourcestring : *mut super::super::Foundation:: UNICODE_STRING , allocatedestinationstring : super::super::Foundation:: BOOLEAN ) -> super::super::Foundation:: NTSTATUS );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RtlUnicodeToMultiByteSize ( bytesinmultibytestring : *mut u32 , unicodestring : :: windows_sys::core::PCWSTR , bytesinunicodestring : u32 ) -> super::super::Foundation:: NTSTATUS );
::windows_sys::core::link ! ( "ntdll.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn RtlUniform ( seed : *mut u32 ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RunSetupCommandA ( hwnd : super::super::Foundation:: HWND , szcmdname : :: windows_sys::core::PCSTR , szinfsection : :: windows_sys::core::PCSTR , szdir : :: windows_sys::core::PCSTR , lpsztitle : :: windows_sys::core::PCSTR , phexe : *mut super::super::Foundation:: HANDLE , dwflags : u32 , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn RunSetupCommandW ( hwnd : super::super::Foundation:: HWND , szcmdname : :: windows_sys::core::PCWSTR , szinfsection : :: windows_sys::core::PCWSTR , szdir : :: windows_sys::core::PCWSTR , lpsztitle : :: windows_sys::core::PCWSTR , phexe : *mut super::super::Foundation:: HANDLE , dwflags : u32 , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SendIMEMessageExA ( param0 : super::super::Foundation:: HWND , param1 : super::super::Foundation:: LPARAM ) -> super::super::Foundation:: LRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SendIMEMessageExW ( param0 : super::super::Foundation:: HWND , param1 : super::super::Foundation:: LPARAM ) -> super::super::Foundation:: LRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetEnvironmentStringsA ( newenvironment : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetFirmwareEnvironmentVariableA ( lpname : :: windows_sys::core::PCSTR , lpguid : :: windows_sys::core::PCSTR , pvalue : *const ::core::ffi::c_void , nsize : u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetFirmwareEnvironmentVariableExA ( lpname : :: windows_sys::core::PCSTR , lpguid : :: windows_sys::core::PCSTR , pvalue : *const ::core::ffi::c_void , nsize : u32 , dwattributes : u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetFirmwareEnvironmentVariableExW ( lpname : :: windows_sys::core::PCWSTR , lpguid : :: windows_sys::core::PCWSTR , pvalue : *const ::core::ffi::c_void , nsize : u32 , dwattributes : u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetFirmwareEnvironmentVariableW ( lpname : :: windows_sys::core::PCWSTR , lpguid : :: windows_sys::core::PCWSTR , pvalue : *const ::core::ffi::c_void , nsize : u32 ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn SetHandleCount ( unumber : u32 ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetMessageWaitingIndicator ( hmsgindicator : super::super::Foundation:: HANDLE , ulmsgcount : u32 ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetPerUserSecValuesA ( pperuser : *mut PERUSERSECTIONA ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SetPerUserSecValuesW ( pperuser : *mut PERUSERSECTIONW ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn SignalObjectAndWait ( hobjecttosignal : super::super::Foundation:: HANDLE , hobjecttowaiton : super::super::Foundation:: HANDLE , dwmilliseconds : u32 , balertable : super::super::Foundation:: BOOL ) -> super::super::Foundation:: WIN32_ERROR );
::windows_sys::core::link ! ( "api-ms-win-core-featurestaging-l1-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn SubscribeFeatureStateChangeNotification ( subscription : *mut FEATURE_STATE_CHANGE_SUBSCRIPTION , callback : PFEATURE_STATE_CHANGE_CALLBACK , context : *const ::core::ffi::c_void ) -> ( ) );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn TranslateInfStringA ( pszinffilename : :: windows_sys::core::PCSTR , pszinstallsection : :: windows_sys::core::PCSTR , psztranslatesection : :: windows_sys::core::PCSTR , psztranslatekey : :: windows_sys::core::PCSTR , pszbuffer : :: windows_sys::core::PSTR , cchbuffer : u32 , pdwrequiredsize : *mut u32 , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn TranslateInfStringExA ( hinf : *mut ::core::ffi::c_void , pszinffilename : :: windows_sys::core::PCSTR , psztranslatesection : :: windows_sys::core::PCSTR , psztranslatekey : :: windows_sys::core::PCSTR , pszbuffer : :: windows_sys::core::PSTR , dwbuffersize : u32 , pdwrequiredsize : *mut u32 , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn TranslateInfStringExW ( hinf : *mut ::core::ffi::c_void , pszinffilename : :: windows_sys::core::PCWSTR , psztranslatesection : :: windows_sys::core::PCWSTR , psztranslatekey : :: windows_sys::core::PCWSTR , pszbuffer : :: windows_sys::core::PWSTR , dwbuffersize : u32 , pdwrequiredsize : *mut u32 , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn TranslateInfStringW ( pszinffilename : :: windows_sys::core::PCWSTR , pszinstallsection : :: windows_sys::core::PCWSTR , psztranslatesection : :: windows_sys::core::PCWSTR , psztranslatekey : :: windows_sys::core::PCWSTR , pszbuffer : :: windows_sys::core::PWSTR , cchbuffer : u32 , pdwrequiredsize : *mut u32 , pvreserved : *mut ::core::ffi::c_void ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "api-ms-win-core-featurestaging-l1-1-0.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn UnsubscribeFeatureStateChangeNotification ( subscription : FEATURE_STATE_CHANGE_SUBSCRIPTION ) -> ( ) );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn UserInstStubWrapperA ( hwnd : super::super::Foundation:: HWND , hinstance : super::super::Foundation:: HINSTANCE , pszparms : :: windows_sys::core::PCSTR , nshow : i32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn UserInstStubWrapperW ( hwnd : super::super::Foundation:: HWND , hinstance : super::super::Foundation:: HINSTANCE , pszparms : :: windows_sys::core::PCWSTR , nshow : i32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn UserUnInstStubWrapperA ( hwnd : super::super::Foundation:: HWND , hinstance : super::super::Foundation:: HINSTANCE , pszparms : :: windows_sys::core::PCSTR , nshow : i32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "advpack.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn UserUnInstStubWrapperW ( hwnd : super::super::Foundation:: HWND , hinstance : super::super::Foundation:: HINSTANCE , pszparms : :: windows_sys::core::PCWSTR , nshow : i32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WINNLSEnableIME ( param0 : super::super::Foundation:: HWND , param1 : super::super::Foundation:: BOOL ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WINNLSGetEnableStatus ( param0 : super::super::Foundation:: HWND ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "user32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WINNLSGetIMEHotkey ( param0 : super::super::Foundation:: HWND ) -> u32 );
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn WinWatchClose ( hww : HWINWATCH ) -> ( ) );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WinWatchDidStatusChange ( hww : HWINWATCH ) -> super::super::Foundation:: BOOL );
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Gdi"))]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_Graphics_Gdi\"`*"] fn WinWatchGetClipList ( hww : HWINWATCH , prc : *mut super::super::Foundation:: RECT , size : u32 , prd : *mut super::super::Graphics::Gdi:: RGNDATA ) -> u32 );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WinWatchNotify ( hww : HWINWATCH , notifycallback : WINWATCHNOTIFYPROC , notifyparam : super::super::Foundation:: LPARAM ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "dciman32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WinWatchOpen ( hwnd : super::super::Foundation:: HWND ) -> HWINWATCH );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "wldp.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WldpGetLockdownPolicy ( hostinformation : *const WLDP_HOST_INFORMATION , lockdownstate : *mut u32 , lockdownflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "wldp.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WldpIsClassInApprovedList ( classid : *const :: windows_sys::core::GUID , hostinformation : *const WLDP_HOST_INFORMATION , isapproved : *mut super::super::Foundation:: BOOL , optionalflags : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "wldp.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WldpIsDynamicCodePolicyEnabled ( isenabled : *mut super::super::Foundation:: BOOL ) -> :: windows_sys::core::HRESULT );
::windows_sys::core::link ! ( "wldp.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn WldpQueryDeviceSecurityInformation ( information : *mut WLDP_DEVICE_SECURITY_INFORMATION , informationlength : u32 , returnlength : *mut u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "wldp.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WldpQueryDynamicCodeTrust ( filehandle : super::super::Foundation:: HANDLE , baseimage : *const ::core::ffi::c_void , imagesize : u32 ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "wldp.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WldpSetDynamicCodeTrust ( filehandle : super::super::Foundation:: HANDLE ) -> :: windows_sys::core::HRESULT );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WritePrivateProfileSectionA ( lpappname : :: windows_sys::core::PCSTR , lpstring : :: windows_sys::core::PCSTR , lpfilename : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WritePrivateProfileSectionW ( lpappname : :: windows_sys::core::PCWSTR , lpstring : :: windows_sys::core::PCWSTR , lpfilename : :: windows_sys::core::PCWSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WritePrivateProfileStringA ( lpappname : :: windows_sys::core::PCSTR , lpkeyname : :: windows_sys::core::PCSTR , lpstring : :: windows_sys::core::PCSTR , lpfilename : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WritePrivateProfileStringW ( lpappname : :: windows_sys::core::PCWSTR , lpkeyname : :: windows_sys::core::PCWSTR , lpstring : :: windows_sys::core::PCWSTR , lpfilename : :: windows_sys::core::PCWSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WritePrivateProfileStructA ( lpszsection : :: windows_sys::core::PCSTR , lpszkey : :: windows_sys::core::PCSTR , lpstruct : *const ::core::ffi::c_void , usizestruct : u32 , szfile : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WritePrivateProfileStructW ( lpszsection : :: windows_sys::core::PCWSTR , lpszkey : :: windows_sys::core::PCWSTR , lpstruct : *const ::core::ffi::c_void , usizestruct : u32 , szfile : :: windows_sys::core::PCWSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WriteProfileSectionA ( lpappname : :: windows_sys::core::PCSTR , lpstring : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WriteProfileSectionW ( lpappname : :: windows_sys::core::PCWSTR , lpstring : :: windows_sys::core::PCWSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WriteProfileStringA ( lpappname : :: windows_sys::core::PCSTR , lpkeyname : :: windows_sys::core::PCSTR , lpstring : :: windows_sys::core::PCSTR ) -> super::super::Foundation:: BOOL );
#[cfg(feature = "Win32_Foundation")]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"] fn WriteProfileStringW ( lpappname : :: windows_sys::core::PCWSTR , lpkeyname : :: windows_sys::core::PCWSTR , lpstring : :: windows_sys::core::PCWSTR ) -> super::super::Foundation:: BOOL );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _hread ( hfile : i32 , lpbuffer : *mut ::core::ffi::c_void , lbytes : i32 ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _hwrite ( hfile : i32 , lpbuffer : :: windows_sys::core::PCSTR , lbytes : i32 ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _lclose ( hfile : i32 ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _lcreat ( lppathname : :: windows_sys::core::PCSTR , iattribute : i32 ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _llseek ( hfile : i32 , loffset : i32 , iorigin : i32 ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _lopen ( lppathname : :: windows_sys::core::PCSTR , ireadwrite : i32 ) -> i32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _lread ( hfile : i32 , lpbuffer : *mut ::core::ffi::c_void , ubytes : u32 ) -> u32 );
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn _lwrite ( hfile : i32 , lpbuffer : :: windows_sys::core::PCSTR , ubytes : u32 ) -> u32 );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_lstrcmpW ( string1 : *const u16 , string2 : *const u16 ) -> i32 );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_lstrcmpiW ( string1 : *const u16 , string2 : *const u16 ) -> i32 );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_lstrlenW ( string : *const u16 ) -> i32 );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_wcschr ( string : *const u16 , character : u16 ) -> *mut u16 );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_wcscpy ( destination : *mut u16 , source : *const u16 ) -> *mut u16 );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_wcsicmp ( string1 : *const u16 , string2 : *const u16 ) -> i32 );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_wcslen ( string : *const u16 ) -> usize );
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
::windows_sys::core::link ! ( "kernel32.dll""system" #[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"] fn uaw_wcsrchr ( string : *const u16 , character : u16 ) -> *mut u16 );
pub type ICameraUIControl = *mut ::core::ffi::c_void;
pub type ICameraUIControlEventCallback = *mut ::core::ffi::c_void;
pub type IClipServiceNotificationHelper = *mut ::core::ffi::c_void;
pub type IContainerActivationHelper = *mut ::core::ffi::c_void;
pub type IDefaultBrowserSyncSettings = *mut ::core::ffi::c_void;
pub type IDeleteBrowsingHistory = *mut ::core::ffi::c_void;
pub type IEditionUpgradeBroker = *mut ::core::ffi::c_void;
pub type IEditionUpgradeHelper = *mut ::core::ffi::c_void;
pub type IWindowsLockModeHelper = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AADBE_ADD_ENTRY: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AADBE_DEL_ENTRY: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_APPLICATION_NAME_VALID: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_HMODULE_VALID: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_LANGID_VALID: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_PROCESSOR_ARCHITECTURE_VALID: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_RESOURCE_NAME_VALID: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_SET_PROCESS_DEFAULT: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTCTX_FLAG_SOURCE_IS_ASSEMBLYREF: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ACTIVATION_CONTEXT_BASIC_INFORMATION_DEFINED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AC_LINE_BACKUP_POWER: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AC_LINE_OFFLINE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AC_LINE_ONLINE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AC_LINE_UNKNOWN: u32 = 255u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ADN_DEL_IF_EMPTY: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ADN_DEL_UNC_PATHS: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ADN_DONT_DEL_DIR: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ADN_DONT_DEL_SUBDIRS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_BACKNEW: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_EXTRAINCREFCNT: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_NODELETENEW: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_NOMESSAGES: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_NOPROGRESS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_RESTORE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_UPDREFCNT: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AFSR_USEREFCNT: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_FORCE_FILE_IN_USE: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_NOLANGUAGECHECK: u32 = 268435456u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_NOOVERWRITE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_NOSKIP: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_NOVERSIONCHECK: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_NO_VERSION_DIALOG: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_QUIET: u32 = 536870912u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_REPLACEONLY: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AIF_WARNIFSKIP: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_BKINSTALL: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_CHECKBKDATA: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_DELAYREGISTEROCX: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_NGCONV: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_QUIET: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_ROLLBACK: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_ROLLBKDOALL: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ALINF_UPDHLPDLLS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ARSR_NOMESSAGES: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ARSR_REGSECTION: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ARSR_REMOVREGBKDATA: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ARSR_RESTORE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ATOM_FLAG_GLOBAL: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AT_ARP: u32 = 640u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AT_NULL: u32 = 642u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BACKUP_GHOSTED_FILE_EXTENTS: u32 = 11u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BACKUP_INVALID: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE: u32 = 65536u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BASE_SEARCH_PATH_PERMANENT: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_FLAG_CHARGING: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_FLAG_CRITICAL: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_FLAG_HIGH: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_FLAG_LOW: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_FLAG_NO_BATTERY: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_FLAG_UNKNOWN: u32 = 255u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_LIFE_UNKNOWN: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BATTERY_PERCENTAGE_UNKNOWN: u32 = 255u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_075: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_110: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_115200: u32 = 131072u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_1200: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_128K: u32 = 65536u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_134_5: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_14400: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_150: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_1800: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_19200: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_2400: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_300: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_38400: u32 = 16384u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_4800: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_56K: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_57600: u32 = 262144u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_600: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_7200: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_9600: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const BAUD_USER: u32 = 268435456u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CATID_DeleteBrowsingHistory: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x31caf6e4_d6aa_4090_a050_a5ac8972e9ef);
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_110: u32 = 110u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_115200: u32 = 115200u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_1200: u32 = 1200u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_128000: u32 = 128000u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_14400: u32 = 14400u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_19200: u32 = 19200u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_2400: u32 = 2400u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_256000: u32 = 256000u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_300: u32 = 300u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_38400: u32 = 38400u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_4800: u32 = 4800u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_56000: u32 = 56000u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_57600: u32 = 57600u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_600: u32 = 600u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CBR_9600: u32 = 9600u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CE_DNS: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CE_IOE: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CE_MODE: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CE_OOP: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CE_PTO: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CE_TXFULL: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CL_NL_IP: u32 = 771u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CL_NL_IPX: u32 = 769u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CL_TL_NBF: u32 = 1025u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CL_TL_UDP: u32 = 1027u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_DEBUGMODE_ENABLED: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_ENABLED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_FLIGHTING_ENABLED: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_FLIGHT_BUILD: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_HVCI_IUM_ENABLED: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_HVCI_KMCI_AUDITMODE_ENABLED: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_HVCI_KMCI_ENABLED: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_HVCI_KMCI_STRICTMODE_ENABLED: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_PREPRODUCTION_BUILD: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_TESTSIGN: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_TEST_BUILD: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_UMCI_AUDITMODE_ENABLED: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_UMCI_ENABLED: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CODEINTEGRITY_OPTION_UMCI_EXCLUSIONPATHS_ENABLED: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COMMPROP_INITIALIZED: u32 = 3879531822u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CONTEXT_SIZE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPYFILE2_IO_CYCLE_SIZE_MAX: u32 = 1073741824u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPYFILE2_IO_CYCLE_SIZE_MIN: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPYFILE2_IO_RATE_MIN: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPYFILE2_MESSAGE_COPY_OFFLOAD: i32 = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_ALLOW_DECRYPTED_DESTINATION: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_COPY_SYMLINK: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_DIRECTORY: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_DISABLE_PRE_ALLOCATION: u32 = 67108864u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_DONT_REQUEST_DEST_WRITE_DAC: u32 = 33554432u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_ENABLE_LOW_FREE_SPACE_MODE: u32 = 134217728u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_FAIL_IF_EXISTS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_IGNORE_EDP_BLOCK: u32 = 4194304u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_IGNORE_SOURCE_ENCRYPTION: u32 = 8388608u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_NO_BUFFERING: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_NO_OFFLOAD: u32 = 262144u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_OPEN_AND_COPY_REPARSE_POINT: u32 = 2097152u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_OPEN_SOURCE_FOR_WRITE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_REQUEST_COMPRESSED_TRAFFIC: u32 = 268435456u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_REQUEST_SECURITY_PRIVILEGES: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_RESTARTABLE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_RESUME_FROM_PAUSE: u32 = 16384u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const COPY_FILE_SKIP_ALTERNATE_STREAMS: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CO_TL_NBF: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CO_TL_SPP: u32 = 1030u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CO_TL_SPX: u32 = 1026u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CO_TL_TCP: u32 = 1028u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CP_DIRECT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CP_HWND: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CP_LEVEL: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CP_OPEN: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CREATE_FOR_DIR: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CREATE_FOR_IMPORT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CRITICAL_SECTION_NO_DEBUG_INFO: u32 = 16777216u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CameraUIControl: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x16d5a2be_b1c5_47b3_8eae_ccbcf452c7e8);
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCICREATEOFFSCREENSURFACE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCICREATEOVERLAYSURFACE: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCICREATEPRIMARYSURFACE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCIENUMSURFACE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCIESCAPE: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_1632_ACCESS: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ASYNC: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_CANOVERLAY: u32 = 65536u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_CAN_STRETCHX: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_CAN_STRETCHXN: u32 = 16384u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_CAN_STRETCHY: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_CAN_STRETCHYN: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_CHROMAKEY: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_DWORDALIGN: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_DWORDSIZE: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_CURRENTLYNOTAVAIL: i32 = -5i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_HEIGHTALIGN: i32 = -21i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_INVALIDCLIPLIST: i32 = -15i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_INVALIDPOSITION: i32 = -13i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_INVALIDRECT: i32 = -6i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_INVALIDSTRETCH: i32 = -14i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_OUTOFMEMORY: i32 = -12i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_SURFACEISOBSCURED: i32 = -16i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_TOOBIGHEIGHT: i32 = -9i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_TOOBIGSIZE: i32 = -11i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_TOOBIGWIDTH: i32 = -10i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_UNSUPPORTEDFORMAT: i32 = -7i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_UNSUPPORTEDMASK: i32 = -8i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_WIDTHALIGN: i32 = -20i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_XALIGN: i32 = -17i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_XYALIGN: i32 = -19i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_ERR_YALIGN: i32 = -18i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_FAIL_GENERIC: i32 = -1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_FAIL_INVALIDSURFACE: i32 = -3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_FAIL_UNSUPPORTED: i32 = -4i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_FAIL_UNSUPPORTEDVERSION: i32 = -2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_OFFSCREEN: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_OK: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_OVERLAY: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_PRIMARY: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_STATUS_CHROMAKEYCHANGED: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_STATUS_FORMATCHANGED: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_STATUS_POINTERCHANGED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_STATUS_STRIDECHANGED: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_STATUS_SURFACEINFOCHANGED: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_STATUS_WASSTILLDRAWING: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_SURFACE_TYPE: u32 = 15u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_VERSION: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_VISIBLE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DCI_WRITEONLY: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DEACTIVATE_ACTCTX_FLAG_FORCE_EARLY_DEACTIVATION: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELAYLOAD_GPA_FAILURE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELETE_BROWSING_HISTORY_COOKIES: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELETE_BROWSING_HISTORY_DOWNLOADHISTORY: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELETE_BROWSING_HISTORY_FORMDATA: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELETE_BROWSING_HISTORY_HISTORY: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELETE_BROWSING_HISTORY_PASSWORDS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELETE_BROWSING_HISTORY_PRESERVEFAVORITES: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DELETE_BROWSING_HISTORY_TIF: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DOCKINFO_DOCKED: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DOCKINFO_UNDOCKED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DOCKINFO_USER_SUPPLIED: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DRIVE_CDROM: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DRIVE_FIXED: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DRIVE_NO_ROOT_DIR: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DRIVE_RAMDISK: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DRIVE_REMOTE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DRIVE_REMOVABLE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DRIVE_UNKNOWN: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DTR_CONTROL_DISABLE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DTR_CONTROL_ENABLE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DTR_CONTROL_HANDSHAKE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DefaultBrowserSyncSettings: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x3ac83423_3112_4aa6_9b5b_1feb23d0c5f9);
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const EFSRPC_SECURE_ONLY: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const EFS_DROP_ALTERNATE_STREAMS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const EFS_USE_RECOVERY_KEYS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ENTITY_LIST_ID: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ENTITY_TYPE_ID: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ER_ICMP: u32 = 896u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const EVENTLOG_FULL_INFO: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const EditionUpgradeBroker: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xc4270827_4f39_45df_9288_12ff6b85a921);
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const EditionUpgradeHelper: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x01776df3_b9af_4e50_9b1c_56e93116d704);
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FAIL_FAST_GENERATE_EXCEPTION_ADDRESS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FAIL_FAST_NO_HARD_ERROR_DLG: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FIBER_FLAG_FLOAT_SWITCH: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_COMPLETE_IF_OPLOCKED: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_CREATED: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_CREATE_TREE_CONNECTION: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DELETE_ON_CLOSE: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DIRECTORY_FILE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DIR_DISALLOWED: u32 = 9u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DISPOSITION_FLAG_DELETE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DISPOSITION_FLAG_DO_NOT_DELETE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DISPOSITION_FLAG_FORCE_IMAGE_SECTION_CHECK: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DISPOSITION_FLAG_ON_CLOSE: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DISPOSITION_FLAG_POSIX_SEMANTICS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_DOES_NOT_EXIST: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_ENCRYPTABLE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_EXISTS: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_FLAG_OPEN_REQUIRING_OPLOCK: u32 = 262144u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_IS_ENCRYPTED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_MAXIMUM_DISPOSITION: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_NON_DIRECTORY_FILE: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_NO_COMPRESSION: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_NO_EA_KNOWLEDGE: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_NO_INTERMEDIATE_BUFFERING: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPENED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPEN_BY_FILE_ID: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPEN_FOR_BACKUP_INTENT: u32 = 16384u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPEN_FOR_FREE_SPACE_QUERY: u32 = 8388608u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPEN_NO_RECALL: u32 = 4194304u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPEN_REMOTE_INSTANCE: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPEN_REPARSE_POINT: u32 = 2097152u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OPEN_REQUIRING_OPLOCK: u32 = 65536u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_OVERWRITTEN: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_RANDOM_ACCESS: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_READ_ONLY: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_RENAME_FLAG_POSIX_SEMANTICS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_RENAME_FLAG_REPLACE_IF_EXISTS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_RENAME_FLAG_SUPPRESS_PIN_STATE_INHERITANCE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_RESERVE_OPFILTER: u32 = 1048576u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_ROOT_DIR: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SEQUENTIAL_ONLY: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SKIP_SET_EVENT_ON_HANDLE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SUPERSEDED: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SYNCHRONOUS_IO_ALERT: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SYSTEM_ATTR: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SYSTEM_DIR: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_SYSTEM_NOT_SUPPORT: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_UNKNOWN: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_USER_DISALLOWED: u32 = 7u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_VALID_MAILSLOT_OPTION_FLAGS: u32 = 50u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_VALID_OPTION_FLAGS: u32 = 16777215u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_VALID_PIPE_OPTION_FLAGS: u32 = 50u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_VALID_SET_FLAGS: u32 = 54u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FILE_WRITE_THROUGH: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FIND_ACTCTX_SECTION_KEY_RETURN_ASSEMBLY_METADATA: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FIND_ACTCTX_SECTION_KEY_RETURN_FLAGS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FORMAT_MESSAGE_MAX_WIDTH_MASK: u32 = 255u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FS_CASE_IS_PRESERVED: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FS_CASE_SENSITIVE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FS_FILE_COMPRESSION: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FS_FILE_ENCRYPTION: u32 = 131072u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FS_PERSISTENT_ACLS: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FS_UNICODE_STORED_ON_DISK: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FS_VOL_IS_COMPRESSED: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_A_A: ::windows_sys::core::PCSTR = ::windows_sys::s!("GetSystemWow64DirectoryA");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_A_T: ::windows_sys::core::PCWSTR = ::windows_sys::w!("GetSystemWow64DirectoryA");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_A_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("GetSystemWow64DirectoryA");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_T_A: ::windows_sys::core::PCWSTR = ::windows_sys::w!("GetSystemWow64DirectoryW");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_T_T: ::windows_sys::core::PCWSTR = ::windows_sys::w!("GetSystemWow64DirectoryW");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_T_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("GetSystemWow64DirectoryW");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_W_A: ::windows_sys::core::PCSTR = ::windows_sys::s!("GetSystemWow64DirectoryW");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_W_T: ::windows_sys::core::PCWSTR = ::windows_sys::w!("GetSystemWow64DirectoryW");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GET_SYSTEM_WOW64_DIRECTORY_NAME_W_W: ::windows_sys::core::PCWSTR = ::windows_sys::w!("GetSystemWow64DirectoryW");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_DDESHARE: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_DISCARDABLE: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_DISCARDED: u32 = 16384u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_INVALID_HANDLE: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_LOCKCOUNT: u32 = 255u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_LOWER: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_MODIFY: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_NOCOMPACT: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_NODISCARD: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_NOTIFY: u32 = 16384u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_NOT_BANKED: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_SHARE: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GMEM_VALID_FLAGS: u32 = 32626u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const HANJA_WINDOW: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const HINSTANCE_ERROR: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const HW_PROFILE_GUIDLEN: u32 = 39u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_BACKNEW: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_EXTRAINCREFCNT: u32 = 2048u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_FRDOALL: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_NODELETENEW: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_NOENUMKEY: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_NOMESSAGES: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_NOPROGRESS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_NO_CRC_MAPPING: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_REGSECTION: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_REMOVREGBKDATA: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_RESTORE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_UPDREFCNT: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE4_USEREFCNT: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_BADID: i32 = -1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_BAUDRATE: i32 = -12i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_BYTESIZE: i32 = -11i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_DEFAULT: i32 = -5i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_HARDWARE: i32 = -10i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_MEMORY: i32 = -4i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_NOPEN: i32 = -3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IE_OPEN: i32 = -2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IF_GENERIC: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IF_MIB: u32 = 514u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IGNORE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IMEA_INIT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IMEA_NEXT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IMEA_PREV: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_BANJAtoJUNJA: u32 = 19u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_ENABLE_CONVERT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_ENTERWORDREGISTERMODE: u32 = 24u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_GETCONVERSIONMODE: u32 = 17u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_GETIMECAPS: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_GETOPEN: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_GETVERSION: u32 = 7u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_JOHABtoKS: u32 = 21u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_JUNJAtoBANJA: u32 = 20u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_KStoJOHAB: u32 = 22u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MAXPROCESS: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_ALPHANUMERIC: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_CODEINPUT: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_DBCSCHAR: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_HANJACONVERT: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_HIRAGANA: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_KATAKANA: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_NOCODEINPUT: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_NOROMAN: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_ROMAN: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MODE_SBCSCHAR: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_MOVEIMEWINDOW: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_REQUEST_CONVERT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_DISKERROR: u32 = 14u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_ERROR: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_ILLEGAL: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_INVALID: u32 = 17u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_NEST: u32 = 18u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_NOIME: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_NOROOM: u32 = 10u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_NOTFOUND: u32 = 7u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_SYSTEMMODAL: u32 = 19u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_RS_TOOLONG: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_SENDVKEY: u32 = 19u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_SETCONVERSIONFONTEX: u32 = 25u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_SETCONVERSIONMODE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_SETCONVERSIONWINDOW: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_SETOPEN: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IME_SET_MODE: u32 = 18u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INFINITE: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INFO_CLASS_GENERIC: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INFO_CLASS_IMPLEMENTATION: u32 = 768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INFO_CLASS_PROTOCOL: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INFO_TYPE_ADDRESS_OBJECT: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INFO_TYPE_CONNECTION: u32 = 768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INFO_TYPE_PROVIDER: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INTERIM_WINDOW: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const INVALID_ENTITY_INSTANCE: i32 = -1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IOCTL_TDI_TL_IO_CONTROL_ENDPOINT: u32 = 2162744u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_CHANGECONVERT: u32 = 289u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_CLOSECONVERT: u32 = 290u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_DBCSCHAR: u32 = 352u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_FULLCONVERT: u32 = 291u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_IMESELECT: u32 = 304u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_MODEINFO: u32 = 400u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_OPENCONVERT: u32 = 288u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_STRING: u32 = 320u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_STRINGEND: u32 = 257u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_STRINGEX: u32 = 384u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_STRINGSTART: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IR_UNDETERMINE: u32 = 368u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const LIS_NOGRPCONV: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const LIS_QUIET: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const LOGON32_PROVIDER_VIRTUAL: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const LOGON32_PROVIDER_WINNT35: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const LOGON_ZERO_PASSWORD_BUFFER: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const LPTx: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MAXINTATOM: u32 = 49152u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MAX_COMPUTERNAME_LENGTH: u32 = 15u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MAX_TDI_ENTITIES: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MCW_DEFAULT: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MCW_HIDDEN: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MCW_RECT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MCW_SCREEN: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MCW_VERTICAL: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MCW_WINDOW: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MICROSOFT_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MODE_WINDOW: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const OFS_MAXPATHNAME: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const OPERATION_API_VERSION: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const OVERWRITE_HIDDEN: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_16BITMODE: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_DTRDSR: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_INTTIMEOUTS: u32 = 128u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_PARITY_CHECK: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_RLSD: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_RTSCTS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_SETXCHAR: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_SPECIALCHARS: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_TOTALTIMEOUTS: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PCF_XONXOFF: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_ALL_APPLICATION_PACKAGES_OPT_OUT: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_CHILD_PROCESS_OVERRIDE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_CHILD_PROCESS_RESTRICTED: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_CHILD_PROCESS_RESTRICTED_UNLESS_SECURE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_DISABLE_PROCESS_TREE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_ENABLE_PROCESS_TREE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_OVERRIDE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROC_THREAD_ATTRIBUTE_ADDITIVE: u32 = 262144u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROC_THREAD_ATTRIBUTE_INPUT: u32 = 131072u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROC_THREAD_ATTRIBUTE_NUMBER: u32 = 65535u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROC_THREAD_ATTRIBUTE_THREAD: u32 = 65536u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROGRESS_CANCEL: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROGRESS_CONTINUE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROGRESS_QUIET: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROGRESS_STOP: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PROTECTION_LEVEL_SAME: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_FAX: u32 = 33u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_LAT: u32 = 257u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_MODEM: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_NETWORK_BRIDGE: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_PARALLELPORT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_RS232: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_RS422: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_RS423: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_RS449: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_SCANNER: u32 = 34u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_TCPIP_TELNET: u32 = 258u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_UNSPECIFIED: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const PST_X25: u32 = 259u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const QUERY_ACTCTX_FLAG_ACTCTX_IS_ADDRESS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const QUERY_ACTCTX_FLAG_ACTCTX_IS_HMODULE: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const QUERY_ACTCTX_FLAG_NO_ADDREF: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const QUERY_ACTCTX_FLAG_USE_ACTIVE_ACTCTX: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RECOVERY_DEFAULT_PING_INTERVAL: u32 = 5000u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const REG_RESTORE_LOG_KEY: ::windows_sys::core::PCWSTR = ::windows_sys::w!("RegRestoreLogFile");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const REG_SAVE_LOG_KEY: ::windows_sys::core::PCWSTR = ::windows_sys::w!("RegSaveLogFile");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const REMOTE_PROTOCOL_INFO_FLAG_LOOPBACK: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const REMOTE_PROTOCOL_INFO_FLAG_OFFLINE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const REMOTE_PROTOCOL_INFO_FLAG_PERSISTENT_HANDLE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RESETDEV: u32 = 7u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RESTART_MAX_CMD_LINE: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_FLAG_SMB2_SHARECAP_CLUSTER: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_FLAG_SMB2_SHARECAP_CONTINUOUS_AVAILABILITY: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_FLAG_SMB2_SHARECAP_DFS: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_FLAG_SMB2_SHARECAP_SCALEOUT: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_FLAG_SMB2_SHARECAP_TIMEWARP: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_SMB2_FLAG_SERVERCAP_DFS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_SMB2_FLAG_SERVERCAP_DIRECTORY_LEASING: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_SMB2_FLAG_SERVERCAP_LARGEMTU: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_SMB2_FLAG_SERVERCAP_LEASING: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_SMB2_FLAG_SERVERCAP_MULTICHANNEL: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RPI_SMB2_FLAG_SERVERCAP_PERSISTENT_HANDLES: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RSC_FLAG_DELAYREGISTEROCX: u32 = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RSC_FLAG_INF: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RSC_FLAG_NGCONV: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RSC_FLAG_QUIET: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RSC_FLAG_SETUPAPI: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RSC_FLAG_SKIPDISKSPACECHECK: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RSC_FLAG_UPDHLPDLLS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RTS_CONTROL_DISABLE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RTS_CONTROL_ENABLE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RTS_CONTROL_HANDSHAKE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RTS_CONTROL_TOGGLE: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RUNCMDS_DELAYPOSTCMD: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RUNCMDS_NOWAIT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const RUNCMDS_QUIET: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_32BIT_BINARY: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_64BIT_BINARY: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_DOS_BINARY: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_OS216_BINARY: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_PIF_BINARY: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_POSIX_BINARY: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_THIS_PLATFORM_BINARY: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SCS_WOW_BINARY: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SHUTDOWN_NORETRY: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_BAUD: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_DATABITS: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_HANDSHAKING: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_PARITY: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_PARITY_CHECK: u32 = 32u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_RLSD: u32 = 64u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_SERIALCOMM: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SP_STOPBITS: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STARTF_HOLOGRAPHIC: u32 = 262144u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STORAGE_INFO_FLAGS_ALIGNED_DEVICE: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STORAGE_INFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STORAGE_INFO_OFFSET_UNKNOWN: u32 = 4294967295u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STREAM_CONTAINS_GHOSTED_FILE_EXTENTS: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STREAM_CONTAINS_PROPERTIES: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STREAM_CONTAINS_SECURITY: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STREAM_MODIFIED_WHEN_READ: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STREAM_NORMAL_ATTRIBUTE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const STREAM_SPARSE_ATTRIBUTE: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SYSTEM_STATUS_FLAG_POWER_SAVING_ON: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_ALLTHRESHOLD: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_LEGATO: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_NORMAL: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_PERIOD1024: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_PERIOD2048: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_PERIOD512: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_PERIODVOICE: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_QUEUEEMPTY: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERBDNT: i32 = -5i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDCC: i32 = -7i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDDR: i32 = -14i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDFQ: i32 = -13i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDLN: i32 = -6i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDMD: i32 = -10i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDPT: i32 = -12i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDSH: i32 = -11i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDSR: i32 = -15i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDST: i32 = -16i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDTP: i32 = -8i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDVL: i32 = -9i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERDVNA: i32 = -1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERMACT: i32 = -3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SEROFM: i32 = -2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_SERQFUL: i32 = -4i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_STACCATO: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_THRESHOLD: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_WHITE1024: u32 = 5u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_WHITE2048: u32 = 6u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_WHITE512: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const S_WHITEVOICE: u32 = 7u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const TC_GP_TRAP: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const TC_HARDERR: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const TC_NORMAL: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const TC_SIGNAL: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const THREAD_PRIORITY_ERROR_RETURN: u32 = 2147483647u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const UMS_VERSION: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const VOLUME_NAME_DOS: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const VOLUME_NAME_GUID: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const VOLUME_NAME_NONE: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const VOLUME_NAME_NT: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WINWATCHNOTIFY_CHANGED: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WINWATCHNOTIFY_CHANGING: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WINWATCHNOTIFY_DESTROY: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WINWATCHNOTIFY_START: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WINWATCHNOTIFY_STOP: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_DLL: ::windows_sys::core::PCWSTR = ::windows_sys::w!("WLDP.DLL");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_FLAGS_SKIPSIGNATUREVALIDATION: u32 = 256u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_GETLOCKDOWNPOLICY_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpGetLockdownPolicy");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_INFORMATION_REVISION: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_ISAPPAPPROVEDBYPOLICY_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpIsAppApprovedByPolicy");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_ISCLASSINAPPROVEDLIST_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpIsClassInApprovedList");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_ISDYNAMICCODEPOLICYENABLED_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpIsDynamicCodePolicyEnabled");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_ISPRODUCTIONCONFIGURATION_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpIsProductionConfiguration");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_ISWCOSPRODUCTIONCONFIGURATION_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpIsWcosProductionConfiguration");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_AUDIT_FLAG: u32 = 8u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_CONFIG_CI_AUDIT_FLAG: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_CONFIG_CI_FLAG: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_DEFINED_FLAG: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_EXCLUSION_FLAG: u32 = 16u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_OFF: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_UMCIENFORCE_FLAG: u32 = 4u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_LOCKDOWN_UNDEFINED: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_QUERYDANAMICCODETRUST_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpQueryDynamicCodeTrust");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_QUERYDEVICESECURITYINFORMATION_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpQueryDeviceSecurityInformation");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_QUERYDYNAMICCODETRUST_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpQueryDynamicCodeTrust");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_QUERYPOLICYSETTINGENABLED2_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpQueryPolicySettingEnabled2");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_QUERYPOLICYSETTINGENABLED_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpQueryPolicySettingEnabled");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_QUERYWINDOWSLOCKDOWNMODE_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpQueryWindowsLockdownMode");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_QUERYWINDOWSLOCKDOWNRESTRICTION_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpQueryWindowsLockdownRestriction");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_RESETPRODUCTIONCONFIGURATION_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpResetProductionConfiguration");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_RESETWCOSPRODUCTIONCONFIGURATION_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpResetWcosProductionConfiguration");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_SETDYNAMICCODETRUST_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpSetDynamicCodeTrust");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_SETWINDOWSLOCKDOWNRESTRICTION_FN: ::windows_sys::core::PCSTR = ::windows_sys::s!("WldpSetWindowsLockdownRestriction");
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WM_CONVERTREQUEST: u32 = 266u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WM_CONVERTRESULT: u32 = 267u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WM_IMEKEYDOWN: u32 = 656u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WM_IMEKEYUP: u32 = 657u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WM_IME_REPORT: u32 = 640u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WM_INTERIM: u32 = 268u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WM_WNT_CONVERTREQUESTEX: u32 = 265u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[repr(transparent)]
pub struct CameraUIControlCaptureMode(pub i32);
impl CameraUIControlCaptureMode {
pub const PhotoOrVideo: Self = Self(0i32);
pub const Photo: Self = Self(1i32);
pub const Video: Self = Self(2i32);
}
impl ::core::marker::Copy for CameraUIControlCaptureMode {}
impl ::core::clone::Clone for CameraUIControlCaptureMode {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[repr(transparent)]
pub struct CameraUIControlLinearSelectionMode(pub i32);
impl CameraUIControlLinearSelectionMode {
pub const Single: Self = Self(0i32);
pub const Multiple: Self = Self(1i32);
}
impl ::core::marker::Copy for CameraUIControlLinearSelectionMode {}
impl ::core::clone::Clone for CameraUIControlLinearSelectionMode {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[repr(transparent)]
pub struct CameraUIControlMode(pub i32);
impl CameraUIControlMode {
pub const Browse: Self = Self(0i32);
pub const Linear: Self = Self(1i32);
}
impl ::core::marker::Copy for CameraUIControlMode {}
impl ::core::clone::Clone for CameraUIControlMode {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[repr(transparent)]
pub struct CameraUIControlPhotoFormat(pub i32);
impl CameraUIControlPhotoFormat {
pub const Jpeg: Self = Self(0i32);
pub const Png: Self = Self(1i32);
pub const JpegXR: Self = Self(2i32);
}
impl ::core::marker::Copy for CameraUIControlPhotoFormat {}
impl ::core::clone::Clone for CameraUIControlPhotoFormat {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[repr(transparent)]
pub struct CameraUIControlVideoFormat(pub i32);
impl CameraUIControlVideoFormat {
pub const Mp4: Self = Self(0i32);
pub const Wmv: Self = Self(1i32);
}
impl ::core::marker::Copy for CameraUIControlVideoFormat {}
impl ::core::clone::Clone for CameraUIControlVideoFormat {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[repr(transparent)]
pub struct CameraUIControlViewType(pub i32);
impl CameraUIControlViewType {
pub const SingleItem: Self = Self(0i32);
pub const ItemList: Self = Self(1i32);
}
impl ::core::marker::Copy for CameraUIControlViewType {}
impl ::core::clone::Clone for CameraUIControlViewType {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type DECISION_LOCATION = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_REFRESH_GLOBAL_DATA: DECISION_LOCATION = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_PARAMETER_VALIDATION: DECISION_LOCATION = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_AUDIT: DECISION_LOCATION = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_FAILED_CONVERT_GUID: DECISION_LOCATION = 3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_ENTERPRISE_DEFINED_CLASS_ID: DECISION_LOCATION = 4i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_GLOBAL_BUILT_IN_LIST: DECISION_LOCATION = 5i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_PROVIDER_BUILT_IN_LIST: DECISION_LOCATION = 6i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_ENFORCE_STATE_LIST: DECISION_LOCATION = 7i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_NOT_FOUND: DECISION_LOCATION = 8i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const DECISION_LOCATION_UNKNOWN: DECISION_LOCATION = 9i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type FEATURE_CHANGE_TIME = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FEATURE_CHANGE_TIME_READ: FEATURE_CHANGE_TIME = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FEATURE_CHANGE_TIME_MODULE_RELOAD: FEATURE_CHANGE_TIME = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FEATURE_CHANGE_TIME_SESSION: FEATURE_CHANGE_TIME = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FEATURE_CHANGE_TIME_REBOOT: FEATURE_CHANGE_TIME = 3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type FEATURE_ENABLED_STATE = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FEATURE_ENABLED_STATE_DEFAULT: FEATURE_ENABLED_STATE = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FEATURE_ENABLED_STATE_DISABLED: FEATURE_ENABLED_STATE = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FEATURE_ENABLED_STATE_ENABLED: FEATURE_ENABLED_STATE = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type FILE_INFORMATION_CLASS = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const FileDirectoryInformation: FILE_INFORMATION_CLASS = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type KEY_SET_INFORMATION_CLASS = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KeyWriteTimeInformation: KEY_SET_INFORMATION_CLASS = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KeyWow64FlagsInformation: KEY_SET_INFORMATION_CLASS = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KeyControlFlagsInformation: KEY_SET_INFORMATION_CLASS = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KeySetVirtualizationInformation: KEY_SET_INFORMATION_CLASS = 3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KeySetDebugInformation: KEY_SET_INFORMATION_CLASS = 4i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KeySetHandleTagsInformation: KEY_SET_INFORMATION_CLASS = 5i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const MaxKeySetInfoClass: KEY_SET_INFORMATION_CLASS = 6i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type OBJECT_INFORMATION_CLASS = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ObjectBasicInformation: OBJECT_INFORMATION_CLASS = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ObjectTypeInformation: OBJECT_INFORMATION_CLASS = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type SYSTEM_INFORMATION_CLASS = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemBasicInformation: SYSTEM_INFORMATION_CLASS = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemPerformanceInformation: SYSTEM_INFORMATION_CLASS = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemTimeOfDayInformation: SYSTEM_INFORMATION_CLASS = 3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemProcessInformation: SYSTEM_INFORMATION_CLASS = 5i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemProcessorPerformanceInformation: SYSTEM_INFORMATION_CLASS = 8i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemInterruptInformation: SYSTEM_INFORMATION_CLASS = 23i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemExceptionInformation: SYSTEM_INFORMATION_CLASS = 33i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemRegistryQuotaInformation: SYSTEM_INFORMATION_CLASS = 37i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemLookasideInformation: SYSTEM_INFORMATION_CLASS = 45i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemCodeIntegrityInformation: SYSTEM_INFORMATION_CLASS = 103i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SystemPolicyInformation: SYSTEM_INFORMATION_CLASS = 134i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type TDIENTITY_ENTITY_TYPE = u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GENERIC_ENTITY: TDIENTITY_ENTITY_TYPE = 0u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const AT_ENTITY: TDIENTITY_ENTITY_TYPE = 640u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CL_NL_ENTITY: TDIENTITY_ENTITY_TYPE = 769u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CO_NL_ENTITY: TDIENTITY_ENTITY_TYPE = 768u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CL_TL_ENTITY: TDIENTITY_ENTITY_TYPE = 1025u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const CO_TL_ENTITY: TDIENTITY_ENTITY_TYPE = 1024u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const ER_ENTITY: TDIENTITY_ENTITY_TYPE = 896u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const IF_ENTITY: TDIENTITY_ENTITY_TYPE = 512u32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type TDI_TL_IO_CONTROL_TYPE = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const EndpointIoControlType: TDI_TL_IO_CONTROL_TYPE = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SetSockOptIoControlType: TDI_TL_IO_CONTROL_TYPE = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const GetSockOptIoControlType: TDI_TL_IO_CONTROL_TYPE = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const SocketIoControlType: TDI_TL_IO_CONTROL_TYPE = 3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type VALUENAME = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const VALUENAME_UNKNOWN: VALUENAME = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const VALUENAME_ENTERPRISE_DEFINED_CLASS_ID: VALUENAME = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const VALUENAME_BUILT_IN_LIST: VALUENAME = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type WINSTATIONINFOCLASS = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WinStationInformation: WINSTATIONINFOCLASS = 8i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type WLDP_HOST = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_RUNDLL32: WLDP_HOST = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_SVCHOST: WLDP_HOST = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_MAX: WLDP_HOST = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type WLDP_HOST_ID = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_UNKNOWN: WLDP_HOST_ID = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_GLOBAL: WLDP_HOST_ID = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_VBA: WLDP_HOST_ID = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_WSH: WLDP_HOST_ID = 3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_POWERSHELL: WLDP_HOST_ID = 4i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_IE: WLDP_HOST_ID = 5i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_MSI: WLDP_HOST_ID = 6i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_ALL: WLDP_HOST_ID = 7i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_HOST_ID_MAX: WLDP_HOST_ID = 8i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type WLDP_KEY = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KEY_UNKNOWN: WLDP_KEY = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KEY_OVERRIDE: WLDP_KEY = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const KEY_ALL_KEYS: WLDP_KEY = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type WLDP_POLICY_SETTING = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_POLICY_SETTING_AV_PERF_MODE: WLDP_POLICY_SETTING = 1000i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type WLDP_WINDOWS_LOCKDOWN_MODE = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_MODE_UNLOCKED: WLDP_WINDOWS_LOCKDOWN_MODE = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_MODE_TRIAL: WLDP_WINDOWS_LOCKDOWN_MODE = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_MODE_LOCKED: WLDP_WINDOWS_LOCKDOWN_MODE = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_MODE_MAX: WLDP_WINDOWS_LOCKDOWN_MODE = 3i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type WLDP_WINDOWS_LOCKDOWN_RESTRICTION = i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_NONE: WLDP_WINDOWS_LOCKDOWN_RESTRICTION = 0i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_NOUNLOCK: WLDP_WINDOWS_LOCKDOWN_RESTRICTION = 1i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_NOUNLOCK_PERMANENT: WLDP_WINDOWS_LOCKDOWN_RESTRICTION = 2i32;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub const WLDP_WINDOWS_LOCKDOWN_RESTRICTION_MAX: WLDP_WINDOWS_LOCKDOWN_RESTRICTION = 3i32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct ACTCTX_SECTION_KEYED_DATA_2600 {
pub cbSize: u32,
pub ulDataFormatVersion: u32,
pub lpData: *mut ::core::ffi::c_void,
pub ulLength: u32,
pub lpSectionGlobalData: *mut ::core::ffi::c_void,
pub ulSectionGlobalDataLength: u32,
pub lpSectionBase: *mut ::core::ffi::c_void,
pub ulSectionTotalLength: u32,
pub hActCtx: super::super::Foundation::HANDLE,
pub ulAssemblyRosterIndex: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ACTCTX_SECTION_KEYED_DATA_2600 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ACTCTX_SECTION_KEYED_DATA_2600 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA {
pub lpInformation: *mut ::core::ffi::c_void,
pub lpSectionBase: *mut ::core::ffi::c_void,
pub ulSectionLength: u32,
pub lpSectionGlobalDataBase: *mut ::core::ffi::c_void,
pub ulSectionGlobalDataLength: u32,
}
impl ::core::marker::Copy for ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA {}
impl ::core::clone::Clone for ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct ACTIVATION_CONTEXT_BASIC_INFORMATION {
pub hActCtx: super::super::Foundation::HANDLE,
pub dwFlags: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ACTIVATION_CONTEXT_BASIC_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ACTIVATION_CONTEXT_BASIC_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct CABINFOA {
pub pszCab: ::windows_sys::core::PSTR,
pub pszInf: ::windows_sys::core::PSTR,
pub pszSection: ::windows_sys::core::PSTR,
pub szSrcPath: [super::super::Foundation::CHAR; 260],
pub dwFlags: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for CABINFOA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for CABINFOA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct CABINFOW {
pub pszCab: ::windows_sys::core::PWSTR,
pub pszInf: ::windows_sys::core::PWSTR,
pub pszSection: ::windows_sys::core::PWSTR,
pub szSrcPath: [u16; 260],
pub dwFlags: u32,
}
impl ::core::marker::Copy for CABINFOW {}
impl ::core::clone::Clone for CABINFOW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct CLIENT_ID {
pub UniqueProcess: super::super::Foundation::HANDLE,
pub UniqueThread: super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for CLIENT_ID {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for CLIENT_ID {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG {
pub Size: u32,
pub TriggerId: ::windows_sys::core::PCWSTR,
}
impl ::core::marker::Copy for CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG {}
impl ::core::clone::Clone for CUSTOM_SYSTEM_EVENT_TRIGGER_CONFIG {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct DATETIME {
pub year: u16,
pub month: u16,
pub day: u16,
pub hour: u16,
pub min: u16,
pub sec: u16,
}
impl ::core::marker::Copy for DATETIME {}
impl ::core::clone::Clone for DATETIME {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct DCICMD {
pub dwCommand: u32,
pub dwParam1: u32,
pub dwParam2: u32,
pub dwVersion: u32,
pub dwReserved: u32,
}
impl ::core::marker::Copy for DCICMD {}
impl ::core::clone::Clone for DCICMD {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct DCICREATEINPUT {
pub cmd: DCICMD,
pub dwCompression: u32,
pub dwMask: [u32; 3],
pub dwWidth: u32,
pub dwHeight: u32,
pub dwDCICaps: u32,
pub dwBitCount: u32,
pub lpSurface: *mut ::core::ffi::c_void,
}
impl ::core::marker::Copy for DCICREATEINPUT {}
impl ::core::clone::Clone for DCICREATEINPUT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct DCIENUMINPUT {
pub cmd: DCICMD,
pub rSrc: super::super::Foundation::RECT,
pub rDst: super::super::Foundation::RECT,
pub EnumCallback: isize,
pub lpContext: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for DCIENUMINPUT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for DCIENUMINPUT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct DCIOFFSCREEN {
pub dciInfo: DCISURFACEINFO,
pub Draw: isize,
pub SetClipList: isize,
pub SetDestination: isize,
}
impl ::core::marker::Copy for DCIOFFSCREEN {}
impl ::core::clone::Clone for DCIOFFSCREEN {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct DCIOVERLAY {
pub dciInfo: DCISURFACEINFO,
pub dwChromakeyValue: u32,
pub dwChromakeyMask: u32,
}
impl ::core::marker::Copy for DCIOVERLAY {}
impl ::core::clone::Clone for DCIOVERLAY {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct DCISURFACEINFO {
pub dwSize: u32,
pub dwDCICaps: u32,
pub dwCompression: u32,
pub dwMask: [u32; 3],
pub dwWidth: u32,
pub dwHeight: u32,
pub lStride: i32,
pub dwBitCount: u32,
pub dwOffSurface: usize,
pub wSelSurface: u16,
pub wReserved: u16,
pub dwReserved1: u32,
pub dwReserved2: u32,
pub dwReserved3: u32,
pub BeginAccess: isize,
pub EndAccess: isize,
pub DestroySurface: isize,
}
impl ::core::marker::Copy for DCISURFACEINFO {}
impl ::core::clone::Clone for DCISURFACEINFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
pub struct DELAYLOAD_INFO {
pub Size: u32,
pub DelayloadDescriptor: *mut IMAGE_DELAYLOAD_DESCRIPTOR,
pub ThunkAddress: *mut IMAGE_THUNK_DATA64,
pub TargetDllName: ::windows_sys::core::PCSTR,
pub TargetApiDescriptor: DELAYLOAD_PROC_DESCRIPTOR,
pub TargetModuleBase: *mut ::core::ffi::c_void,
pub Unused: *mut ::core::ffi::c_void,
pub LastError: u32,
}
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
impl ::core::marker::Copy for DELAYLOAD_INFO {}
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
impl ::core::clone::Clone for DELAYLOAD_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[cfg(target_arch = "x86")]
pub struct DELAYLOAD_INFO {
pub Size: u32,
pub DelayloadDescriptor: *mut IMAGE_DELAYLOAD_DESCRIPTOR,
pub ThunkAddress: *mut IMAGE_THUNK_DATA32,
pub TargetDllName: ::windows_sys::core::PCSTR,
pub TargetApiDescriptor: DELAYLOAD_PROC_DESCRIPTOR,
pub TargetModuleBase: *mut ::core::ffi::c_void,
pub Unused: *mut ::core::ffi::c_void,
pub LastError: u32,
}
#[cfg(target_arch = "x86")]
impl ::core::marker::Copy for DELAYLOAD_INFO {}
#[cfg(target_arch = "x86")]
impl ::core::clone::Clone for DELAYLOAD_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct DELAYLOAD_PROC_DESCRIPTOR {
pub ImportDescribedByName: u32,
pub Description: DELAYLOAD_PROC_DESCRIPTOR_0,
}
impl ::core::marker::Copy for DELAYLOAD_PROC_DESCRIPTOR {}
impl ::core::clone::Clone for DELAYLOAD_PROC_DESCRIPTOR {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub union DELAYLOAD_PROC_DESCRIPTOR_0 {
pub Name: ::windows_sys::core::PCSTR,
pub Ordinal: u32,
}
impl ::core::marker::Copy for DELAYLOAD_PROC_DESCRIPTOR_0 {}
impl ::core::clone::Clone for DELAYLOAD_PROC_DESCRIPTOR_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct FEATURE_ERROR {
pub hr: ::windows_sys::core::HRESULT,
pub lineNumber: u16,
pub file: ::windows_sys::core::PCSTR,
pub process: ::windows_sys::core::PCSTR,
pub module: ::windows_sys::core::PCSTR,
pub callerReturnAddressOffset: u32,
pub callerModule: ::windows_sys::core::PCSTR,
pub message: ::windows_sys::core::PCSTR,
pub originLineNumber: u16,
pub originFile: ::windows_sys::core::PCSTR,
pub originModule: ::windows_sys::core::PCSTR,
pub originCallerReturnAddressOffset: u32,
pub originCallerModule: ::windows_sys::core::PCSTR,
pub originName: ::windows_sys::core::PCSTR,
}
impl ::core::marker::Copy for FEATURE_ERROR {}
impl ::core::clone::Clone for FEATURE_ERROR {
fn clone(&self) -> Self {
*self
}
}
pub type FEATURE_STATE_CHANGE_SUBSCRIPTION = isize;
pub type FH_SERVICE_PIPE_HANDLE = isize;
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct FILE_CASE_SENSITIVE_INFO {
pub Flags: u32,
}
impl ::core::marker::Copy for FILE_CASE_SENSITIVE_INFO {}
impl ::core::clone::Clone for FILE_CASE_SENSITIVE_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct FILE_DISPOSITION_INFO_EX {
pub Flags: u32,
}
impl ::core::marker::Copy for FILE_DISPOSITION_INFO_EX {}
impl ::core::clone::Clone for FILE_DISPOSITION_INFO_EX {
fn clone(&self) -> Self {
*self
}
}
pub type HWINWATCH = isize;
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct HW_PROFILE_INFOA {
pub dwDockInfo: u32,
pub szHwProfileGuid: [super::super::Foundation::CHAR; 39],
pub szHwProfileName: [super::super::Foundation::CHAR; 80],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for HW_PROFILE_INFOA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for HW_PROFILE_INFOA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct HW_PROFILE_INFOW {
pub dwDockInfo: u32,
pub szHwProfileGuid: [u16; 39],
pub szHwProfileName: [u16; 80],
}
impl ::core::marker::Copy for HW_PROFILE_INFOW {}
impl ::core::clone::Clone for HW_PROFILE_INFOW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct IMAGE_DELAYLOAD_DESCRIPTOR {
pub Attributes: IMAGE_DELAYLOAD_DESCRIPTOR_0,
pub DllNameRVA: u32,
pub ModuleHandleRVA: u32,
pub ImportAddressTableRVA: u32,
pub ImportNameTableRVA: u32,
pub BoundImportAddressTableRVA: u32,
pub UnloadInformationTableRVA: u32,
pub TimeDateStamp: u32,
}
impl ::core::marker::Copy for IMAGE_DELAYLOAD_DESCRIPTOR {}
impl ::core::clone::Clone for IMAGE_DELAYLOAD_DESCRIPTOR {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub union IMAGE_DELAYLOAD_DESCRIPTOR_0 {
pub AllAttributes: u32,
pub Anonymous: IMAGE_DELAYLOAD_DESCRIPTOR_0_0,
}
impl ::core::marker::Copy for IMAGE_DELAYLOAD_DESCRIPTOR_0 {}
impl ::core::clone::Clone for IMAGE_DELAYLOAD_DESCRIPTOR_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct IMAGE_DELAYLOAD_DESCRIPTOR_0_0 {
pub _bitfield: u32,
}
impl ::core::marker::Copy for IMAGE_DELAYLOAD_DESCRIPTOR_0_0 {}
impl ::core::clone::Clone for IMAGE_DELAYLOAD_DESCRIPTOR_0_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct IMAGE_THUNK_DATA32 {
pub u1: IMAGE_THUNK_DATA32_0,
}
impl ::core::marker::Copy for IMAGE_THUNK_DATA32 {}
impl ::core::clone::Clone for IMAGE_THUNK_DATA32 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub union IMAGE_THUNK_DATA32_0 {
pub ForwarderString: u32,
pub Function: u32,
pub Ordinal: u32,
pub AddressOfData: u32,
}
impl ::core::marker::Copy for IMAGE_THUNK_DATA32_0 {}
impl ::core::clone::Clone for IMAGE_THUNK_DATA32_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct IMAGE_THUNK_DATA64 {
pub u1: IMAGE_THUNK_DATA64_0,
}
impl ::core::marker::Copy for IMAGE_THUNK_DATA64 {}
impl ::core::clone::Clone for IMAGE_THUNK_DATA64 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub union IMAGE_THUNK_DATA64_0 {
pub ForwarderString: u64,
pub Function: u64,
pub Ordinal: u64,
pub AddressOfData: u64,
}
impl ::core::marker::Copy for IMAGE_THUNK_DATA64_0 {}
impl ::core::clone::Clone for IMAGE_THUNK_DATA64_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct IMEPROA {
pub hWnd: super::super::Foundation::HWND,
pub InstDate: DATETIME,
pub wVersion: u32,
pub szDescription: [u8; 50],
pub szName: [u8; 80],
pub szOptions: [u8; 30],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for IMEPROA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for IMEPROA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct IMEPROW {
pub hWnd: super::super::Foundation::HWND,
pub InstDate: DATETIME,
pub wVersion: u32,
pub szDescription: [u16; 50],
pub szName: [u16; 80],
pub szOptions: [u16; 30],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for IMEPROW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for IMEPROW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct IMESTRUCT {
pub fnc: u32,
pub wParam: super::super::Foundation::WPARAM,
pub wCount: u32,
pub dchSource: u32,
pub dchDest: u32,
pub lParam1: super::super::Foundation::LPARAM,
pub lParam2: super::super::Foundation::LPARAM,
pub lParam3: super::super::Foundation::LPARAM,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for IMESTRUCT {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for IMESTRUCT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct IO_STATUS_BLOCK {
pub Anonymous: IO_STATUS_BLOCK_0,
pub Information: usize,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for IO_STATUS_BLOCK {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for IO_STATUS_BLOCK {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub union IO_STATUS_BLOCK_0 {
pub Status: super::super::Foundation::NTSTATUS,
pub Pointer: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for IO_STATUS_BLOCK_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for IO_STATUS_BLOCK_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct JAVA_TRUST {
pub cbSize: u32,
pub flag: u32,
pub fAllActiveXPermissions: super::super::Foundation::BOOL,
pub fAllPermissions: super::super::Foundation::BOOL,
pub dwEncodingType: u32,
pub pbJavaPermissions: *mut u8,
pub cbJavaPermissions: u32,
pub pbSigner: *mut u8,
pub cbSigner: u32,
pub pwszZone: ::windows_sys::core::PCWSTR,
pub guidZone: ::windows_sys::core::GUID,
pub hVerify: ::windows_sys::core::HRESULT,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for JAVA_TRUST {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for JAVA_TRUST {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct JIT_DEBUG_INFO {
pub dwSize: u32,
pub dwProcessorArchitecture: u32,
pub dwThreadID: u32,
pub dwReserved0: u32,
pub lpExceptionAddress: u64,
pub lpExceptionRecord: u64,
pub lpContextRecord: u64,
}
impl ::core::marker::Copy for JIT_DEBUG_INFO {}
impl ::core::clone::Clone for JIT_DEBUG_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct KEY_VALUE_ENTRY {
pub ValueName: *mut super::super::Foundation::UNICODE_STRING,
pub DataLength: u32,
pub DataOffset: u32,
pub Type: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for KEY_VALUE_ENTRY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for KEY_VALUE_ENTRY {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
pub struct LDR_DATA_TABLE_ENTRY {
pub Reserved1: [*mut ::core::ffi::c_void; 2],
pub InMemoryOrderLinks: super::Kernel::LIST_ENTRY,
pub Reserved2: [*mut ::core::ffi::c_void; 2],
pub DllBase: *mut ::core::ffi::c_void,
pub Reserved3: [*mut ::core::ffi::c_void; 2],
pub FullDllName: super::super::Foundation::UNICODE_STRING,
pub Reserved4: [u8; 8],
pub Reserved5: [*mut ::core::ffi::c_void; 3],
pub Anonymous: LDR_DATA_TABLE_ENTRY_0,
pub TimeDateStamp: u32,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
impl ::core::marker::Copy for LDR_DATA_TABLE_ENTRY {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
impl ::core::clone::Clone for LDR_DATA_TABLE_ENTRY {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`, `\"Win32_System_Kernel\"`*"]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
pub union LDR_DATA_TABLE_ENTRY_0 {
pub CheckSum: u32,
pub Reserved6: *mut ::core::ffi::c_void,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
impl ::core::marker::Copy for LDR_DATA_TABLE_ENTRY_0 {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Kernel"))]
impl ::core::clone::Clone for LDR_DATA_TABLE_ENTRY_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct OBJECT_ATTRIBUTES {
pub Length: u32,
pub RootDirectory: super::super::Foundation::HANDLE,
pub ObjectName: *mut super::super::Foundation::UNICODE_STRING,
pub Attributes: u32,
pub SecurityDescriptor: *mut ::core::ffi::c_void,
pub SecurityQualityOfService: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for OBJECT_ATTRIBUTES {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for OBJECT_ATTRIBUTES {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct PERUSERSECTIONA {
pub szGUID: [super::super::Foundation::CHAR; 59],
pub szDispName: [super::super::Foundation::CHAR; 128],
pub szLocale: [super::super::Foundation::CHAR; 10],
pub szStub: [super::super::Foundation::CHAR; 1040],
pub szVersion: [super::super::Foundation::CHAR; 32],
pub szCompID: [super::super::Foundation::CHAR; 128],
pub dwIsInstalled: u32,
pub bRollback: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PERUSERSECTIONA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PERUSERSECTIONA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct PERUSERSECTIONW {
pub szGUID: [u16; 59],
pub szDispName: [u16; 128],
pub szLocale: [u16; 10],
pub szStub: [u16; 1040],
pub szVersion: [u16; 32],
pub szCompID: [u16; 128],
pub dwIsInstalled: u32,
pub bRollback: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PERUSERSECTIONW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PERUSERSECTIONW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct PUBLIC_OBJECT_BASIC_INFORMATION {
pub Attributes: u32,
pub GrantedAccess: u32,
pub HandleCount: u32,
pub PointerCount: u32,
pub Reserved: [u32; 10],
}
impl ::core::marker::Copy for PUBLIC_OBJECT_BASIC_INFORMATION {}
impl ::core::clone::Clone for PUBLIC_OBJECT_BASIC_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct PUBLIC_OBJECT_TYPE_INFORMATION {
pub TypeName: super::super::Foundation::UNICODE_STRING,
pub Reserved: [u32; 22],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for PUBLIC_OBJECT_TYPE_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for PUBLIC_OBJECT_TYPE_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct STRENTRYA {
pub pszName: ::windows_sys::core::PSTR,
pub pszValue: ::windows_sys::core::PSTR,
}
impl ::core::marker::Copy for STRENTRYA {}
impl ::core::clone::Clone for STRENTRYA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct STRENTRYW {
pub pszName: ::windows_sys::core::PWSTR,
pub pszValue: ::windows_sys::core::PWSTR,
}
impl ::core::marker::Copy for STRENTRYW {}
impl ::core::clone::Clone for STRENTRYW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct STRINGEXSTRUCT {
pub dwSize: u32,
pub uDeterminePos: u32,
pub uDetermineDelimPos: u32,
pub uYomiPos: u32,
pub uYomiDelimPos: u32,
}
impl ::core::marker::Copy for STRINGEXSTRUCT {}
impl ::core::clone::Clone for STRINGEXSTRUCT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct STRTABLEA {
pub cEntries: u32,
pub pse: *mut STRENTRYA,
}
impl ::core::marker::Copy for STRTABLEA {}
impl ::core::clone::Clone for STRTABLEA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct STRTABLEW {
pub cEntries: u32,
pub pse: *mut STRENTRYW,
}
impl ::core::marker::Copy for STRTABLEW {}
impl ::core::clone::Clone for STRTABLEW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_BASIC_INFORMATION {
pub Reserved1: [u8; 24],
pub Reserved2: [*mut ::core::ffi::c_void; 4],
pub NumberOfProcessors: i8,
}
impl ::core::marker::Copy for SYSTEM_BASIC_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_BASIC_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_CODEINTEGRITY_INFORMATION {
pub Length: u32,
pub CodeIntegrityOptions: u32,
}
impl ::core::marker::Copy for SYSTEM_CODEINTEGRITY_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_CODEINTEGRITY_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_EXCEPTION_INFORMATION {
pub Reserved1: [u8; 16],
}
impl ::core::marker::Copy for SYSTEM_EXCEPTION_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_EXCEPTION_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_INTERRUPT_INFORMATION {
pub Reserved1: [u8; 24],
}
impl ::core::marker::Copy for SYSTEM_INTERRUPT_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_INTERRUPT_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_LOOKASIDE_INFORMATION {
pub Reserved1: [u8; 32],
}
impl ::core::marker::Copy for SYSTEM_LOOKASIDE_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_LOOKASIDE_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_PERFORMANCE_INFORMATION {
pub Reserved1: [u8; 312],
}
impl ::core::marker::Copy for SYSTEM_PERFORMANCE_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_PERFORMANCE_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_POLICY_INFORMATION {
pub Reserved1: [*mut ::core::ffi::c_void; 2],
pub Reserved2: [u32; 3],
}
impl ::core::marker::Copy for SYSTEM_POLICY_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_POLICY_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
pub IdleTime: i64,
pub KernelTime: i64,
pub UserTime: i64,
pub Reserved1: [i64; 2],
pub Reserved2: u32,
}
impl ::core::marker::Copy for SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct SYSTEM_PROCESS_INFORMATION {
pub NextEntryOffset: u32,
pub NumberOfThreads: u32,
pub Reserved1: [u8; 48],
pub ImageName: super::super::Foundation::UNICODE_STRING,
pub BasePriority: i32,
pub UniqueProcessId: super::super::Foundation::HANDLE,
pub Reserved2: *mut ::core::ffi::c_void,
pub HandleCount: u32,
pub SessionId: u32,
pub Reserved3: *mut ::core::ffi::c_void,
pub PeakVirtualSize: usize,
pub VirtualSize: usize,
pub Reserved4: u32,
pub PeakWorkingSetSize: usize,
pub WorkingSetSize: usize,
pub Reserved5: *mut ::core::ffi::c_void,
pub QuotaPagedPoolUsage: usize,
pub Reserved6: *mut ::core::ffi::c_void,
pub QuotaNonPagedPoolUsage: usize,
pub PagefileUsage: usize,
pub PeakPagefileUsage: usize,
pub PrivatePageCount: usize,
pub Reserved7: [i64; 6],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for SYSTEM_PROCESS_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for SYSTEM_PROCESS_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_REGISTRY_QUOTA_INFORMATION {
pub RegistryQuotaAllowed: u32,
pub RegistryQuotaUsed: u32,
pub Reserved1: *mut ::core::ffi::c_void,
}
impl ::core::marker::Copy for SYSTEM_REGISTRY_QUOTA_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_REGISTRY_QUOTA_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct SYSTEM_THREAD_INFORMATION {
pub Reserved1: [i64; 3],
pub Reserved2: u32,
pub StartAddress: *mut ::core::ffi::c_void,
pub ClientId: CLIENT_ID,
pub Priority: i32,
pub BasePriority: i32,
pub Reserved3: u32,
pub ThreadState: u32,
pub WaitReason: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for SYSTEM_THREAD_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for SYSTEM_THREAD_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct SYSTEM_TIMEOFDAY_INFORMATION {
pub Reserved1: [u8; 48],
}
impl ::core::marker::Copy for SYSTEM_TIMEOFDAY_INFORMATION {}
impl ::core::clone::Clone for SYSTEM_TIMEOFDAY_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
pub struct TCP_REQUEST_QUERY_INFORMATION_EX32_XP {
pub ID: TDIObjectID,
pub Context: [u32; 4],
}
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
impl ::core::marker::Copy for TCP_REQUEST_QUERY_INFORMATION_EX32_XP {}
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
impl ::core::clone::Clone for TCP_REQUEST_QUERY_INFORMATION_EX32_XP {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct TCP_REQUEST_QUERY_INFORMATION_EX_W2K {
pub ID: TDIObjectID,
pub Context: [u8; 16],
}
impl ::core::marker::Copy for TCP_REQUEST_QUERY_INFORMATION_EX_W2K {}
impl ::core::clone::Clone for TCP_REQUEST_QUERY_INFORMATION_EX_W2K {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct TCP_REQUEST_QUERY_INFORMATION_EX_XP {
pub ID: TDIObjectID,
pub Context: [usize; 4],
}
impl ::core::marker::Copy for TCP_REQUEST_QUERY_INFORMATION_EX_XP {}
impl ::core::clone::Clone for TCP_REQUEST_QUERY_INFORMATION_EX_XP {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct TCP_REQUEST_SET_INFORMATION_EX {
pub ID: TDIObjectID,
pub BufferSize: u32,
pub Buffer: [u8; 1],
}
impl ::core::marker::Copy for TCP_REQUEST_SET_INFORMATION_EX {}
impl ::core::clone::Clone for TCP_REQUEST_SET_INFORMATION_EX {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct TDIEntityID {
pub tei_entity: TDIENTITY_ENTITY_TYPE,
pub tei_instance: u32,
}
impl ::core::marker::Copy for TDIEntityID {}
impl ::core::clone::Clone for TDIEntityID {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct TDIObjectID {
pub toi_entity: TDIEntityID,
pub toi_class: u32,
pub toi_type: u32,
pub toi_id: u32,
}
impl ::core::marker::Copy for TDIObjectID {}
impl ::core::clone::Clone for TDIObjectID {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct TDI_TL_IO_CONTROL_ENDPOINT {
pub Type: TDI_TL_IO_CONTROL_TYPE,
pub Level: u32,
pub Anonymous: TDI_TL_IO_CONTROL_ENDPOINT_0,
pub InputBuffer: *mut ::core::ffi::c_void,
pub InputBufferLength: u32,
pub OutputBuffer: *mut ::core::ffi::c_void,
pub OutputBufferLength: u32,
}
impl ::core::marker::Copy for TDI_TL_IO_CONTROL_ENDPOINT {}
impl ::core::clone::Clone for TDI_TL_IO_CONTROL_ENDPOINT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub union TDI_TL_IO_CONTROL_ENDPOINT_0 {
pub IoControlCode: u32,
pub OptionName: u32,
}
impl ::core::marker::Copy for TDI_TL_IO_CONTROL_ENDPOINT_0 {}
impl ::core::clone::Clone for TDI_TL_IO_CONTROL_ENDPOINT_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct THREAD_NAME_INFORMATION {
pub ThreadName: super::super::Foundation::UNICODE_STRING,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for THREAD_NAME_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for THREAD_NAME_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct UNDETERMINESTRUCT {
pub dwSize: u32,
pub uDefIMESize: u32,
pub uDefIMEPos: u32,
pub uUndetTextLen: u32,
pub uUndetTextPos: u32,
pub uUndetAttrPos: u32,
pub uCursorPos: u32,
pub uDeltaStart: u32,
pub uDetermineTextLen: u32,
pub uDetermineTextPos: u32,
pub uDetermineDelimPos: u32,
pub uYomiTextLen: u32,
pub uYomiTextPos: u32,
pub uYomiDelimPos: u32,
}
impl ::core::marker::Copy for UNDETERMINESTRUCT {}
impl ::core::clone::Clone for UNDETERMINESTRUCT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct WINSTATIONINFORMATIONW {
pub Reserved2: [u8; 70],
pub LogonId: u32,
pub Reserved3: [u8; 1140],
}
impl ::core::marker::Copy for WINSTATIONINFORMATIONW {}
impl ::core::clone::Clone for WINSTATIONINFORMATIONW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub struct WLDP_DEVICE_SECURITY_INFORMATION {
pub UnlockIdSize: u32,
pub UnlockId: *mut u8,
pub ManufacturerIDLength: u32,
pub ManufacturerID: ::windows_sys::core::PWSTR,
}
impl ::core::marker::Copy for WLDP_DEVICE_SECURITY_INFORMATION {}
impl ::core::clone::Clone for WLDP_DEVICE_SECURITY_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub struct WLDP_HOST_INFORMATION {
pub dwRevision: u32,
pub dwHostId: WLDP_HOST_ID,
pub szSource: ::windows_sys::core::PCWSTR,
pub hSource: super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for WLDP_HOST_INFORMATION {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for WLDP_HOST_INFORMATION {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct _D3DHAL_CALLBACKS(pub u8);
#[repr(C)]
pub struct _D3DHAL_GLOBALDRIVERDATA(pub u8);
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type APPLICATION_RECOVERY_CALLBACK = ::core::option::Option<unsafe extern "system" fn(pvparameter: *mut ::core::ffi::c_void) -> u32>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type ENUM_CALLBACK = ::core::option::Option<unsafe extern "system" fn(lpsurfaceinfo: *mut DCISURFACEINFO, lpcontext: *mut ::core::ffi::c_void) -> ()>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PDELAYLOAD_FAILURE_DLL_CALLBACK = ::core::option::Option<unsafe extern "system" fn(notificationreason: u32, delayloadinfo: *const DELAYLOAD_INFO) -> *mut ::core::ffi::c_void>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PFEATURE_STATE_CHANGE_CALLBACK = ::core::option::Option<unsafe extern "system" fn(context: *const ::core::ffi::c_void) -> ()>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PFIBER_CALLOUT_ROUTINE = ::core::option::Option<unsafe extern "system" fn(lpparameter: *mut ::core::ffi::c_void) -> *mut ::core::ffi::c_void>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PIO_APC_ROUTINE = ::core::option::Option<unsafe extern "system" fn(apccontext: *mut ::core::ffi::c_void, iostatusblock: *mut IO_STATUS_BLOCK, reserved: u32) -> ()>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PQUERYACTCTXW_FUNC = ::core::option::Option<unsafe extern "system" fn(dwflags: u32, hactctx: super::super::Foundation::HANDLE, pvsubinstance: *const ::core::ffi::c_void, ulinfoclass: u32, pvbuffer: *mut ::core::ffi::c_void, cbbuffer: usize, pcbwrittenorrequired: *mut usize) -> super::super::Foundation::BOOL>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWINSTATIONQUERYINFORMATIONW = ::core::option::Option<unsafe extern "system" fn(param0: super::super::Foundation::HANDLE, param1: u32, param2: WINSTATIONINFOCLASS, param3: *mut ::core::ffi::c_void, param4: u32, param5: *mut u32) -> super::super::Foundation::BOOLEAN>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PWLDP_ISAPPAPPROVEDBYPOLICY_API = ::core::option::Option<unsafe extern "system" fn(packagefamilyname: ::windows_sys::core::PCWSTR, packageversion: u64) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWLDP_ISDYNAMICCODEPOLICYENABLED_API = ::core::option::Option<unsafe extern "system" fn(pbenabled: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWLDP_ISPRODUCTIONCONFIGURATION_API = ::core::option::Option<unsafe extern "system" fn(isproductionconfiguration: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWLDP_ISWCOSPRODUCTIONCONFIGURATION_API = ::core::option::Option<unsafe extern "system" fn(isproductionconfiguration: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PWLDP_QUERYDEVICESECURITYINFORMATION_API = ::core::option::Option<unsafe extern "system" fn(information: *mut WLDP_DEVICE_SECURITY_INFORMATION, informationlength: u32, returnlength: *mut u32) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWLDP_QUERYDYNAMICODETRUST_API = ::core::option::Option<unsafe extern "system" fn(filehandle: super::super::Foundation::HANDLE, baseimage: *const ::core::ffi::c_void, imagesize: u32) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWLDP_QUERYPOLICYSETTINGENABLED2_API = ::core::option::Option<unsafe extern "system" fn(setting: ::windows_sys::core::PCWSTR, enabled: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWLDP_QUERYPOLICYSETTINGENABLED_API = ::core::option::Option<unsafe extern "system" fn(setting: WLDP_POLICY_SETTING, enabled: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PWLDP_QUERYWINDOWSLOCKDOWNMODE_API = ::core::option::Option<unsafe extern "system" fn(lockdownmode: *mut WLDP_WINDOWS_LOCKDOWN_MODE) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PWLDP_QUERYWINDOWSLOCKDOWNRESTRICTION_API = ::core::option::Option<unsafe extern "system" fn(lockdownrestriction: *mut WLDP_WINDOWS_LOCKDOWN_RESTRICTION) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PWLDP_RESETPRODUCTIONCONFIGURATION_API = ::core::option::Option<unsafe extern "system" fn() -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PWLDP_RESETWCOSPRODUCTIONCONFIGURATION_API = ::core::option::Option<unsafe extern "system" fn() -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type PWLDP_SETDYNAMICCODETRUST_API = ::core::option::Option<unsafe extern "system" fn(hfilehandle: super::super::Foundation::HANDLE) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`*"]
pub type PWLDP_SETWINDOWSLOCKDOWNRESTRICTION_API = ::core::option::Option<unsafe extern "system" fn(lockdownrestriction: WLDP_WINDOWS_LOCKDOWN_RESTRICTION) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type REGINSTALLA = ::core::option::Option<unsafe extern "system" fn(hm: super::super::Foundation::HINSTANCE, pszsection: ::windows_sys::core::PCSTR, psttable: *mut STRTABLEA) -> ::windows_sys::core::HRESULT>;
#[doc = "*Required features: `\"Win32_System_WindowsProgramming\"`, `\"Win32_Foundation\"`*"]
#[cfg(feature = "Win32_Foundation")]
pub type WINWATCHNOTIFYPROC = ::core::option::Option<unsafe extern "system" fn(hww: HWINWATCH, hwnd: super::super::Foundation::HWND, code: u32, lparam: super::super::Foundation::LPARAM) -> ()>;
|
// Copyright 2021 Chiral Ltd.
// Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
//! CNAP (Canonical Numbering by Automorphism Permutation)
//! Symmetry perception with theoretical completeness
mod combinatorial;
mod permutation;
mod isomorphism;
mod workflow;
pub use workflow::ErrorCNAP;
pub use workflow::run;
pub use workflow::is_computable;
pub use workflow::get_symmetric_orbits;
pub use combinatorial::factorial_vec; |
// TODO(thlorenz): move to separate module and impl From<Rad> where struct Rad(f32);
#[derive(Debug, PartialEq)]
pub(crate) enum DirectionX {
Left,
Right,
Parallel,
}
#[derive(Debug, PartialEq)]
pub(crate) enum DirectionY {
Up,
Down,
Parallel,
}
|
#[derive(Debug)]
enum InsKind {
Nop,
Acc,
Jmp,
}
impl InsKind {
fn from_name(name: &str) -> Self {
match name {
"acc" => InsKind::Acc,
"nop" => InsKind::Nop,
"jmp" => InsKind::Jmp,
_ => panic!("Unknown ins name"),
}
}
}
#[derive(Debug)]
struct Ins {
kind: InsKind,
arg: i32,
}
fn parse(input: &str) -> Vec<Ins> {
input.lines().map(parse_instr).collect()
}
fn parse_instr(input: &str) -> Ins {
let mut splits = input.split(' ');
let name = splits.next().unwrap();
let arg = splits.next().unwrap().parse().unwrap();
Ins {
kind: InsKind::from_name(name),
arg,
}
}
struct Vm<'a> {
acc: i32,
pc: i32,
instrs: &'a [Ins],
}
impl<'a> Vm<'a> {
fn new(instrs: &'a [Ins]) -> Self {
Self {
instrs,
acc: 0,
pc: 0,
}
}
fn cycle(&mut self) {
let ins = &self.instrs[self.pc as usize];
self.pc += 1;
match ins.kind {
InsKind::Acc => self.acc += ins.arg,
InsKind::Jmp => {
self.pc -= 1;
self.pc += ins.arg
}
InsKind::Nop => {}
}
}
}
enum ExecResult {
Terminate,
InfiLoop,
}
fn exec(vm: &mut Vm) -> ExecResult {
let mut visited = vec![false; vm.instrs.len()];
loop {
if visited[vm.pc as usize] {
return ExecResult::InfiLoop;
}
visited[vm.pc as usize] = true;
let last_ins = vm.pc as usize == vm.instrs.len() - 1;
vm.cycle();
if last_ins {
return ExecResult::Terminate;
}
}
}
fn part1(input: &str) -> i32 {
let instrs = parse(input);
let mut vm = Vm::new(&instrs);
match exec(&mut vm) {
ExecResult::InfiLoop => vm.acc,
_ => unreachable!(),
}
}
fn swap(ins: &mut Ins) {
ins.kind = match ins.kind {
InsKind::Jmp => InsKind::Nop,
InsKind::Nop => InsKind::Jmp,
InsKind::Acc => InsKind::Acc,
}
}
fn part2(input: &str) -> i32 {
let mut instrs = parse(input);
let mut swap_idx = 0;
loop {
swap(&mut instrs[swap_idx]);
let mut vm = Vm::new(&instrs);
match exec(&mut vm) {
ExecResult::InfiLoop => {}
ExecResult::Terminate => return vm.acc,
}
swap(&mut instrs[swap_idx]);
swap_idx += 1;
}
}
#[cfg(test)]
const TEST_INSTRS: &str = "nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6";
aoc::tests! {
fn part1:
TEST_INSTRS => 5;
in => 1859;
fn part2:
TEST_INSTRS => 8;
}
aoc::main!(part1, part2);
|
use crate::prelude::*;
#[repr(C)]
#[derive(Debug)]
pub struct VkClearRect {
pub VkRect: VkRect2D,
pub baseArrayLayer: u32,
pub layerCount: u32,
}
|
use crate::mtg;
use crate::structs;
use structs::Deck;
use structs::DeckPosition;
use std::fs::File;
use std::io::prelude::*;
use serde_json::json;
use std::process::Command;
use nalgebra::Point2;
fn write_decks_and_positions_file(deckpos: &Vec<DeckPosition>, alphabet: &Vec<String>){
//the one hot vector of the cards and the
let mut towritestruct: Vec<(Vec<f32>, (f32,f32))> = Vec::new();
for deck in deckpos{
let ohv = deck.deck.get_one_hot_vector(&alphabet);
let pos = deck.get_position();
towritestruct.push( (ohv, pos) );
}
let towrite = json!( towritestruct ).to_string();
let mut file = File::create("nnmajorization/decksandpositions.json").unwrap();
file.write_all( towrite.as_bytes() ).unwrap();
}
fn train_on_decks_and_posiitions_file(){
let output = Command::new("python3")
.current_dir("nnmajorization")
.args(&["train.py"])
.output()
//.spawn()
.expect("failed to execute process");
}
fn get_predictions(oldpos: &Vec<DeckPosition>) -> Vec<DeckPosition>{
//get predictions
let output = Command::new("python3")
.current_dir("nnmajorization")
.args(&["predict.py"])
.output()
//.spawn()
.expect("failed to execute process");
//println!("output of get predictions {:?}", output);
let contents = std::fs::read_to_string( "nnmajorization/predicted.json" ).expect("Something went wrong reading the file");
let predictedpositions: Vec<(f32,f32)> = serde_json::from_str(&contents).expect("JSON was not well-formatted");
let mut toreturn = Vec::new();
let mut id = 0;
for newpos in &predictedpositions{
let newpos = Point2::new(newpos.0, newpos.1);
toreturn.push( oldpos[id].clone_with_new_pos( newpos ) );
id +=1;
}
toreturn
}
//given two lists of deck positions, return the one that has a better score
pub fn get_better_positions(oldpos: &Vec<DeckPosition>, newpos: &Vec<DeckPosition>) -> Vec<DeckPosition>{
let mut toreturn = oldpos.clone();
use rand::Rng;
let mut rng = rand::thread_rng();
let mut id = 0;
for newdeckpos in newpos{
let mut toreturncopy = toreturn.clone();
//toreturncopy[id] = newdeckpos.deck.to_deck_position_with_random_initialization();
toreturncopy[id] = newdeckpos.clone();
let randx = (rng.gen::<f32>() - 0.5) * 0.05;
let randy = (rng.gen::<f32>() - 0.5) * 0.05;
toreturncopy[id].position.x += randx;
toreturncopy[id].position.y += randy;
//is toreturn improved by this change?
if DeckPosition::get_stress_score( &toreturncopy ) < DeckPosition::get_stress_score( &toreturn ){
toreturn = toreturncopy;
}
id +=1;
}
println!("stress score {:?}", DeckPosition::get_stress_score(&toreturn) );
return toreturn;
}
fn new_model() {
//get predictions
let output = Command::new("python3")
.current_dir("nnmajorization")
.args(&["newmodel.py"])
.output()
//.spawn()
.expect("failed to execute process");
println!("output {:?}", output);
}
pub fn nnmajorization(decks: Vec<Deck>) {
let mut deckpos = Vec::new();
for deck in decks{
deckpos.push( deck.to_deck_position_with_random_initialization() );
}
let standardalphabet = mtg::get_standard_alphabet();
let colormapping = mtg::get_colour_mapping();
new_model();
//write the deck contents and its position to file (1)
write_decks_and_positions_file(&deckpos, &standardalphabet);
for x in 0..1000{
let predictions = get_predictions(&deckpos);
println!("got predictions");
use crate::draw;
draw::draw_decks(&predictions, "pred", &colormapping);
draw::draw_decks(&deckpos, "realpos", &colormapping);
//get the list of deckpos that has a better score
deckpos = get_better_positions(&deckpos, &predictions);
println!("got the better position");
//write the decks and the better positions to file (1)
write_decks_and_positions_file(&deckpos, &standardalphabet);
println!("wrote decks to file again");
//train the decks on the file (1), the decks to position
train_on_decks_and_posiitions_file();
println!("trained decks on file");
}
}
|
use super::{Loc, Op, Reg, Span};
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Fence {
Sc,
Acq,
Rel,
AcqRel,
}
pub struct ExprVal {
pub span: Span,
pub guts: ExprGuts,
}
pub enum ExprGuts {
Unit,
Int {
value: i64,
},
Reg {
reg: Reg,
},
Loc {
loc: Loc,
},
Monop {
op: Op,
arg: Expr,
},
Binop {
op: Op,
lhs: Expr,
rhs: Expr,
},
Fence {
kind: Fence,
},
Read {
loc: Expr,
is_acquire: bool,
},
Write {
loc: Expr,
value: Expr,
is_release: bool,
},
Update {
loc: Expr,
reg: Expr,
value: Expr,
is_acquire: bool,
is_release: bool,
},
Cond {
cond: Expr,
if_true: Expr,
if_false: Expr,
},
LoopIf {
body: Expr,
},
Block {
stmts: Vec<Expr>,
value: Expr,
},
Assign {
reg: Expr,
value: Expr,
},
Return {
value: Expr,
},
Break {},
Ignore {},
}
pub type Expr = Box<ExprVal>;
pub fn expr_unit(span: Span) -> Expr {
Expr::new(ExprVal {
span,
guts: ExprGuts::Unit,
})
}
pub fn expr_int(span: Span, value: i64) -> Expr {
Expr::new(ExprVal {
span,
guts: ExprGuts::Int { value },
})
}
pub fn expr_reg(span: Span, reg: Reg) -> Expr {
Expr::new(ExprVal {
span,
guts: ExprGuts::Reg { reg },
})
}
pub fn expr_loc(span: Span, loc: Loc) -> Expr {
Expr::new(ExprVal {
span,
guts: ExprGuts::Loc { loc },
})
}
pub fn expr_monop(op_span: Span, op: Op, arg: Expr) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[op_span, arg.span]),
guts: ExprGuts::Monop { op, arg },
})
}
pub fn expr_binop(op_span: Span, op: Op, lhs: Expr, rhs: Expr) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[lhs.span, op_span, rhs.span]),
guts: ExprGuts::Binop { op, lhs, rhs },
})
}
pub fn expr_fence(kw_span: Span, kind: Fence) -> Expr {
Expr::new(ExprVal {
span: kw_span,
guts: ExprGuts::Fence { kind },
})
}
pub fn expr_read(op_span: Span, is_acquire: bool, loc: Expr) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[op_span, loc.span]),
guts: ExprGuts::Read { loc, is_acquire },
})
}
pub fn expr_write(kw_span: Span, loc: Expr, is_release: bool, value: Expr) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[kw_span, loc.span, value.span]),
guts: ExprGuts::Write {
loc,
is_release,
value,
},
})
}
pub fn expr_update(
kw_span: Span,
is_acquire: bool,
loc: Expr,
reg: Expr,
is_release: bool,
value: Expr,
) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[kw_span, loc.span, reg.span, value.span]),
guts: ExprGuts::Update {
loc,
is_acquire,
reg,
is_release,
value,
},
})
}
pub fn expr_cond(if_span: Span, cond: Expr, if_true: Expr, if_false: Expr) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[if_span, cond.span, if_true.span, if_false.span]),
guts: ExprGuts::Cond {
cond,
if_true,
if_false,
},
})
}
pub fn expr_loop_if(span: Span, body: Expr) -> Expr {
Expr::new(ExprVal {
span,
guts: ExprGuts::LoopIf { body },
})
}
pub fn expr_assign(eq_span: Span, reg: Expr, value: Expr) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[reg.span, eq_span, value.span]),
guts: ExprGuts::Assign { reg, value },
})
}
pub fn expr_block(lbrace: usize, rbrace: usize, stmts: Vec<Expr>, value: Expr) -> Expr {
Expr::new(ExprVal {
span: Span(lbrace, rbrace),
guts: ExprGuts::Block { stmts, value },
})
}
pub fn expr_return(return_span: Span, value: Expr) -> Expr {
Expr::new(ExprVal {
span: Span::union(&[return_span, value.span]),
guts: ExprGuts::Return { value },
})
}
pub fn expr_break(span: Span) -> Expr {
Expr::new(ExprVal {
span,
guts: ExprGuts::Break {},
})
}
pub fn expr_ignore(span: Span) -> Expr {
Expr::new(ExprVal {
span,
guts: ExprGuts::Ignore {},
})
}
|
use std::collections::HashMap;
use std::fs::create_dir_all;
use std::fs::File;
use std::path::PathBuf;
use std::cell::RefCell;
use anyhow::Result;
use structopt::StructOpt;
/// This is a program to
#[derive(Debug, StructOpt)]
#[structopt(rename_all = "kebab-case")]
struct Opt {
/// Suffix for output filenames.
#[structopt(short, long, default_value = "csv")]
suffix: String,
#[structopt(short, long, default_value = ",")]
delimiter: u8,
#[structopt(short, long)]
has_headers: bool,
/// The CSV file to extract data from. If the filename is '-' then the stdin will be read.
#[structopt(parse(from_os_str))]
raw: PathBuf,
/// Index of the column to use for finding the name of the file to write to. This is 0 based,
/// so the first
column_index: usize,
/// Directory to output into. If it does not exist, it will be created.
#[structopt(parse(from_os_str))]
output: PathBuf,
}
fn main() -> Result<()> {
let opt = Opt::from_args();
create_dir_all(&opt.output)?;
let input = rnc_utils::buf_reader(&opt.raw)?;
let mut reader = csv::ReaderBuilder::new()
.delimiter(opt.delimiter)
.has_headers(opt.has_headers)
.from_reader(input);
let mut mapping: HashMap<String, RefCell<csv::Writer<File>>> = HashMap::new();
for record in reader.records() {
let record = record?;
let value = &record[opt.column_index];
if !mapping.contains_key(value) {
let mut path = PathBuf::from(&opt.output);
path.push(value);
path.set_extension(&opt.suffix);
let writer = csv::Writer::from_writer(File::create(path)?);
mapping.insert(value.to_string(), RefCell::new(writer));
}
let mut writer = mapping[value].borrow_mut();
writer.write_record(&record)?;
}
Ok(())
}
|
#![allow(non_snake_case)]
use chua::upload_blocking;
use jni::objects::{JClass, JString};
use jni::sys::jint;
use jni::JNIEnv;
const OK: i32 = 0;
const NULL: i32 = 1;
const INVALID: i32 = 2;
const UPLOAD: i32 = 3;
#[no_mangle]
pub extern "system" fn Java_com_live2o3_chua_Chua_upload(
env: JNIEnv,
_class: JClass,
url: JString,
path: JString,
chunk_size: jint,
parallel: jint,
) -> i32 {
#[cfg(target_os = "android")]
init_android_log();
if url.is_null() || path.is_null() {
return NULL;
}
if chunk_size < 0 || parallel < 0 {
return INVALID;
}
let url: String = match env.get_string(url) {
Ok(s) => s.into(),
Err(_) => return INVALID,
};
let path: String = match env.get_string(path) {
Ok(s) => s.into(),
Err(_) => return INVALID,
};
match upload_blocking(&url, path, chunk_size as usize, parallel as usize) {
Ok(()) => OK,
Err(e) => {
#[cfg(target_os = "android")]
log::error!("Chua: {}", e);
UPLOAD
}
}
}
#[cfg(target_os = "android")]
fn init_android_log() {
use android_logger::{Config, FilterBuilder};
use log::Level;
android_logger::init_once(
Config::default()
.with_min_level(Level::Trace) // limit log level
.with_tag("mytag") // logs will show under mytag tag
.with_filter(
// configure messages for specific crate
FilterBuilder::new()
.parse("debug,hello::crate=error")
.build(),
),
);
}
|
fn read_line() -> String {
let mut buf = String::new();
std::io::stdin().read_line(&mut buf).expect("failed to readline");
buf
}
fn create_num_vec() -> Vec<i64> {
let buf = read_line();
let iter = buf.split_whitespace().map(|x| x.parse().expect("unable to parse"));
let num_vec : Vec<i64> = iter.collect();
num_vec
}
fn count_num(int_vec:Vec<i64>) -> (i64,i64,i64) {
let (mut num_positive, mut num_negative, mut num_zero) = (0i64, 0i64, 0i64);
for &num in int_vec.iter() {
if num == 0 { num_zero += 1; }
else if num > 0 { num_positive += 1; }
else { num_negative += 1; }
}
(num_positive, num_negative, num_zero)
}
fn calculate_fraction(numerator:i64, denominator:i64) -> f64 {
(numerator as f64)/(denominator as f64)
}
fn main() {
let array_size : String = read_line();
let int_vec : Vec<i64> = create_num_vec();
let array_size : i64 = int_vec.len() as i64;
let (num_positive, num_negative, num_zero) = count_num(int_vec);
println!("{} {} {}", calculate_fraction(num_positive,array_size), calculate_fraction(num_negative, array_size), calculate_fraction(num_zero, array_size));
} |
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[cfg(feature = "Win32_System_WinRT_Graphics_Capture")]
pub mod Capture;
#[cfg(feature = "Win32_System_WinRT_Graphics_Direct2D")]
pub mod Direct2D;
#[cfg(feature = "Win32_System_WinRT_Graphics_Imaging")]
pub mod Imaging;
|
//! Implementation of command line option for running server
use std::sync::Arc;
use clap_blocks::run_config::RunConfig;
use ioxd_common::server_type::{CommonServerState, CommonServerStateError};
use ioxd_common::Service;
use ioxd_test::{TestAction, TestServerType};
use thiserror::Error;
use crate::process_info::setup_metric_registry;
use super::main;
#[derive(Debug, Error)]
pub enum Error {
#[error("Run: {0}")]
Run(#[from] main::Error),
#[error("Invalid config: {0}")]
InvalidConfig(#[from] CommonServerStateError),
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, clap::Parser)]
#[clap(
name = "run",
about = "Runs in test mode",
long_about = "Run the IOx test server.\n\nThe configuration options below can be \
set either with the command line flags or with the specified environment \
variable. If there is a file named '.env' in the current working directory, \
it is sourced before loading the configuration.
Configuration is loaded from the following sources (highest precedence first):
- command line arguments
- user set environment variables
- .env file contents
- pre-configured default values"
)]
pub struct Config {
#[clap(flatten)]
pub(crate) run_config: RunConfig,
/// Test action
#[clap(
value_enum,
long = "test-action",
env = "IOX_TEST_ACTION",
default_value = "None",
ignore_case = true,
action
)]
test_action: TestAction,
}
pub async fn command(config: Config) -> Result<()> {
let common_state = CommonServerState::from_config(config.run_config.clone())?;
let metrics = setup_metric_registry();
let server_type = Arc::new(TestServerType::new(
Arc::clone(&metrics),
common_state.trace_collector(),
config.test_action,
));
let services = vec![Service::create(server_type, common_state.run_config())];
Ok(main::main(common_state, services, metrics).await?)
}
|
// `without_boolean_value_errors_badarg` in unit tests
test_stdout!(with_boolean_returns_original_value_false, "false\n");
test_stdout!(
with_true_value_then_boolean_value_returns_old_value_true,
"false\ntrue\n"
);
test_stdout!(
with_true_value_with_linked_and_does_not_exit_when_linked_process_exits_normal,
"{trap_exit, true}\n{parent, alive, true}\n{child, exited, normal}\n"
);
test_stdout!(
with_true_value_with_linked_receive_exit_message_and_does_not_exit_when_linked_process_does_not_exit_normal,
"{trap_exit, true}\n{parent, alive, true}\n{child, exited, abnormal}\n{parent, sees, child, alive, false}\n"
);
test_stdout!(
with_true_value_then_false_value_exits_when_linked_process_does_not_exit_normal,
"{trap_exit, true}\n{trap_exit, false}\n{child, exited, abnormal}\n{parent, exited, abnormal}\n"
);
|
extern crate embed_resource;
fn main() {
embed_resource::compile("embed_resources.rc");
}
|
// This file is part of Substrate.
// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! Support code for the runtime.
#![cfg_attr(not(feature = "std"), no_std)]
/// Export ourself as `frame_support` to make tests happy.
extern crate self as frame_support;
#[doc(hidden)]
pub use sp_tracing;
#[cfg(feature = "std")]
pub use serde;
pub use sp_core::Void;
#[doc(hidden)]
pub use sp_std;
#[doc(hidden)]
pub use codec;
#[cfg(feature = "std")]
#[doc(hidden)]
pub use once_cell;
#[doc(hidden)]
pub use paste;
#[cfg(feature = "std")]
#[doc(hidden)]
pub use sp_state_machine::BasicExternalities;
#[doc(hidden)]
pub use sp_io::{storage::root as storage_root, self};
#[doc(hidden)]
pub use sp_runtime::RuntimeDebug;
#[doc(hidden)]
pub use log;
#[macro_use]
mod origin;
#[macro_use]
pub mod dispatch;
pub mod storage;
mod hash;
#[macro_use]
pub mod event;
#[macro_use]
pub mod metadata;
#[macro_use]
pub mod genesis_config;
#[macro_use]
pub mod inherent;
#[macro_use]
pub mod unsigned;
#[macro_use]
pub mod error;
pub mod traits;
pub mod weights;
pub mod instances;
pub use self::hash::{
Twox256, Twox128, Blake2_256, Blake2_128, Identity, Twox64Concat, Blake2_128Concat, Hashable,
StorageHasher, ReversibleStorageHasher
};
pub use self::storage::{
StorageValue, StorageMap, StorageDoubleMap, StorageNMap, StoragePrefixedMap,
IterableStorageMap, IterableStorageDoubleMap, IterableStorageNMap, migration,
bounded_vec::{BoundedVec, BoundedSlice}, weak_bounded_vec::WeakBoundedVec,
};
pub use self::dispatch::{Parameter, Callable};
pub use sp_runtime::{self, ConsensusEngineId, print, traits::Printable};
use codec::{Encode, Decode};
use sp_runtime::TypeId;
/// A unified log target for support operations.
pub const LOG_TARGET: &'static str = "runtime::frame-support";
/// A type that cannot be instantiated.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Never {}
/// A pallet identifier. These are per pallet and should be stored in a registry somewhere.
#[derive(Clone, Copy, Eq, PartialEq, Encode, Decode)]
pub struct PalletId(pub [u8; 8]);
impl TypeId for PalletId {
const TYPE_ID: [u8; 4] = *b"modl";
}
/// Generate a new type alias for [`storage::types::StorageValue`],
/// [`storage::types::StorageMap`] and [`storage::types::StorageDoubleMap`].
///
/// Useful for creating a *storage-like* struct for test and migrations.
///
///```
/// # use frame_support::generate_storage_alias;
/// use frame_support::codec;
/// use frame_support::Twox64Concat;
/// // generate a storage value with type u32.
/// generate_storage_alias!(Prefix, StorageName => Value<u32>);
///
/// // generate a double map from `(u32, u32)` (with hasher `Twox64Concat`) to `Vec<u8>`
/// generate_storage_alias!(
/// OtherPrefix, OtherStorageName => DoubleMap<
/// (u32, u32),
/// (u32, u32),
/// Vec<u8>
/// >
/// );
///
/// // generate a map from `Config::AccountId` (with hasher `Twox64Concat`) to `Vec<u8>`
/// trait Config { type AccountId: codec::FullCodec; }
/// generate_storage_alias!(
/// Prefix, GenericStorage<T: Config> => Map<(Twox64Concat, T::AccountId), Vec<u8>>
/// );
/// # fn main() {}
/// ```
#[macro_export]
macro_rules! generate_storage_alias {
// without generic for $name.
($pallet:ident, $name:ident => Map<($key:ty, $hasher:ty), $value:ty>) => {
$crate::paste::paste! {
$crate::generate_storage_alias!(@GENERATE_INSTANCE_STRUCT $pallet, $name);
type $name = $crate::storage::types::StorageMap<
[<$name Instance>],
$hasher,
$key,
$value,
>;
}
};
($pallet:ident, $name:ident => DoubleMap<($key1:ty, $hasher1:ty), ($key2:ty, $hasher2:ty), $value:ty>) => {
$crate::paste::paste! {
$crate::generate_storage_alias!(@GENERATE_INSTANCE_STRUCT $pallet, $name);
type $name = $crate::storage::types::StorageDoubleMap<
[<$name Instance>],
$hasher1,
$key1,
$hasher2,
$key2,
$value,
>;
}
};
($pallet:ident, $name:ident => Value<$value:ty>) => {
$crate::paste::paste! {
$crate::generate_storage_alias!(@GENERATE_INSTANCE_STRUCT $pallet, $name);
type $name = $crate::storage::types::StorageValue<
[<$name Instance>],
$value,
>;
}
};
// with generic for $name.
($pallet:ident, $name:ident<$t:ident : $bounds:tt> => Map<($key:ty, $hasher:ty), $value:ty>) => {
$crate::paste::paste! {
$crate::generate_storage_alias!(@GENERATE_INSTANCE_STRUCT $pallet, $name);
#[allow(type_alias_bounds)]
type $name<$t : $bounds> = $crate::storage::types::StorageMap<
[<$name Instance>],
$key,
$hasher,
$value,
>;
}
};
(
$pallet:ident,
$name:ident<$t:ident : $bounds:tt>
=> DoubleMap<($key1:ty, $hasher1:ty), ($key2:ty, $hasher2:ty), $value:ty>) => {
$crate::paste::paste! {
$crate::generate_storage_alias!(@GENERATE_INSTANCE_STRUCT $pallet, $name);
#[allow(type_alias_bounds)]
type $name<$t : $bounds> = $crate::storage::types::StorageDoubleMap<
[<$name Instance>],
$key1,
$hasher1,
$key2,
$hasher2,
$value,
>;
}
};
($pallet:ident, $name:ident<$t:ident : $bounds:tt> => Value<$value:ty>) => {
$crate::paste::paste! {
$crate::generate_storage_alias!(@GENERATE_INSTANCE_STRUCT $pallet, $name);
#[allow(type_alias_bounds)]
type $name<$t : $bounds> = $crate::storage::types::StorageValue<
[<$name Instance>],
$value,
$crate::storage::types::ValueQuery,
>;
}
};
// helper used in all arms.
(@GENERATE_INSTANCE_STRUCT $pallet:ident, $name:ident) => {
$crate::paste::paste! {
struct [<$name Instance>];
impl $crate::traits::StorageInstance for [<$name Instance>] {
fn pallet_prefix() -> &'static str { stringify!($pallet) }
const STORAGE_PREFIX: &'static str = stringify!($name);
}
}
};
}
/// Create new implementations of the [`Get`](crate::traits::Get) trait.
///
/// The so-called parameter type can be created in four different ways:
///
/// - Using `const` to create a parameter type that provides a `const` getter. It is required that
/// the `value` is const.
///
/// - Declare the parameter type without `const` to have more freedom when creating the value.
///
/// - Using `storage` to create a storage parameter type. This type is special as it tries to load
/// the value from the storage under a fixed key. If the value could not be found in the storage,
/// the given default value will be returned. It is required that the value implements
/// [`Encode`](codec::Encode) and [`Decode`](codec::Decode). The key for looking up the value in
/// the storage is built using the following formula:
///
/// `twox_128(":" ++ NAME ++ ":")` where `NAME` is the name that is passed as type name.
///
/// - Using `static` to create a static parameter type. Its value is
/// being provided by a static variable with the equivalent name in `UPPER_SNAKE_CASE`. An
/// additional `set` function is provided in this case to alter the static variable.
/// **This is intended for testing ONLY and is ONLY available when `std` is enabled.**
///
/// # Examples
///
/// ```
/// # use frame_support::traits::Get;
/// # use frame_support::parameter_types;
/// // This function cannot be used in a const context.
/// fn non_const_expression() -> u64 { 99 }
///
/// const FIXED_VALUE: u64 = 10;
/// parameter_types! {
/// pub const Argument: u64 = 42 + FIXED_VALUE;
/// /// Visibility of the type is optional
/// OtherArgument: u64 = non_const_expression();
/// pub storage StorageArgument: u64 = 5;
/// pub static StaticArgument: u32 = 7;
/// }
///
/// trait Config {
/// type Parameter: Get<u64>;
/// type OtherParameter: Get<u64>;
/// type StorageParameter: Get<u64>;
/// type StaticParameter: Get<u32>;
/// }
///
/// struct Runtime;
/// impl Config for Runtime {
/// type Parameter = Argument;
/// type OtherParameter = OtherArgument;
/// type StorageParameter = StorageArgument;
/// type StaticParameter = StaticArgument;
/// }
///
/// // In testing, `StaticArgument` can be altered later: `StaticArgument::set(8)`.
/// ```
///
/// # Invalid example:
///
/// ```compile_fail
/// # use frame_support::traits::Get;
/// # use frame_support::parameter_types;
/// // This function cannot be used in a const context.
/// fn non_const_expression() -> u64 { 99 }
///
/// parameter_types! {
/// pub const Argument: u64 = non_const_expression();
/// }
/// ```
#[macro_export]
macro_rules! parameter_types {
(
$( #[ $attr:meta ] )*
$vis:vis const $name:ident: $type:ty = $value:expr;
$( $rest:tt )*
) => (
$( #[ $attr ] )*
$vis struct $name;
$crate::parameter_types!(IMPL_CONST $name , $type , $value);
$crate::parameter_types!( $( $rest )* );
);
(
$( #[ $attr:meta ] )*
$vis:vis $name:ident: $type:ty = $value:expr;
$( $rest:tt )*
) => (
$( #[ $attr ] )*
$vis struct $name;
$crate::parameter_types!(IMPL $name, $type, $value);
$crate::parameter_types!( $( $rest )* );
);
(
$( #[ $attr:meta ] )*
$vis:vis storage $name:ident: $type:ty = $value:expr;
$( $rest:tt )*
) => (
$( #[ $attr ] )*
$vis struct $name;
$crate::parameter_types!(IMPL_STORAGE $name, $type, $value);
$crate::parameter_types!( $( $rest )* );
);
() => ();
(IMPL_CONST $name:ident, $type:ty, $value:expr) => {
impl $name {
/// Returns the value of this parameter type.
#[allow(unused)]
pub const fn get() -> $type {
$value
}
}
impl<I: From<$type>> $crate::traits::Get<I> for $name {
fn get() -> I {
I::from($value)
}
}
};
(IMPL $name:ident, $type:ty, $value:expr) => {
impl $name {
/// Returns the value of this parameter type.
#[allow(unused)]
pub fn get() -> $type {
$value
}
}
impl<I: From<$type>> $crate::traits::Get<I> for $name {
fn get() -> I {
I::from($value)
}
}
};
(IMPL_STORAGE $name:ident, $type:ty, $value:expr) => {
impl $name {
/// Returns the key for this parameter type.
#[allow(unused)]
pub fn key() -> [u8; 16] {
$crate::sp_io::hashing::twox_128(
concat!(":", stringify!($name), ":").as_bytes()
)
}
/// Set the value of this parameter type in the storage.
///
/// This needs to be executed in an externalities provided
/// environment.
#[allow(unused)]
pub fn set(value: &$type) {
$crate::storage::unhashed::put(&Self::key(), value);
}
/// Returns the value of this parameter type.
///
/// This needs to be executed in an externalities provided
/// environment.
#[allow(unused)]
pub fn get() -> $type {
$crate::storage::unhashed::get(&Self::key()).unwrap_or_else(|| $value)
}
}
impl<I: From<$type>> $crate::traits::Get<I> for $name {
fn get() -> I {
I::from(Self::get())
}
}
};
(
$( #[ $attr:meta ] )*
$vis:vis static $name:ident: $type:ty = $value:expr;
$( $rest:tt )*
) => (
$crate::parameter_types_impl_thread_local!(
$( #[ $attr ] )*
$vis static $name: $type = $value;
);
$crate::parameter_types!( $( $rest )* );
);
}
#[cfg(not(feature = "std"))]
#[macro_export]
macro_rules! parameter_types_impl_thread_local {
( $( $any:tt )* ) => {
compile_error!("static parameter types is only available in std and for testing.");
};
}
#[cfg(feature = "std")]
#[macro_export]
macro_rules! parameter_types_impl_thread_local {
(
$(
$( #[ $attr:meta ] )*
$vis:vis static $name:ident: $type:ty = $value:expr;
)*
) => {
$crate::parameter_types_impl_thread_local!(
IMPL_THREAD_LOCAL $( $vis, $name, $type, $value, )*
);
$crate::paste::item! {
$crate::parameter_types!(
$(
$( #[ $attr ] )*
$vis $name: $type = [<$name:snake:upper>].with(|v| v.borrow().clone());
)*
);
$(
impl $name {
/// Set the internal value.
pub fn set(t: $type) {
[<$name:snake:upper>].with(|v| *v.borrow_mut() = t);
}
}
)*
}
};
(IMPL_THREAD_LOCAL $( $vis:vis, $name:ident, $type:ty, $value:expr, )* ) => {
$crate::paste::item! {
thread_local! {
$(
pub static [<$name:snake:upper>]: std::cell::RefCell<$type> =
std::cell::RefCell::new($value);
)*
}
}
};
}
/// Macro for easily creating a new implementation of both the `Get` and `Contains` traits. Use
/// exactly as with `parameter_types`, only the type must be `Ord`.
#[macro_export]
macro_rules! ord_parameter_types {
(
$( #[ $attr:meta ] )*
$vis:vis const $name:ident: $type:ty = $value:expr;
$( $rest:tt )*
) => (
$( #[ $attr ] )*
$vis struct $name;
$crate::parameter_types!{IMPL $name , $type , $value}
$crate::ord_parameter_types!{IMPL $name , $type , $value}
$crate::ord_parameter_types!{ $( $rest )* }
);
() => ();
(IMPL $name:ident , $type:ty , $value:expr) => {
impl $crate::traits::SortedMembers<$type> for $name {
fn contains(t: &$type) -> bool { &$value == t }
fn sorted_members() -> $crate::sp_std::prelude::Vec<$type> { vec![$value] }
fn count() -> usize { 1 }
#[cfg(feature = "runtime-benchmarks")]
fn add(_: &$type) {}
}
impl $crate::traits::Contains<$type> for $name {
fn contains(t: &$type) -> bool { &$value == t }
}
}
}
/// Print out a formatted message.
///
/// # Example
///
/// ```
/// frame_support::runtime_print!("my value is {}", 3);
/// ```
#[macro_export]
macro_rules! runtime_print {
($($arg:tt)+) => {
{
use core::fmt::Write;
let mut w = $crate::sp_std::Writer::default();
let _ = core::write!(&mut w, $($arg)+);
$crate::sp_io::misc::print_utf8(&w.inner())
}
}
}
/// Print out the debuggable type.
pub fn debug(data: &impl sp_std::fmt::Debug) {
runtime_print!("{:?}", data);
}
#[doc(inline)]
pub use frame_support_procedural::{
decl_storage, construct_runtime, transactional, RuntimeDebugNoBound
};
/// Derive [`Clone`] but do not bound any generic.
///
/// This is useful for type generic over runtime:
/// ```
/// # use frame_support::CloneNoBound;
/// trait Config {
/// type C: Clone;
/// }
///
/// // Foo implements [`Clone`] because `C` bounds [`Clone`].
/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Clone`].
/// #[derive(CloneNoBound)]
/// struct Foo<T: Config> {
/// c: T::C,
/// }
/// ```
pub use frame_support_procedural::CloneNoBound;
/// Derive [`Eq`] but do not bound any generic.
///
/// This is useful for type generic over runtime:
/// ```
/// # use frame_support::{EqNoBound, PartialEqNoBound};
/// trait Config {
/// type C: Eq;
/// }
///
/// // Foo implements [`Eq`] because `C` bounds [`Eq`].
/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Eq`].
/// #[derive(PartialEqNoBound, EqNoBound)]
/// struct Foo<T: Config> {
/// c: T::C,
/// }
/// ```
pub use frame_support_procedural::EqNoBound;
/// Derive [`PartialEq`] but do not bound any generic.
///
/// This is useful for type generic over runtime:
/// ```
/// # use frame_support::PartialEqNoBound;
/// trait Config {
/// type C: PartialEq;
/// }
///
/// // Foo implements [`PartialEq`] because `C` bounds [`PartialEq`].
/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`PartialEq`].
/// #[derive(PartialEqNoBound)]
/// struct Foo<T: Config> {
/// c: T::C,
/// }
/// ```
pub use frame_support_procedural::PartialEqNoBound;
/// Derive [`Debug`] but do not bound any generic.
///
/// This is useful for type generic over runtime:
/// ```
/// # use frame_support::DebugNoBound;
/// # use core::fmt::Debug;
/// trait Config {
/// type C: Debug;
/// }
///
/// // Foo implements [`Debug`] because `C` bounds [`Debug`].
/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Debug`].
/// #[derive(DebugNoBound)]
/// struct Foo<T: Config> {
/// c: T::C,
/// }
/// ```
pub use frame_support_procedural::DebugNoBound;
/// Derive [`Default`] but do not bound any generic.
///
/// This is useful for type generic over runtime:
/// ```
/// # use frame_support::DefaultNoBound;
/// # use core::default::Default;
/// trait Config {
/// type C: Default;
/// }
///
/// // Foo implements [`Default`] because `C` bounds [`Default`].
/// // Otherwise compilation will fail with an output telling `c` doesn't implement [`Default`].
/// #[derive(DefaultNoBound)]
/// struct Foo<T: Config> {
/// c: T::C,
/// }
/// ```
pub use frame_support_procedural::DefaultNoBound;
/// Assert the annotated function is executed within a storage transaction.
///
/// The assertion is enabled for native execution and when `debug_assertions` are enabled.
///
/// # Example
///
/// ```
/// # use frame_support::{
/// # require_transactional, transactional, dispatch::DispatchResult
/// # };
///
/// #[require_transactional]
/// fn update_all(value: u32) -> DispatchResult {
/// // Update multiple storages.
/// // Return `Err` to indicate should revert.
/// Ok(())
/// }
///
/// #[transactional]
/// fn safe_update(value: u32) -> DispatchResult {
/// // This is safe
/// update_all(value)
/// }
///
/// fn unsafe_update(value: u32) -> DispatchResult {
/// // this may panic if unsafe_update is not called within a storage transaction
/// update_all(value)
/// }
/// ```
pub use frame_support_procedural::require_transactional;
/// Convert the current crate version into a [`PalletVersion`](crate::traits::PalletVersion).
///
/// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and
/// `CARGO_PKG_VERSION_PATCH` environment variables to fetch the crate version.
/// This means that the [`PalletVersion`](crate::traits::PalletVersion)
/// object will correspond to the version of the crate the macro is called in!
///
/// # Example
///
/// ```
/// # use frame_support::{traits::PalletVersion, crate_to_pallet_version};
/// const Version: PalletVersion = crate_to_pallet_version!();
/// ```
pub use frame_support_procedural::crate_to_pallet_version;
/// Return Err of the expression: `return Err($expression);`.
///
/// Used as `fail!(expression)`.
#[macro_export]
macro_rules! fail {
( $y:expr ) => {{
return Err($y.into());
}}
}
/// Evaluate `$x:expr` and if not true return `Err($y:expr)`.
///
/// Used as `ensure!(expression_to_ensure, expression_to_return_on_false)`.
#[macro_export]
macro_rules! ensure {
( $x:expr, $y:expr $(,)? ) => {{
if !$x {
$crate::fail!($y);
}
}}
}
/// Evaluate an expression, assert it returns an expected `Err` value and that
/// runtime storage has not been mutated (i.e. expression is a no-operation).
///
/// Used as `assert_noop(expression_to_assert, expected_error_expression)`.
#[macro_export]
macro_rules! assert_noop {
(
$x:expr,
$y:expr $(,)?
) => {
let h = $crate::storage_root();
$crate::assert_err!($x, $y);
assert_eq!(h, $crate::storage_root());
}
}
/// Evaluate any expression and assert that runtime storage has not been mutated
/// (i.e. expression is a storage no-operation).
///
/// Used as `assert_storage_noop(expression_to_assert)`.
#[macro_export]
macro_rules! assert_storage_noop {
(
$x:expr
) => {
let h = $crate::storage_root();
$x;
assert_eq!(h, $crate::storage_root());
}
}
/// Assert an expression returns an error specified.
///
/// Used as `assert_err!(expression_to_assert, expected_error_expression)`
#[macro_export]
macro_rules! assert_err {
( $x:expr , $y:expr $(,)? ) => {
assert_eq!($x, Err($y.into()));
}
}
/// Assert an expression returns an error specified.
///
/// This can be used on`DispatchResultWithPostInfo` when the post info should
/// be ignored.
#[macro_export]
macro_rules! assert_err_ignore_postinfo {
( $x:expr , $y:expr $(,)? ) => {
$crate::assert_err!($x.map(|_| ()).map_err(|e| e.error), $y);
}
}
/// Assert an expression returns error with the given weight.
#[macro_export]
macro_rules! assert_err_with_weight {
($call:expr, $err:expr, $weight:expr $(,)? ) => {
if let Err(dispatch_err_with_post) = $call {
$crate::assert_err!($call.map(|_| ()).map_err(|e| e.error), $err);
assert_eq!(dispatch_err_with_post.post_info.actual_weight, $weight.into());
} else {
panic!("expected Err(_), got Ok(_).")
}
}
}
/// Panic if an expression doesn't evaluate to `Ok`.
///
/// Used as `assert_ok!(expression_to_assert, expected_ok_expression)`,
/// or `assert_ok!(expression_to_assert)` which would assert against `Ok(())`.
#[macro_export]
macro_rules! assert_ok {
( $x:expr $(,)? ) => {
let is = $x;
match is {
Ok(_) => (),
_ => assert!(false, "Expected Ok(_). Got {:#?}", is),
}
};
( $x:expr, $y:expr $(,)? ) => {
assert_eq!($x, Ok($y));
}
}
#[cfg(feature = "std")]
#[doc(hidden)]
pub use serde::{Serialize, Deserialize};
#[cfg(test)]
pub mod tests {
use super::*;
use codec::{Codec, EncodeLike};
use frame_metadata::{
DecodeDifferent, StorageEntryMetadata, StorageMetadata, StorageEntryType,
StorageEntryModifier, DefaultByteGetter, StorageHasher,
};
use sp_std::{marker::PhantomData, result};
use sp_io::TestExternalities;
/// A PalletInfo implementation which just panics.
pub struct PanicPalletInfo;
impl crate::traits::PalletInfo for PanicPalletInfo {
fn index<P: 'static>() -> Option<usize> {
unimplemented!("PanicPalletInfo mustn't be triggered by tests");
}
fn name<P: 'static>() -> Option<&'static str> {
unimplemented!("PanicPalletInfo mustn't be triggered by tests");
}
}
pub trait Config: 'static {
type BlockNumber: Codec + EncodeLike + Default;
type Origin;
type PalletInfo: crate::traits::PalletInfo;
type DbWeight: crate::traits::Get<crate::weights::RuntimeDbWeight>;
}
mod module {
#![allow(dead_code)]
use super::Config;
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin, system=self {}
}
}
use self::module::Module;
decl_storage! {
trait Store for Module<T: Config> as Test {
pub Data get(fn data) build(|_| vec![(15u32, 42u64)]):
map hasher(twox_64_concat) u32 => u64;
pub OptionLinkedMap: map hasher(blake2_128_concat) u32 => Option<u32>;
pub GenericData get(fn generic_data):
map hasher(identity) T::BlockNumber => T::BlockNumber;
pub GenericData2 get(fn generic_data2):
map hasher(blake2_128_concat) T::BlockNumber => Option<T::BlockNumber>;
pub DataDM config(test_config) build(|_| vec![(15u32, 16u32, 42u64)]):
double_map hasher(twox_64_concat) u32, hasher(blake2_128_concat) u32 => u64;
pub GenericDataDM:
double_map hasher(blake2_128_concat) T::BlockNumber, hasher(identity) T::BlockNumber
=> T::BlockNumber;
pub GenericData2DM:
double_map hasher(blake2_128_concat) T::BlockNumber, hasher(twox_64_concat) T::BlockNumber
=> Option<T::BlockNumber>;
pub AppendableDM:
double_map hasher(blake2_128_concat) u32, hasher(blake2_128_concat) T::BlockNumber => Vec<u32>;
}
}
struct Test;
impl Config for Test {
type BlockNumber = u32;
type Origin = u32;
type PalletInfo = PanicPalletInfo;
type DbWeight = ();
}
fn new_test_ext() -> TestExternalities {
GenesisConfig::default().build_storage().unwrap().into()
}
type Map = Data;
trait Sorted { fn sorted(self) -> Self; }
impl<T: Ord> Sorted for Vec<T> {
fn sorted(mut self) -> Self {
self.sort();
self
}
}
#[test]
fn map_issue_3318() {
new_test_ext().execute_with(|| {
OptionLinkedMap::insert(1, 1);
assert_eq!(OptionLinkedMap::get(1), Some(1));
OptionLinkedMap::insert(1, 2);
assert_eq!(OptionLinkedMap::get(1), Some(2));
});
}
#[test]
fn map_swap_works() {
new_test_ext().execute_with(|| {
OptionLinkedMap::insert(0, 0);
OptionLinkedMap::insert(1, 1);
OptionLinkedMap::insert(2, 2);
OptionLinkedMap::insert(3, 3);
let collect = || OptionLinkedMap::iter().collect::<Vec<_>>().sorted();
assert_eq!(collect(), vec![(0, 0), (1, 1), (2, 2), (3, 3)]);
// Two existing
OptionLinkedMap::swap(1, 2);
assert_eq!(collect(), vec![(0, 0), (1, 2), (2, 1), (3, 3)]);
// Back to normal
OptionLinkedMap::swap(2, 1);
assert_eq!(collect(), vec![(0, 0), (1, 1), (2, 2), (3, 3)]);
// Left existing
OptionLinkedMap::swap(2, 5);
assert_eq!(collect(), vec![(0, 0), (1, 1), (3, 3), (5, 2)]);
// Right existing
OptionLinkedMap::swap(5, 2);
assert_eq!(collect(), vec![(0, 0), (1, 1), (2, 2), (3, 3)]);
});
}
#[test]
fn double_map_swap_works() {
new_test_ext().execute_with(|| {
DataDM::insert(0, 1, 1);
DataDM::insert(1, 0, 2);
DataDM::insert(1, 1, 3);
let get_all = || vec![
DataDM::get(0, 1),
DataDM::get(1, 0),
DataDM::get(1, 1),
DataDM::get(2, 0),
DataDM::get(2, 1),
];
assert_eq!(get_all(), vec![1, 2, 3, 0, 0]);
// Two existing
DataDM::swap(0, 1, 1, 0);
assert_eq!(get_all(), vec![2, 1, 3, 0, 0]);
// Left existing
DataDM::swap(1, 0, 2, 0);
assert_eq!(get_all(), vec![2, 0, 3, 1, 0]);
// Right existing
DataDM::swap(2, 1, 1, 1);
assert_eq!(get_all(), vec![2, 0, 0, 1, 3]);
});
}
#[test]
fn map_basic_insert_remove_should_work() {
new_test_ext().execute_with(|| {
// initialized during genesis
assert_eq!(Map::get(&15u32), 42u64);
// get / insert / take
let key = 17u32;
assert_eq!(Map::get(&key), 0u64);
Map::insert(key, 4u64);
assert_eq!(Map::get(&key), 4u64);
assert_eq!(Map::take(&key), 4u64);
assert_eq!(Map::get(&key), 0u64);
// mutate
Map::mutate(&key, |val| {
*val = 15;
});
assert_eq!(Map::get(&key), 15u64);
// remove
Map::remove(&key);
assert_eq!(Map::get(&key), 0u64);
});
}
#[test]
fn map_iteration_should_work() {
new_test_ext().execute_with(|| {
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(15, 42)]);
// insert / remove
let key = 17u32;
Map::insert(key, 4u64);
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(15, 42), (key, 4)]);
assert_eq!(Map::take(&15), 42u64);
assert_eq!(Map::take(&key), 4u64);
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![]);
// Add couple of more elements
Map::insert(key, 42u64);
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(key, 42)]);
Map::insert(key + 1, 43u64);
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(key, 42), (key + 1, 43)]);
// mutate
let key = key + 2;
Map::mutate(&key, |val| {
*val = 15;
});
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(key - 2, 42), (key - 1, 43), (key, 15)]);
Map::mutate(&key, |val| {
*val = 17;
});
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(key - 2, 42), (key - 1, 43), (key, 17)]);
// remove first
Map::remove(&key);
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(key - 2, 42), (key - 1, 43)]);
// remove last from the list
Map::remove(&(key - 2));
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![(key - 1, 43)]);
// remove the last element
Map::remove(&(key - 1));
assert_eq!(Map::iter().collect::<Vec<_>>().sorted(), vec![]);
});
}
#[test]
fn double_map_basic_insert_remove_remove_prefix_should_work() {
new_test_ext().execute_with(|| {
type DoubleMap = DataDM;
// initialized during genesis
assert_eq!(DoubleMap::get(&15u32, &16u32), 42u64);
// get / insert / take
let key1 = 17u32;
let key2 = 18u32;
assert_eq!(DoubleMap::get(&key1, &key2), 0u64);
DoubleMap::insert(&key1, &key2, &4u64);
assert_eq!(DoubleMap::get(&key1, &key2), 4u64);
assert_eq!(DoubleMap::take(&key1, &key2), 4u64);
assert_eq!(DoubleMap::get(&key1, &key2), 0u64);
// mutate
DoubleMap::mutate(&key1, &key2, |val| {
*val = 15;
});
assert_eq!(DoubleMap::get(&key1, &key2), 15u64);
// remove
DoubleMap::remove(&key1, &key2);
assert_eq!(DoubleMap::get(&key1, &key2), 0u64);
// remove prefix
DoubleMap::insert(&key1, &key2, &4u64);
DoubleMap::insert(&key1, &(key2 + 1), &4u64);
DoubleMap::insert(&(key1 + 1), &key2, &4u64);
DoubleMap::insert(&(key1 + 1), &(key2 + 1), &4u64);
DoubleMap::remove_prefix(&key1);
assert_eq!(DoubleMap::get(&key1, &key2), 0u64);
assert_eq!(DoubleMap::get(&key1, &(key2 + 1)), 0u64);
assert_eq!(DoubleMap::get(&(key1 + 1), &key2), 4u64);
assert_eq!(DoubleMap::get(&(key1 + 1), &(key2 + 1)), 4u64);
});
}
#[test]
fn double_map_append_should_work() {
new_test_ext().execute_with(|| {
type DoubleMap = AppendableDM<Test>;
let key1 = 17u32;
let key2 = 18u32;
DoubleMap::insert(&key1, &key2, &vec![1]);
DoubleMap::append(&key1, &key2, 2);
assert_eq!(DoubleMap::get(&key1, &key2), &[1, 2]);
});
}
#[test]
fn double_map_mutate_exists_should_work() {
new_test_ext().execute_with(|| {
type DoubleMap = DataDM;
let (key1, key2) = (11, 13);
// mutated
DoubleMap::mutate_exists(key1, key2, |v| *v = Some(1));
assert_eq!(DoubleMap::get(&key1, key2), 1);
// removed if mutated to `None`
DoubleMap::mutate_exists(key1, key2, |v| *v = None);
assert!(!DoubleMap::contains_key(&key1, key2));
});
}
#[test]
fn double_map_try_mutate_exists_should_work() {
new_test_ext().execute_with(|| {
type DoubleMap = DataDM;
type TestResult = result::Result<(), &'static str>;
let (key1, key2) = (11, 13);
// mutated if `Ok`
assert_ok!(DoubleMap::try_mutate_exists(key1, key2, |v| -> TestResult {
*v = Some(1);
Ok(())
}));
assert_eq!(DoubleMap::get(&key1, key2), 1);
// no-op if `Err`
assert_noop!(DoubleMap::try_mutate_exists(key1, key2, |v| -> TestResult {
*v = Some(2);
Err("nah")
}), "nah");
// removed if mutated to`None`
assert_ok!(DoubleMap::try_mutate_exists(key1, key2, |v| -> TestResult {
*v = None;
Ok(())
}));
assert!(!DoubleMap::contains_key(&key1, key2));
});
}
const EXPECTED_METADATA: StorageMetadata = StorageMetadata {
prefix: DecodeDifferent::Encode("Test"),
entries: DecodeDifferent::Encode(
&[
StorageEntryMetadata {
name: DecodeDifferent::Encode("Data"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map{
hasher: StorageHasher::Twox64Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("u64"),
unused: false,
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructData(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("OptionLinkedMap"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map {
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("u32"),
unused: false,
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructOptionLinkedMap(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericData"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::Map{
hasher: StorageHasher::Identity,
key: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
unused: false
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructGenericData(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericData2"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::Map{
hasher: StorageHasher::Blake2_128Concat,
key: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
unused: false
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructGenericData2(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("DataDM"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::DoubleMap{
hasher: StorageHasher::Twox64Concat,
key1: DecodeDifferent::Encode("u32"),
key2: DecodeDifferent::Encode("u32"),
value: DecodeDifferent::Encode("u64"),
key2_hasher: StorageHasher::Blake2_128Concat,
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructDataDM(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericDataDM"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::DoubleMap{
hasher: StorageHasher::Blake2_128Concat,
key1: DecodeDifferent::Encode("T::BlockNumber"),
key2: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
key2_hasher: StorageHasher::Identity,
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructGenericDataDM(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("GenericData2DM"),
modifier: StorageEntryModifier::Optional,
ty: StorageEntryType::DoubleMap{
hasher: StorageHasher::Blake2_128Concat,
key1: DecodeDifferent::Encode("T::BlockNumber"),
key2: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("T::BlockNumber"),
key2_hasher: StorageHasher::Twox64Concat,
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructGenericData2DM(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
StorageEntryMetadata {
name: DecodeDifferent::Encode("AppendableDM"),
modifier: StorageEntryModifier::Default,
ty: StorageEntryType::DoubleMap{
hasher: StorageHasher::Blake2_128Concat,
key1: DecodeDifferent::Encode("u32"),
key2: DecodeDifferent::Encode("T::BlockNumber"),
value: DecodeDifferent::Encode("Vec<u32>"),
key2_hasher: StorageHasher::Blake2_128Concat,
},
default: DecodeDifferent::Encode(
DefaultByteGetter(&__GetByteStructGenericData2DM(PhantomData::<Test>))
),
documentation: DecodeDifferent::Encode(&[]),
},
]
),
};
#[test]
fn store_metadata() {
let metadata = Module::<Test>::storage_metadata();
pretty_assertions::assert_eq!(EXPECTED_METADATA, metadata);
}
parameter_types! {
storage StorageParameter: u64 = 10;
}
#[test]
fn check_storage_parameter_type_works() {
TestExternalities::default().execute_with(|| {
assert_eq!(sp_io::hashing::twox_128(b":StorageParameter:"), StorageParameter::key());
assert_eq!(10, StorageParameter::get());
StorageParameter::set(&300);
assert_eq!(300, StorageParameter::get());
})
}
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub static Members: Vec<u64> = vec![];
pub const Foo: Option<u64> = None;
}
}
/// Prelude to be used alongside pallet macro, for ease of use.
pub mod pallet_prelude {
pub use sp_std::marker::PhantomData;
#[cfg(feature = "std")]
pub use crate::traits::GenesisBuild;
pub use crate::{
EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, DebugNoBound, CloneNoBound, Twox256,
Twox128, Blake2_256, Blake2_128, Identity, Twox64Concat, Blake2_128Concat, ensure,
RuntimeDebug, storage,
traits::{
Get, Hooks, IsType, GetPalletVersion, EnsureOrigin, PalletInfoAccess, StorageInfoTrait,
ConstU32, GetDefault, MaxEncodedLen,
},
dispatch::{DispatchResultWithPostInfo, Parameter, DispatchError, DispatchResult},
weights::{DispatchClass, Pays, Weight},
storage::types::{
Key as NMapKey, StorageDoubleMap, StorageMap, StorageNMap, StorageValue, ValueQuery,
OptionQuery,
},
storage::bounded_vec::BoundedVec,
};
pub use codec::{Encode, Decode};
pub use crate::inherent::{InherentData, InherentIdentifier, ProvideInherent};
pub use sp_runtime::{
traits::{MaybeSerializeDeserialize, Member, ValidateUnsigned},
transaction_validity::{
TransactionSource, TransactionValidity, ValidTransaction, TransactionPriority,
TransactionTag, TransactionLongevity, TransactionValidityError, InvalidTransaction,
UnknownTransaction,
},
};
}
/// `pallet` attribute macro allows to define a pallet to be used in `construct_runtime!`.
///
/// It is define by a module item:
/// ```ignore
/// #[pallet]
/// pub mod pallet {
/// ...
/// }
/// ```
///
/// Inside the module the macro will parse item with the attribute: `#[pallet::*]`, some attributes
/// are mandatory, some other optional.
///
/// The attribute are explained with the syntax of non instantiable pallets, to see how pallet with
/// instance work see below example.
///
/// Note various type can be automatically imported using pallet_prelude in frame_support and
/// frame_system:
/// ```ignore
/// #[pallet]
/// pub mod pallet {
/// use frame_support::pallet_prelude::*;
/// use frame_system::pallet_prelude::*;
/// ...
/// }
/// ```
///
/// # Config trait: `#[pallet::config]` mandatory
///
/// The trait defining generics of the pallet.
///
/// Item must be defined as
/// ```ignore
/// #[pallet::config]
/// pub trait Config: frame_system::Config + $optionally_some_other_supertraits
/// $optional_where_clause
/// {
/// ...
/// }
/// ```
/// I.e. a regular trait definition named `Config`, with supertrait `frame_system::Config`,
/// optionally other supertrait and where clause.
///
/// The associated type `Event` is reserved, if defined it must bounds `From<Event>` and
/// `IsType<<Self as frame_system::Config>::Event>`, see `#[pallet::event]` for more information.
///
/// To put `Get` associated type into metadatas, use the attribute `#[pallet::constant]`, e.g.:
/// ```ignore
/// #[pallet::config]
/// pub trait Config: frame_system::Config {
/// #[pallet::constant]
/// type Foo: Get<u32>;
/// }
/// ```
///
/// To bypass the `frame_system::Config` supertrait check, use the attribute
/// `#[pallet::disable_frame_system_supertrait_check]`, e.g.:
/// ```ignore
/// #[pallet::config]
/// #[pallet::disable_frame_system_supertrait_check]
/// pub trait Config: pallet_timestamp::Config {}
/// ```
///
/// ### Macro expansion:
///
/// The macro expand pallet constant metadata with the information given by `#[pallet::constant]`.
///
/// # Pallet struct placeholder: `#[pallet::pallet]` mandatory
///
/// The placeholder struct, on which is implemented pallet informations.
///
/// Item must be defined as followed:
/// ```ignore
/// #[pallet::pallet]
/// pub struct Pallet<T>(_);
/// ```
/// I.e. a regular struct definition named `Pallet`, with generic T and no where clause.
///
/// To generate a `Store` trait associating all storages, use the attribute
/// `#[pallet::generate_store($vis trait Store)]`, e.g.:
/// ```ignore
/// #[pallet::pallet]
/// #[pallet::generate_store(pub(super) trait Store)]
/// pub struct Pallet<T>(_);
/// ```
/// More precisely the store trait contains an associated type for each storage. It is implemented
/// for `Pallet` allowing to access the storage from pallet struct.
///
/// Thus when defining a storage named `Foo`, it can later be accessed from `Pallet` using
/// `<Pallet as Store>::Foo`.
///
/// To generate the full storage info (used for PoV calculation) use the attribute
/// `#[pallet::set_storage_max_encoded_len]`, e.g.:
/// ```ignore
/// #[pallet::pallet]
/// #[pallet::set_storage_max_encoded_len]
/// pub struct Pallet<T>(_);
/// ```
///
/// This require all storage to implement the trait [`traits::StorageInfoTrait`], thus all keys
/// and value types must bound [`traits::MaxEncodedLen`].
///
/// ### Macro expansion:
///
/// The macro add this attribute to the struct definition:
/// ```ignore
/// #[derive(
/// frame_support::CloneNoBound,
/// frame_support::EqNoBound,
/// frame_support::PartialEqNoBound,
/// frame_support::RuntimeDebugNoBound,
/// )]
/// ```
/// and replace the type `_` by `PhantomData<T>`.
///
/// It implements on pallet:
/// * [`traits::GetPalletVersion`]
/// * [`traits::OnGenesis`]: contains some logic to write pallet version into storage.
/// * `ModuleErrorMetadata`: using error declared or no metadata.
///
/// It declare `type Module` type alias for `Pallet`, used by [`construct_runtime`].
///
/// It implements [`traits::PalletInfoAccess`] on `Pallet` to ease access to pallet informations
/// given by [`frame_support::traits::PalletInfo`].
/// (The implementation use the associated type `frame_system::Config::PalletInfo`).
///
/// It implements [`traits::StorageInfoTrait`] on `Pallet` which give information about all storages.
///
/// If the attribute generate_store is set then the macro creates the trait `Store` and implements
/// it on `Pallet`.
///
/// If the attribute set_storage_max_encoded_len is set then the macro call
/// [`traits::StorageInfoTrait`] for each storage in the implementation of
/// [`traits::StorageInfoTrait`] for the pallet.
///
/// # Hooks: `#[pallet::hooks]` optional
///
/// Implementation of `Hooks` on `Pallet` allowing to define some specific pallet logic.
///
/// Item must be defined as
/// ```ignore
/// #[pallet::hooks]
/// impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> $optional_where_clause {
/// }
/// ```
/// I.e. a regular trait implementation with generic bound: `T: Config`, for the trait
/// `Hooks<BlockNumberFor<T>>` (they are defined in preludes), for the type `Pallet<T>`
/// and with an optional where clause.
///
/// If no `#[pallet::hooks]` exists, then a default implementation corresponding to the following
/// code is automatically generated:
/// ```ignore
/// #[pallet::hooks]
/// impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
/// ```
///
/// ### Macro expansion:
///
/// The macro implements the traits `OnInitialize`, `OnIdle`, `OnFinalize`, `OnRuntimeUpgrade`,
/// `OffchainWorker`, `IntegrityTest` using `Hooks` implementation.
///
/// NOTE: OnRuntimeUpgrade is implemented with `Hooks::on_runtime_upgrade` and some additional
/// logic. E.g. logic to write pallet version into storage.
///
/// NOTE: The macro also adds some tracing logic when implementing the above traits. The following
/// hooks emit traces: `on_initialize`, `on_finalize` and `on_runtime_upgrade`.
///
/// # Call: `#[pallet::call]` optional
///
/// Implementation of pallet dispatchables.
///
/// Item must be defined as:
/// ```ignore
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {
/// /// $some_doc
/// #[pallet::weight($ExpressionResultingInWeight)]
/// $vis fn $fn_name(
/// origin: OriginFor<T>,
/// $some_arg: $some_type,
/// // or with compact attribute: #[pallet::compact] $some_arg: $some_type,
/// ...
/// ) -> DispatchResultWithPostInfo { // or `-> DispatchResult`
/// ...
/// }
/// ...
/// }
/// ```
/// I.e. a regular type implementation, with generic `T: Config`, on type `Pallet<T>`, with
/// optional where clause.
///
/// Each dispatchable needs to define a weight with `#[pallet::weight($expr)]` attribute,
/// the first argument must be `origin: OriginFor<T>`, compact encoding for argument can be used
/// using `#[pallet::compact]`, function must return `DispatchResultWithPostInfo` or
/// `DispatchResult`.
///
/// All arguments must implement `Debug`, `PartialEq`, `Eq`, `Decode`, `Encode`, `Clone`. For ease
/// of use, bound the trait `Member` available in frame_support::pallet_prelude.
///
/// If no `#[pallet::call]` exists, then a default implementation corresponding to the following
/// code is automatically generated:
/// ```ignore
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {}
/// ```
///
/// **WARNING**: modifying dispatchables, changing their order, removing some must be done with
/// care. Indeed this will change the outer runtime call type (which is an enum with one variant
/// per pallet), this outer runtime call can be stored on-chain (e.g. in pallet-scheduler).
/// Thus migration might be needed.
///
/// ### Macro expansion
///
/// The macro create an enum `Call` with one variant per dispatchable. This enum implements:
/// `Clone`, `Eq`, `PartialEq`, `Debug` (with stripped implementation in `not("std")`), `Encode`,
/// `Decode`, `GetDispatchInfo`, `GetCallName`, `UnfilteredDispatchable`.
///
/// The macro implement on `Pallet`, the `Callable` trait and a function `call_functions` which
/// returns the dispatchable metadatas.
///
/// # Extra constants: `#[pallet::extra_constants]` optional
///
/// Allow to define some extra constants to put into constant metadata.
///
/// Item must be defined as:
/// ```ignore
/// #[pallet::extra_constants]
/// impl<T: Config> Pallet<T> where $optional_where_clause {
/// /// $some_doc
/// $vis fn $fn_name() -> $some_return_type {
/// ...
/// }
/// ...
/// }
/// ```
/// I.e. a regular rust implement block with some optional where clause and functions with 0 args,
/// 0 generics, and some return type.
///
/// ### Macro expansion
///
/// The macro add some extra constant to pallet constant metadata.
///
/// # Error: `#[pallet::error]` optional
///
/// Allow to define an error type to be return from dispatchable on error.
/// This error type informations are put into metadata.
///
/// Item must be defined as:
/// ```ignore
/// #[pallet::error]
/// pub enum Error<T> {
/// /// $some_optional_doc
/// $SomeFieldLessVariant,
/// ...
/// }
/// ```
/// I.e. a regular rust enum named `Error`, with generic `T` and fieldless variants.
/// The generic `T` mustn't bound anything and where clause is not allowed. But bounds and where
/// clause shouldn't be needed for any usecase.
///
/// ### Macro expansion
///
/// The macro implements `Debug` trait and functions `as_u8` using variant position, and `as_str`
/// using variant doc.
///
/// The macro implements `From<Error<T>>` for `&'static str`.
/// The macro implements `From<Error<T>>` for `DispatchError`.
///
/// The macro implements `ModuleErrorMetadata` on `Pallet` defining the `ErrorMetadata` of the
/// pallet.
///
/// # Event: `#[pallet::event]` optional
///
/// Allow to define pallet events, pallet events are stored in the block when they deposited (and
/// removed in next block).
///
/// Item is defined as:
/// ```ignore
/// #[pallet::event]
/// #[pallet::metadata($SomeType = "$Metadata", $SomeOtherType = "$Metadata", ..)] // Optional
/// #[pallet::generate_deposit($visibility fn deposit_event)] // Optional
/// pub enum Event<$some_generic> $optional_where_clause {
/// /// Some doc
/// $SomeName($SomeType, $YetanotherType, ...),
/// ...
/// }
/// ```
/// I.e. an enum (with named or unnamed fields variant), named Event, with generic: none or `T` or
/// `T: Config`, and optional where clause.
///
/// Each field must implement `Clone`, `Eq`, `PartialEq`, `Encode`, `Decode`, and `Debug` (on std
/// only).
/// For ease of use, bound the trait `Member` available in frame_support::pallet_prelude.
///
/// Variant documentations and field types are put into metadata.
/// The attribute `#[pallet::metadata(..)]` allows to specify the metadata to put for some types.
///
/// The metadata of a type is defined by:
/// * if matching a type in `#[pallet::metadata(..)]`, then the corresponding metadata.
/// * otherwise the type stringified.
///
/// E.g.:
/// ```ignore
/// #[pallet::event]
/// #[pallet::metadata(u32 = "SpecialU32")]
/// pub enum Event<T: Config> {
/// Proposed(u32, T::AccountId),
/// }
/// ```
/// will write in event variant metadata `"SpecialU32"` and `"T::AccountId"`.
///
/// The attribute `#[pallet::generate_deposit($visibility fn deposit_event)]` generate a helper
/// function on `Pallet` to deposit event.
///
/// NOTE: For instantiable pallet, event must be generic over T and I.
///
/// ### Macro expansion:
///
/// Macro will add on enum `Event` the attributes:
/// * `#[derive(frame_support::CloneNoBound)]`,
/// * `#[derive(frame_support::EqNoBound)]`,
/// * `#[derive(frame_support::PartialEqNoBound)]`,
/// * `#[derive(codec::Encode)]`,
/// * `#[derive(codec::Decode)]`,
/// * `#[derive(frame_support::RuntimeDebugNoBound)]`
///
/// Macro implements `From<Event<..>>` for ().
///
/// Macro implements metadata function on `Event` returning the `EventMetadata`.
///
/// If `#[pallet::generate_deposit]` then macro implement `fn deposit_event` on `Pallet`.
///
/// # Storage: `#[pallet::storage]` optional
///
/// Allow to define some abstract storage inside runtime storage and also set its metadata.
/// This attribute can be used multiple times.
///
/// Item is defined as:
/// ```ignore
/// #[pallet::storage]
/// #[pallet::getter(fn $getter_name)] // optional
/// $vis type $StorageName<$some_generic> $optional_where_clause
/// = $StorageType<$generic_name = $some_generics, $other_name = $some_other, ...>;
/// ```
/// or with unnamed generic
/// ```ignore
/// #[pallet::storage]
/// #[pallet::getter(fn $getter_name)] // optional
/// $vis type $StorageName<$some_generic> $optional_where_clause
/// = $StorageType<_, $some_generics, ...>;
/// ```
/// I.e. it must be a type alias, with generics: `T` or `T: Config`, aliased type must be one
/// of `StorageValue`, `StorageMap` or `StorageDoubleMap` (defined in frame_support).
/// The generic arguments of the storage type can be given in two manner: named and unnamed.
/// For named generic argument: the name for each argument is the one as define on the storage
/// struct:
/// * [`pallet_prelude::StorageValue`] expect `Value` and optionally `QueryKind` and `OnEmpty`,
/// * [`pallet_prelude::StorageMap`] expect `Hasher`, `Key`, `Value` and optionally `QueryKind` and
/// `OnEmpty`,
/// * [`pallet_prelude::StorageDoubleMap`] expect `Hasher1`, `Key1`, `Hasher2`, `Key2`, `Value` and
/// optionally `QueryKind` and `OnEmpty`.
///
/// For unnamed generic argument: Their first generic must be `_` as it is replaced by the macro
/// and other generic must declared as a normal declaration of type generic in rust.
///
/// The Prefix generic written by the macro is generated using `PalletInfo::name::<Pallet<..>>()`
/// and the name of the storage type.
/// E.g. if runtime names the pallet "MyExample" then the storage `type Foo<T> = ...` use the
/// prefix: `Twox128(b"MyExample") ++ Twox128(b"Foo")`.
///
/// The optional attribute `#[pallet::getter(fn $my_getter_fn_name)]` allow to define a
/// getter function on `Pallet`.
///
/// E.g:
/// ```ignore
/// #[pallet::storage]
/// #[pallet::getter(fn my_storage)]
/// pub(super) type MyStorage<T> = StorageMap<Hasher = Blake2_128Concat, Key = u32, Value = u32>;
/// ```
/// or
/// ```ignore
/// #[pallet::storage]
/// #[pallet::getter(fn my_storage)]
/// pub(super) type MyStorage<T> = StorageMap<_, Blake2_128Concat, u32, u32>;
/// ```
///
/// The optional attributes `#[cfg(..)]` allow conditional compilation for the storage.
///
/// E.g:
/// ```ignore
/// #[cfg(feature = "my-feature")]
/// #[pallet::storage]
/// pub(super) type MyStorage<T> = StorageValue<Value = u32>;
/// ```
///
/// All the `cfg` attributes are automatically copied to the items generated for the storage, i.e. the
/// getter, storage prefix, and the metadata element etc.
///
/// NOTE: If the `QueryKind` generic parameter is still generic at this stage or is using some type
/// alias then the generation of the getter might fail. In this case the getter can be implemented
/// manually.
///
/// NOTE: The generic `Hasher` must implement the [`StorageHasher`] trait (or the type is not
/// usable at all). We use [`StorageHasher::METADATA`] for the metadata of the hasher of the
/// storage item. Thus generic hasher is supported.
///
/// ### Macro expansion
///
/// For each storage item the macro generates a struct named
/// `_GeneratedPrefixForStorage$NameOfStorage`, and implements
/// [`StorageInstance`](traits::StorageInstance) on it using the pallet and storage name. It then
/// uses it as the first generic of the aliased type.
///
/// For named generic, the macro will reorder the generics, and remove the names.
///
/// The macro implements the function `storage_metadata` on `Pallet` implementing the metadata for
/// all storage items based on their kind:
/// * for a storage value, the type of the value is copied into the metadata
/// * for a storage map, the type of the values and the key's type is copied into the metadata
/// * for a storage double map, the type of the values, and the types of key1 and key2 are copied into
/// the metadata.
///
/// # Type value: `#[pallet::type_value]` optional
///
/// Helper to define a struct implementing `Get` trait. To ease use of storage types.
/// This attribute can be used multiple time.
///
/// Item is defined as
/// ```ignore
/// #[pallet::type_value]
/// fn $MyDefaultName<$some_generic>() -> $default_type $optional_where_clause { $expr }
/// ```
/// I.e.: a function definition with generics none or `T: Config` and a returned type.
///
/// E.g.:
/// ```ignore
/// #[pallet::type_value]
/// fn MyDefault<T: Config>() -> T::Balance { 3.into() }
/// ```
///
/// NOTE: This attribute is meant to be used alongside `#[pallet::storage]` to defined some
/// specific default value in storage.
///
/// ### Macro expansion
///
/// Macro renames the function to some internal name, generate a struct with the original name of
/// the function and its generic, and implement `Get<$ReturnType>` by calling the user defined
/// function.
///
/// # Genesis config: `#[pallet::genesis_config]` optional
///
/// Allow to define the genesis configuration of the pallet.
///
/// Item is defined as either an enum or a struct.
/// It needs to be public and implement trait GenesisBuild with `#[pallet::genesis_build]`.
/// The type generics is constrained to be either none, or `T` or `T: Config`.
///
/// E.g:
/// ```ignore
/// #[pallet::genesis_config]
/// pub struct GenesisConfig<T: Config> {
/// _myfield: BalanceOf<T>,
/// }
/// ```
///
/// ### Macro expansion
///
/// Macro will add the following attribute on it:
/// * `#[cfg(feature = "std")]`
/// * `#[derive(Serialize, Deserialize)]`
/// * `#[serde(rename_all = "camelCase")]`
/// * `#[serde(deny_unknown_fields)]`
/// * `#[serde(bound(serialize = ""))]`
/// * `#[serde(bound(deserialize = ""))]`
///
/// # Genesis build: `#[pallet::genesis_build]` optional
///
/// Allow to define how genesis_configuration is built.
///
/// Item is defined as
/// ```ignore
/// #[pallet::genesis_build]
/// impl<T: Config> GenesisBuild<T> for GenesisConfig<$maybe_generics> {
/// fn build(&self) { $expr }
/// }
/// ```
/// I.e. a rust trait implementation with generic `T: Config`, of trait `GenesisBuild<T>` on type
/// `GenesisConfig` with generics none or `T`.
///
/// E.g.:
/// ```ignore
/// #[pallet::genesis_build]
/// impl<T: Config> GenesisBuild<T> for GenesisConfig {
/// fn build(&self) {}
/// }
/// ```
///
/// ### Macro expansion
///
/// Macro will add the following attribute on it:
/// * `#[cfg(feature = "std")]`
///
/// Macro will implement `sp_runtime::BuildModuleGenesisStorage` using `()` as second generic for
/// non-instantiable pallets.
///
/// # Inherent: `#[pallet::inherent]` optional
///
/// Allow the pallet to provide some inherent:
///
/// Item is defined as:
/// ```ignore
/// #[pallet::inherent]
/// impl<T: Config> ProvideInherent for Pallet<T> {
/// // ... regular trait implementation
/// }
/// ```
/// I.e. a trait implementation with bound `T: Config`, of trait `ProvideInherent` for type
/// `Pallet<T>`, and some optional where clause.
///
/// ### Macro expansion
///
/// Macro make currently no use of this information, but it might use this information in the
/// future to give information directly to construct_runtime.
///
/// # Validate unsigned: `#[pallet::validate_unsigned]` optional
///
/// Allow the pallet to validate some unsigned transaction:
///
/// Item is defined as:
/// ```ignore
/// #[pallet::validate_unsigned]
/// impl<T: Config> ValidateUnsigned for Pallet<T> {
/// // ... regular trait implementation
/// }
/// ```
/// I.e. a trait implementation with bound `T: Config`, of trait `ValidateUnsigned` for type
/// `Pallet<T>`, and some optional where clause.
///
/// NOTE: There is also `sp_runtime::traits::SignedExtension` that can be used to add some specific
/// logic for transaction validation.
///
/// ### Macro expansion
///
/// Macro make currently no use of this information, but it might use this information in the
/// future to give information directly to construct_runtime.
///
/// # Origin: `#[pallet::origin]` optional
///
/// Allow to define some origin for the pallet.
///
/// Item must be either a type alias or an enum or a struct. It needs to be public.
///
/// E.g.:
/// ```ignore
/// #[pallet::origin]
/// pub struct Origin<T>(PhantomData<(T)>);
/// ```
///
/// **WARNING**: modifying origin changes the outer runtime origin. This outer runtime origin can
/// be stored on-chain (e.g. in pallet-scheduler), thus any change must be done with care as it
/// might require some migration.
///
/// NOTE: for instantiable pallet, origin must be generic over T and I.
///
/// # General notes on instantiable pallet
///
/// An instantiable pallet is one where Config is generic, i.e. `Config<I>`. This allow runtime to
/// implement multiple instance of the pallet, by using different type for the generic.
/// This is the sole purpose of the generic `I`.
/// But because `PalletInfo` requires `Pallet` placeholder to be static it is important to bound
/// `'static` whenever `PalletInfo` can be used.
/// And in order to have instantiable pallet usable as a regular pallet without instance, it is
/// important to bound `= ()` on every types.
///
/// Thus impl bound look like `impl<T: Config<I>, I: 'static>`, and types look like
/// `SomeType<T, I=()>` or `SomeType<T: Config<I>, I: 'static = ()>`.
///
/// # Example for pallet without instance.
///
/// ```
/// pub use pallet::*; // reexport in crate namespace for `construct_runtime!`
///
/// #[frame_support::pallet]
/// // NOTE: The name of the pallet is provided by `construct_runtime` and is used as
/// // the unique identifier for the pallet's storage. It is not defined in the pallet itself.
/// pub mod pallet {
/// use frame_support::pallet_prelude::*; // Import various types used in the pallet definition
/// use frame_system::pallet_prelude::*; // Import some system helper types.
///
/// type BalanceOf<T> = <T as Config>::Balance;
///
/// // Define the generic parameter of the pallet
/// // The macro parses `#[pallet::constant]` attributes and uses them to generate metadata
/// // for the pallet's constants.
/// #[pallet::config]
/// pub trait Config: frame_system::Config {
/// #[pallet::constant] // put the constant in metadata
/// type MyGetParam: Get<u32>;
/// type Balance: Parameter + From<u8>;
/// type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
/// }
///
/// // Define some additional constant to put into the constant metadata.
/// #[pallet::extra_constants]
/// impl<T: Config> Pallet<T> {
/// /// Some description
/// fn exra_constant_name() -> u128 { 4u128 }
/// }
///
/// // Define the pallet struct placeholder, various pallet function are implemented on it.
/// #[pallet::pallet]
/// #[pallet::generate_store(pub(super) trait Store)]
/// pub struct Pallet<T>(_);
///
/// // Implement the pallet hooks.
/// #[pallet::hooks]
/// impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
/// fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
/// unimplemented!();
/// }
///
/// // can implement also: on_finalize, on_runtime_upgrade, offchain_worker, ...
/// // see `Hooks` trait
/// }
///
/// // Declare Call struct and implement dispatchables.
/// //
/// // WARNING: Each parameter used in functions must implement: Clone, Debug, Eq, PartialEq,
/// // Codec.
/// //
/// // The macro parses `#[pallet::compact]` attributes on function arguments and implements
/// // the `Call` encoding/decoding accordingly.
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {
/// /// Doc comment put in metadata
/// #[pallet::weight(0)] // Defines weight for call (function parameters are in scope)
/// fn toto(
/// origin: OriginFor<T>,
/// #[pallet::compact] _foo: u32,
/// ) -> DispatchResultWithPostInfo {
/// let _ = origin;
/// unimplemented!();
/// }
/// }
///
/// // Declare the pallet `Error` enum (this is optional).
/// // The macro generates error metadata using the doc comment on each variant.
/// #[pallet::error]
/// pub enum Error<T> {
/// /// doc comment put into metadata
/// InsufficientProposersBalance,
/// }
///
/// // Declare pallet Event enum (this is optional).
/// //
/// // WARNING: Each type used in variants must implement: Clone, Debug, Eq, PartialEq, Codec.
/// //
/// // The macro generates event metadata, and derive Clone, Debug, Eq, PartialEq and Codec
/// #[pallet::event]
/// // Additional argument to specify the metadata to use for given type.
/// #[pallet::metadata(BalanceOf<T> = "Balance", u32 = "Other")]
/// // Generate a funciton on Pallet to deposit an event.
/// #[pallet::generate_deposit(pub(super) fn deposit_event)]
/// pub enum Event<T: Config> {
/// /// doc comment put in metadata
/// // `<T as frame_system::Config>::AccountId` is not defined in metadata list, the last
/// // Thus the metadata is `<T as frame_system::Config>::AccountId`.
/// Proposed(<T as frame_system::Config>::AccountId),
/// /// doc
/// // here metadata will be `Balance` as define in metadata list
/// Spending(BalanceOf<T>),
/// // here metadata will be `Other` as define in metadata list
/// Something(u32),
/// }
///
/// // Define a struct which implements `frame_support::traits::Get<T::Balance>` (optional).
/// #[pallet::type_value]
/// pub(super) fn MyDefault<T: Config>() -> T::Balance { 3.into() }
///
/// // Declare a storage item. Any amount of storage items can be declared (optional).
/// //
/// // Is expected either `StorageValue`, `StorageMap` or `StorageDoubleMap`.
/// // The macro generates the prefix type and replaces the first generic `_`.
/// //
/// // The macro expands the metadata for the storage item with the type used:
/// // * for a storage value the type of the value is copied into the metadata
/// // * for a storage map the type of the values and the type of the key is copied into the metadata
/// // * for a storage double map the types of the values and keys are copied into the
/// // metadata.
/// //
/// // NOTE: The generic `Hasher` must implement the `StorageHasher` trait (or the type is not
/// // usable at all). We use [`StorageHasher::METADATA`] for the metadata of the hasher of the
/// // storage item. Thus generic hasher is supported.
/// #[pallet::storage]
/// pub(super) type MyStorageValue<T: Config> =
/// StorageValue<Value = T::Balance, QueryKind = ValueQuery, OnEmpty = MyDefault<T>>;
///
/// // Another storage declaration
/// #[pallet::storage]
/// #[pallet::getter(fn my_storage)]
/// pub(super) type MyStorage<T> =
/// StorageMap<Hasher = Blake2_128Concat, Key = u32, Value = u32>;
///
/// // Declare the genesis config (optional).
/// //
/// // The macro accepts either a struct or an enum; it checks that generics are consistent.
/// //
/// // Type must implement the `Default` trait.
/// #[pallet::genesis_config]
/// #[derive(Default)]
/// pub struct GenesisConfig {
/// _myfield: u32,
/// }
///
/// // Declare genesis builder. (This is need only if GenesisConfig is declared)
/// #[pallet::genesis_build]
/// impl<T: Config> GenesisBuild<T> for GenesisConfig {
/// fn build(&self) {}
/// }
///
/// // Declare a pallet origin (this is optional).
/// //
/// // The macro accept type alias or struct or enum, it checks generics are consistent.
/// #[pallet::origin]
/// pub struct Origin<T>(PhantomData<T>);
///
/// // Declare validate_unsigned implementation (this is optional).
/// #[pallet::validate_unsigned]
/// impl<T: Config> ValidateUnsigned for Pallet<T> {
/// type Call = Call<T>;
/// fn validate_unsigned(
/// source: TransactionSource,
/// call: &Self::Call
/// ) -> TransactionValidity {
/// Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
/// }
/// }
///
/// // Declare inherent provider for pallet (this is optional).
/// #[pallet::inherent]
/// impl<T: Config> ProvideInherent for Pallet<T> {
/// type Call = Call<T>;
/// type Error = InherentError;
///
/// const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
///
/// fn create_inherent(_data: &InherentData) -> Option<Self::Call> {
/// unimplemented!();
/// }
///
/// fn is_inherent(_call: &Self::Call) -> bool {
/// unimplemented!();
/// }
/// }
///
/// // Regular rust code needed for implementing ProvideInherent trait
///
/// #[derive(codec::Encode, sp_runtime::RuntimeDebug)]
/// #[cfg_attr(feature = "std", derive(codec::Decode))]
/// pub enum InherentError {
/// }
///
/// impl sp_inherents::IsFatalError for InherentError {
/// fn is_fatal_error(&self) -> bool {
/// unimplemented!();
/// }
/// }
///
/// pub const INHERENT_IDENTIFIER: sp_inherents::InherentIdentifier = *b"testpall";
/// }
/// ```
///
/// # Example for pallet with instance.
///
/// ```
/// pub use pallet::*;
///
/// #[frame_support::pallet]
/// pub mod pallet {
/// use frame_support::pallet_prelude::*;
/// use frame_system::pallet_prelude::*;
///
/// type BalanceOf<T, I = ()> = <T as Config<I>>::Balance;
///
/// #[pallet::config]
/// pub trait Config<I: 'static = ()>: frame_system::Config {
/// #[pallet::constant]
/// type MyGetParam: Get<u32>;
/// type Balance: Parameter + From<u8>;
/// type Event: From<Event<Self, I>> + IsType<<Self as frame_system::Config>::Event>;
/// }
///
/// #[pallet::extra_constants]
/// impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// /// Some description
/// fn exra_constant_name() -> u128 { 4u128 }
/// }
///
/// #[pallet::pallet]
/// #[pallet::generate_store(pub(super) trait Store)]
/// pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
///
/// #[pallet::hooks]
/// impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
/// }
///
/// #[pallet::call]
/// impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// /// Doc comment put in metadata
/// #[pallet::weight(0)]
/// fn toto(origin: OriginFor<T>, #[pallet::compact] _foo: u32) -> DispatchResultWithPostInfo {
/// let _ = origin;
/// unimplemented!();
/// }
/// }
///
/// #[pallet::error]
/// pub enum Error<T, I = ()> {
/// /// doc comment put into metadata
/// InsufficientProposersBalance,
/// }
///
/// #[pallet::event]
/// #[pallet::metadata(BalanceOf<T> = "Balance", u32 = "Other")]
/// #[pallet::generate_deposit(pub(super) fn deposit_event)]
/// pub enum Event<T: Config<I>, I: 'static = ()> {
/// /// doc comment put in metadata
/// Proposed(<T as frame_system::Config>::AccountId),
/// /// doc
/// Spending(BalanceOf<T, I>),
/// Something(u32),
/// }
///
/// #[pallet::type_value]
/// pub(super) fn MyDefault<T: Config<I>, I: 'static>() -> T::Balance { 3.into() }
///
/// #[pallet::storage]
/// pub(super) type MyStorageValue<T: Config<I>, I: 'static = ()> =
/// StorageValue<Value = T::Balance, QueryKind = ValueQuery, OnEmpty = MyDefault<T, I>>;
///
/// #[pallet::storage]
/// #[pallet::getter(fn my_storage)]
/// pub(super) type MyStorage<T, I = ()> =
/// StorageMap<Hasher = Blake2_128Concat, Key = u32, Value = u32>;
///
/// #[pallet::genesis_config]
/// #[derive(Default)]
/// pub struct GenesisConfig {
/// _myfield: u32,
/// }
///
/// #[pallet::genesis_build]
/// impl<T: Config<I>, I: 'static> GenesisBuild<T, I> for GenesisConfig {
/// fn build(&self) {}
/// }
///
/// #[pallet::origin]
/// pub struct Origin<T, I = ()>(PhantomData<(T, I)>);
///
/// #[pallet::validate_unsigned]
/// impl<T: Config<I>, I: 'static> ValidateUnsigned for Pallet<T, I> {
/// type Call = Call<T, I>;
/// fn validate_unsigned(
/// source: TransactionSource,
/// call: &Self::Call
/// ) -> TransactionValidity {
/// Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
/// }
/// }
///
/// #[pallet::inherent]
/// impl<T: Config<I>, I: 'static> ProvideInherent for Pallet<T, I> {
/// type Call = Call<T, I>;
/// type Error = InherentError;
///
/// const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
///
/// fn create_inherent(_data: &InherentData) -> Option<Self::Call> {
/// unimplemented!();
/// }
///
/// fn is_inherent(_call: &Self::Call) -> bool {
/// unimplemented!();
/// }
/// }
///
/// // Regular rust code needed for implementing ProvideInherent trait
///
/// #[derive(codec::Encode, sp_runtime::RuntimeDebug)]
/// #[cfg_attr(feature = "std", derive(codec::Decode))]
/// pub enum InherentError {
/// }
///
/// impl sp_inherents::IsFatalError for InherentError {
/// fn is_fatal_error(&self) -> bool {
/// unimplemented!();
/// }
/// }
///
/// pub const INHERENT_IDENTIFIER: sp_inherents::InherentIdentifier = *b"testpall";
/// }
/// ```
///
/// ## Upgrade guidelines:
///
/// 1. Export the metadata of the pallet for later checks
/// - run your node with the pallet active
/// - query the metadata using the `state_getMetadata` RPC and curl, or use
/// `subsee -p <PALLET_NAME> > meta.json`
/// 2. generate the template upgrade for the pallet provided by decl_storage
/// with environment variable `PRINT_PALLET_UPGRADE`:
/// `PRINT_PALLET_UPGRADE=1 cargo check -p my_pallet` This template can be
/// used as information it contains all information for storages, genesis
/// config and genesis build.
/// 3. reorganize pallet to have trait `Config`, `decl_*` macros, `ValidateUnsigned`,
/// `ProvideInherent`, `Origin` all together in one file. Suggested order:
/// * Config,
/// * decl_module,
/// * decl_event,
/// * decl_error,
/// * decl_storage,
/// * origin,
/// * validate_unsigned,
/// * provide_inherent,
/// so far it should compile and all be correct.
/// 4. start writing the new pallet module
/// ```ignore
/// pub use pallet::*;
///
/// #[frame_support::pallet]
/// pub mod pallet {
/// use frame_support::pallet_prelude::*;
/// use frame_system::pallet_prelude::*;
/// use super::*;
///
/// #[pallet::pallet]
/// #[pallet::generate_store($visibility_of_trait_store trait Store)]
/// // NOTE: if the visibility of trait store is private but you want to make it available
/// // in super, then use `pub(super)` or `pub(crate)` to make it available in crate.
/// pub struct Pallet<T>(_);
/// // pub struct Pallet<T, I = ()>(PhantomData<T>); // for instantiable pallet
/// }
/// ```
/// 5. **migrate Config**: move trait into the module with
/// * all const in decl_module to `#[pallet::constant]`
/// * add bound `IsType<<Self as frame_system::Config>::Event>` to `type Event`
/// 7. **migrate decl_module**: write:
/// ```ignore
/// #[pallet::hooks]
/// impl<T: Config> Hooks for Pallet<T> {
/// }
/// ```
/// and write inside on_initialize/on_finalize/on_runtime_upgrade/offchain_worker/integrity_test
///
/// then write:
/// ```ignore
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {
/// }
/// ```
/// and write inside all the calls in decl_module with a few changes in the signature:
/// - origin must now be written completely, e.g. `origin: OriginFor<T>`
/// - result type must be `DispatchResultWithPostInfo`, you need to write it and also you might
/// need to put `Ok(().into())` at the end or the function.
/// - `#[compact]` must now be written `#[pallet::compact]`
/// - `#[weight = ..]` must now be written `#[pallet::weight(..)]`
///
/// 7. **migrate event**:
/// rewrite as a simple enum under with the attribute `#[pallet::event]`,
/// use `#[pallet::generate_deposit($vis fn deposit_event)]` to generate deposit_event,
/// use `#[pallet::metadata(...)]` to configure the metadata for types in order not to break them.
/// 8. **migrate error**: rewrite it with attribute `#[pallet::error]`.
/// 9. **migrate storage**:
/// decl_storage provide an upgrade template (see 3.). All storages, genesis config, genesis
/// build and default implementation of genesis config can be taken from it directly.
///
/// Otherwise here is the manual process:
///
/// first migrate the genesis logic. write:
/// ```ignore
/// #[pallet::genesis_config]
/// struct GenesisConfig {
/// // fields of add_extra_genesis
/// }
/// impl Default for GenesisConfig {
/// // type default or default provided for fields
/// }
/// #[pallet::genesis_build]
/// impl<T: Config> GenesisBuild<T> for GenesisConfig {
/// // impl<T: Config, I: 'static> GenesisBuild<T, I> for GenesisConfig { for instantiable pallet
/// fn build() {
/// // The add_extra_genesis build logic
/// }
/// }
/// ```
/// for each storages, if it contains config(..) then add a fields, and make its default to the
/// value in `= ..;` or the type default if none, if it contains no build then also add the
/// logic to build the value.
/// for each storages if it contains build(..) then add the logic to genesis_build.
///
/// NOTE: in decl_storage: is executed first the individual config and build and at the end the
/// add_extra_genesis build
///
/// Once this is done you can migrate storage individually, a few notes:
/// - for private storage use `pub(crate) type ` or `pub(super) type` or nothing,
/// - for storage with `get(fn ..)` use `#[pallet::getter(fn ...)]`
/// - for storage with value being `Option<$something>` make generic `Value` being `$something`
/// and generic `QueryKind` being `OptionQuery` (note: this is default). Otherwise make
/// `Value` the complete value type and `QueryKind` being `ValueQuery`.
/// - for storage with default value: `= $expr;` provide some specific OnEmpty generic. To do so
/// use of `#[pallet::type_value]` to generate the wanted struct to put.
/// example: `MyStorage: u32 = 3u32` would be written:
/// ```ignore
/// #[pallet::type_value] fn MyStorageOnEmpty() -> u32 { 3u32 }
/// #[pallet::storage]
/// pub(super) type MyStorage<T> = StorageValue<_, u32, ValueQuery, MyStorageOnEmpty>;
/// ```
///
/// NOTE: `decl_storage` also generates functions `assimilate_storage` and `build_storage`
/// directly on GenesisConfig, those are sometimes used in tests. In order not to break they
/// can be implemented manually, one can implement those functions by calling `GenesisBuild`
/// implementation.
///
/// 10. **migrate origin**: move the origin to the pallet module under `#[pallet::origin]`
/// 11. **migrate validate_unsigned**: move the `ValidateUnsigned` implementation to the pallet
/// module under `#[pallet::validate_unsigned]`
/// 12. **migrate provide_inherent**: move the `ProvideInherent` implementation to the pallet
/// module under `#[pallet::inherent]`
/// 13. rename the usage of `Module` to `Pallet` inside the crate.
/// 14. migration is done, now double check migration with the checking migration guidelines.
///
/// ## Checking upgrade guidelines:
///
/// * compare metadata. Use [subsee](https://github.com/ascjones/subsee) to fetch the metadata
/// and do a diff of the resulting json before and after migration. This checks for:
/// * call, names, signature, docs
/// * event names, docs
/// * error names, docs
/// * storage names, hasher, prefixes, default value
/// * error , error, constant,
/// * manually check that:
/// * `Origin` is moved inside the macro under `#[pallet::origin]` if it exists
/// * `ValidateUnsigned` is moved inside the macro under `#[pallet::validate_unsigned)]` if it exists
/// * `ProvideInherent` is moved inside macro under `#[pallet::inherent)]` if it exists
/// * `on_initialize`/`on_finalize`/`on_runtime_upgrade`/`offchain_worker` are moved to `Hooks`
/// implementation
/// * storages with `config(..)` are converted to `GenesisConfig` field, and their default is
/// `= $expr;` if the storage have default value
/// * storages with `build($expr)` or `config(..)` are built in `GenesisBuild::build`
/// * `add_extra_genesis` fields are converted to `GenesisConfig` field with their correct
/// default if specified
/// * `add_extra_genesis` build is written into `GenesisBuild::build`
/// * storage items defined with [`pallet`] use the name of the pallet provided by
/// [`traits::PalletInfo::name`] as `pallet_prefix` (in `decl_storage`, storage items used the
/// `pallet_prefix` given as input of `decl_storage` with the syntax `as Example`).
/// Thus a runtime using the pallet must be careful with this change.
/// To handle this change:
/// * either ensure that the name of the pallet given to `construct_runtime!` is the same
/// as the name the pallet was giving to `decl_storage`,
/// * or do a storage migration from the old prefix used to the new prefix used.
///
/// NOTE: The prefixes used by storage items are in the metadata. Thus, ensuring the metadata hasn't
/// changed does ensure that the `pallet_prefix`s used by the storage items haven't changed.
///
/// # Notes when macro fails to show proper error message spans:
///
/// Rustc loses span for some macro input. Some tips to fix it:
/// * do not use inner attribute:
/// ```ignore
/// #[pallet]
/// pub mod pallet {
/// //! This inner attribute will make span fail
/// ..
/// }
/// ```
/// * use the newest nightly possible.
///
pub use frame_support_procedural::pallet;
/// The `max_encoded_len` module contains the `MaxEncodedLen` trait and derive macro, which is
/// useful for computing upper bounds on storage size.
pub use max_encoded_len;
|
use std::sync::Arc;
use datafusion::{
common::tree_node::{Transformed, TreeNode},
config::ConfigOptions,
error::Result,
physical_optimizer::PhysicalOptimizerRule,
physical_plan::ExecutionPlan,
};
use crate::{
physical_optimizer::chunk_extraction::extract_chunks,
provider::{chunks_to_physical_nodes, DeduplicateExec},
};
/// Removes de-duplication operation if there are at most 1 chunks and this chunk does NOT contain primary-key duplicates.
#[derive(Debug, Default)]
pub struct RemoveDedup;
impl PhysicalOptimizerRule for RemoveDedup {
fn optimize(
&self,
plan: Arc<dyn ExecutionPlan>,
config: &ConfigOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
plan.transform_up(&|plan| {
let plan_any = plan.as_any();
if let Some(dedup_exec) = plan_any.downcast_ref::<DeduplicateExec>() {
let mut children = dedup_exec.children();
assert_eq!(children.len(), 1);
let child = children.remove(0);
let Some((schema, chunks, output_sort_key)) = extract_chunks(child.as_ref()) else {
return Ok(Transformed::No(plan));
};
if (chunks.len() < 2) && chunks.iter().all(|c| !c.may_contain_pk_duplicates()) {
return Ok(Transformed::Yes(chunks_to_physical_nodes(
&schema,
output_sort_key.as_ref(),
chunks,
config.execution.target_partitions,
)));
}
}
Ok(Transformed::No(plan))
})
}
fn name(&self) -> &str {
"remove_dedup"
}
fn schema_check(&self) -> bool {
true
}
}
#[cfg(test)]
mod tests {
use crate::{
physical_optimizer::{
dedup::test_util::{chunk, dedup_plan},
test_util::OptimizationTest,
},
QueryChunk,
};
use super::*;
#[test]
fn test_no_chunks() {
let schema = chunk(1).schema().clone();
let plan = dedup_plan(schema, vec![]);
let opt = RemoveDedup;
insta::assert_yaml_snapshot!(
OptimizationTest::new(plan, opt),
@r###"
---
input:
- " DeduplicateExec: [tag1@1 ASC,tag2@2 ASC,time@3 ASC]"
- " EmptyExec: produce_one_row=false"
output:
Ok:
- " EmptyExec: produce_one_row=false"
"###
);
}
#[test]
fn test_single_chunk_no_pk_dups() {
let chunk1 = chunk(1).with_may_contain_pk_duplicates(false);
let schema = chunk1.schema().clone();
let plan = dedup_plan(schema, vec![chunk1]);
let opt = RemoveDedup;
insta::assert_yaml_snapshot!(
OptimizationTest::new(plan, opt),
@r###"
---
input:
- " DeduplicateExec: [tag1@1 ASC,tag2@2 ASC,time@3 ASC]"
- " UnionExec"
- " RecordBatchesExec: batches_groups=1 batches=0 total_rows=0"
output:
Ok:
- " UnionExec"
- " RecordBatchesExec: batches_groups=1 batches=0 total_rows=0"
"###
);
}
#[test]
fn test_single_chunk_with_pk_dups() {
let chunk1 = chunk(1).with_may_contain_pk_duplicates(true);
let schema = chunk1.schema().clone();
let plan = dedup_plan(schema, vec![chunk1]);
let opt = RemoveDedup;
insta::assert_yaml_snapshot!(
OptimizationTest::new(plan, opt),
@r###"
---
input:
- " DeduplicateExec: [tag1@1 ASC,tag2@2 ASC,time@3 ASC]"
- " UnionExec"
- " RecordBatchesExec: batches_groups=1 batches=0 total_rows=0"
output:
Ok:
- " DeduplicateExec: [tag1@1 ASC,tag2@2 ASC,time@3 ASC]"
- " UnionExec"
- " RecordBatchesExec: batches_groups=1 batches=0 total_rows=0"
"###
);
}
#[test]
fn test_multiple_chunks() {
let chunk1 = chunk(1).with_may_contain_pk_duplicates(false);
let chunk2 = chunk(2).with_may_contain_pk_duplicates(false);
let schema = chunk1.schema().clone();
let plan = dedup_plan(schema, vec![chunk1, chunk2]);
let opt = RemoveDedup;
insta::assert_yaml_snapshot!(
OptimizationTest::new(plan, opt),
@r###"
---
input:
- " DeduplicateExec: [tag1@1 ASC,tag2@2 ASC,time@3 ASC]"
- " UnionExec"
- " RecordBatchesExec: batches_groups=2 batches=0 total_rows=0"
output:
Ok:
- " DeduplicateExec: [tag1@1 ASC,tag2@2 ASC,time@3 ASC]"
- " UnionExec"
- " RecordBatchesExec: batches_groups=2 batches=0 total_rows=0"
"###
);
}
}
|
use druid::{
theme::{FOREGROUND_DARK, FOREGROUND_LIGHT},
widget::{CrossAxisAlignment, Flex, Label, MainAxisAlignment},
Data, Widget, WidgetExt
};
pub mod mode_selector;
pub mod tab_selector;
pub fn soft_label<T: Data>(text: &str) -> impl Widget<T> {
Label::new(text.to_string())
.with_text_color(FOREGROUND_DARK)
.with_text_size(14.0)
.align_left()
.padding(2.0)
}
pub fn titled_panel<D, W>(title: &'static str, subtitle: &'static str, inner: W) -> impl Widget<D>
where
D: Data,
W: Widget<D> + 'static,
{
Flex::column()
.cross_axis_alignment(CrossAxisAlignment::Start)
.with_child(
Flex::row()
.with_child(
Label::new(title)
.with_text_size(20.0)
.with_text_color(FOREGROUND_LIGHT),
)
.with_child(
Label::new(subtitle)
.with_text_size(20.0)
.with_text_color(FOREGROUND_DARK),
),
)
.with_flex_child(inner, 1.0)
}
pub fn input_label(name: &'static str) -> impl Widget<bool> {
Flex::row()
.main_axis_alignment(MainAxisAlignment::Start)
.with_child(soft_label(name))
.with_child(
Label::dynamic(|locked, _| {
if *locked {
String::from("locked")
} else {
String::new()
}
})
.with_text_color(FOREGROUND_DARK)
.with_text_size(14.0),
)
}
|
//! Library for managing Wake-on-LAN packets.
//! # Example
//! ```
//! let wol = wakey::WolPacket::from_string("01:02:03:04:05:06", ':').unwrap();
//! if wol.send_magic().is_ok() {
//! println!("Sent the magic packet!");
//! } else {
//! println!("Failed to send the magic packet!");
//! }
//! ```
use std::error::Error;
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use std::{fmt, iter};
use arrayvec::ArrayVec;
const MAC_SIZE: usize = 6;
const MAC_PER_MAGIC: usize = 16;
const HEADER: [u8; 6] = [0xFF; 6];
const PACKET_LEN: usize = HEADER.len() + MAC_SIZE * MAC_PER_MAGIC;
type Packet = ArrayVec<u8, PACKET_LEN>;
type Mac = ArrayVec<u8, MAC_SIZE>;
/// Wrapper `Result` for the module errors.
pub type Result<T> = std::result::Result<T, WakeyError>;
/// Wrapper Error for fiascoes occuring in this module.
#[derive(Debug)]
pub enum WakeyError {
/// The provided MAC address has invalid length.
InvalidMacLength,
/// The provided MAC address has invalid format.
InvalidMacFormat,
/// There was an error sending the WoL packet.
SendFailure(std::io::Error),
}
impl Error for WakeyError {}
impl fmt::Display for WakeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
WakeyError::InvalidMacLength => {
write!(f, "Invalid MAC address length")
}
WakeyError::InvalidMacFormat => write!(f, "Invalid MAC address format"),
WakeyError::SendFailure(e) => write!(f, "Couldn't send WoL packet: {e}"),
}
}
}
impl From<std::io::Error> for WakeyError {
fn from(error: std::io::Error) -> Self {
WakeyError::SendFailure(error)
}
}
/// Wake-on-LAN packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WolPacket {
/// WOL packet bytes
packet: Packet,
}
impl WolPacket {
/// Creates WOL packet from byte MAC representation
/// # Example
/// ```
/// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]);
/// ```
pub fn from_bytes(mac: &[u8]) -> Result<WolPacket> {
Ok(WolPacket {
packet: WolPacket::create_packet_bytes(mac)?,
})
}
/// Creates WOL packet from string MAC representation (e.x. 00:01:02:03:04:05)
/// # Example
/// ```
/// let wol = wakey::WolPacket::from_string("00:01:02:03:04:05", ':');
/// ```
/// # Panic
/// Panics when input MAC is invalid (i.e. contains non-byte characters)
pub fn from_string<T: AsRef<str>>(data: T, sep: char) -> Result<WolPacket> {
WolPacket::from_bytes(&WolPacket::mac_to_byte(data, sep)?)
}
/// Broadcasts the magic packet from / to default address
/// Source: 0.0.0.0:0
/// Destination 255.255.255.255:9
/// # Example
/// ```
/// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]).unwrap();
/// wol.send_magic();
/// ```
pub fn send_magic(&self) -> Result<()> {
self.send_magic_to(
SocketAddr::from(([0, 0, 0, 0], 0)),
SocketAddr::from(([255, 255, 255, 255], 9)),
)
}
/// Broadcasts the magic packet from / to specified address.
/// # Example
/// ```
/// use std::net::SocketAddr;
/// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]).unwrap();
/// let src = SocketAddr::from(([0,0,0,0], 0));
/// let dst = SocketAddr::from(([255,255,255,255], 9));
/// wol.send_magic_to(src, dst);
/// ```
pub fn send_magic_to<A: ToSocketAddrs>(&self, src: A, dst: A) -> Result<()> {
let udp_sock = UdpSocket::bind(src)?;
udp_sock.set_broadcast(true)?;
udp_sock.send_to(&self.packet, dst)?;
Ok(())
}
/// Returns the underlying WoL packet bytes
pub fn into_inner(self) -> Packet {
self.packet
}
/// Converts string representation of MAC address (e.x. 00:01:02:03:04:05) to raw bytes.
/// # Panic
/// Panics when input MAC is invalid (i.e. contains non-byte characters)
fn mac_to_byte<T: AsRef<str>>(data: T, sep: char) -> Result<Mac> {
// hex-encoded bytes * 2 plus separators
if data.as_ref().len() != MAC_SIZE * 3 - 1 {
return Err(WakeyError::InvalidMacLength);
}
let bytes = data
.as_ref()
.split(sep)
.map(|x| hex::decode(x).map_err(|_| WakeyError::InvalidMacFormat))
.collect::<Result<ArrayVec<_, MAC_SIZE>>>()?
.into_iter()
.flatten()
.collect::<Mac>();
debug_assert_eq!(MAC_SIZE, bytes.len());
Ok(bytes)
}
/// Extends the MAC address to fill the magic packet
fn extend_mac(mac: &[u8]) -> ArrayVec<u8, { MAC_SIZE * MAC_PER_MAGIC }> {
let magic = iter::repeat(mac)
.take(MAC_PER_MAGIC)
.flatten()
.copied()
.collect::<ArrayVec<u8, { MAC_SIZE * MAC_PER_MAGIC }>>();
debug_assert_eq!(MAC_SIZE * MAC_PER_MAGIC, magic.len());
magic
}
/// Creates bytes of the magic packet from MAC address
fn create_packet_bytes(mac: &[u8]) -> Result<Packet> {
if mac.len() != MAC_SIZE {
return Err(WakeyError::InvalidMacLength);
}
let mut packet = Packet::new();
packet.extend(HEADER);
packet.extend(WolPacket::extend_mac(mac));
debug_assert_eq!(PACKET_LEN, packet.len());
Ok(packet)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extend_mac_test() {
let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
let extended_mac = WolPacket::extend_mac(&mac);
assert_eq!(extended_mac.len(), MAC_PER_MAGIC * MAC_SIZE);
assert_eq!(&extended_mac[(MAC_PER_MAGIC - 1) * MAC_SIZE..], &mac[..]);
}
#[test]
#[should_panic]
fn extend_mac_mac_too_long_test() {
let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
WolPacket::extend_mac(&mac);
}
#[test]
#[should_panic]
fn extend_mac_mac_too_short_test() {
let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05];
WolPacket::extend_mac(&mac);
}
#[test]
fn mac_to_byte_test() {
let mac = "01:02:03:04:05:06";
let result = WolPacket::mac_to_byte(mac, ':');
assert_eq!(
result.unwrap().into_inner().unwrap(),
[0x01, 0x02, 0x03, 0x04, 0x05, 0x06]
);
}
#[test]
fn mac_to_byte_invalid_chars_test() {
let mac = "ZZ:02:03:04:05:06";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacFormat)
));
}
#[test]
fn mac_to_byte_invalid_separator_test() {
let mac = "01002:03:04:05:06";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacFormat)
));
}
#[test]
fn mac_to_byte_mac_too_long_test() {
let mac = "01:02:03:04:05:06:07";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacLength)
));
}
#[test]
fn mac_to_byte_mac_too_short_test() {
let mac = "01:02:03:04:05";
assert!(matches!(
WolPacket::mac_to_byte(mac, ':'),
Err(WakeyError::InvalidMacLength)
));
}
#[test]
fn create_packet_bytes_test() {
let bytes = WolPacket::create_packet_bytes(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap();
assert_eq!(bytes.len(), MAC_SIZE * MAC_PER_MAGIC + HEADER.len());
assert!(bytes.iter().all(|&x| x == 0xFF));
}
#[test]
fn create_wol_packet() {
let mac = vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05];
let wol = WolPacket::from_bytes(&mac).unwrap();
let packet = wol.into_inner();
assert_eq!(packet.len(), PACKET_LEN);
assert_eq!(
[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
&packet[0..HEADER.len()]
);
for offset in (HEADER.len()..PACKET_LEN).step_by(MAC_SIZE) {
assert_eq!(&mac, &packet[offset..offset + MAC_SIZE]);
}
}
}
|
//! When serializing or deserializing NBT goes wrong.
use core::fmt;
use std::io;
use serde::{de, ser};
/// This type represents all possible errors that can occur when serializing or
/// deserializing NBT data.
pub struct Error {
err: Box<ErrorImpl>,
}
/// Alias for a `Result` with the error type `coruscant_nbt::Error`.
pub type Result<T> = core::result::Result<T, Error>;
struct ErrorImpl {
code: ErrorCode,
index: usize, // index == 0: index is not necessary
}
pub(crate) enum ErrorCode {
Message(Box<str>),
Io(io::Error),
UnsupportedType,
UnsupportedListInnerType,
UnsupportedArrayType,
UnsupportedArrayInnerType,
InvalidStringLength,
KeyMustBeAString,
SequenceSizeUnknown,
ListDifferentType,
ArrayDifferentType,
InvalidBoolByte(i8),
InvalidUtf8String,
TypeIdMismatch(u8, u8),
TypeIdInvalid(u8),
InvalidLength(i16),
SliceUnexpectedEof,
}
impl Error {
pub(crate) fn syntax(code: ErrorCode, index: usize) -> Self {
Self::from_inner(code, index)
}
pub(crate) fn io(error: io::Error) -> Self {
let code = ErrorCode::Io(error);
Self::from_inner(code, 0)
}
pub(crate) fn io_at(error: io::Error, index: usize) -> Self {
let code = ErrorCode::Io(error);
Self::from_inner(code, index)
}
pub(crate) fn utf8_at(index: usize) -> Self {
let code = ErrorCode::InvalidUtf8String;
Self::from_inner(code, index)
}
pub(crate) fn mismatch_at(mismatch: u8, expected: u8, index: usize) -> Self {
let code = ErrorCode::TypeIdMismatch(mismatch, expected);
Self::from_inner(code, index)
}
pub(crate) fn invalid_id_at(invalid_id: u8, index: usize) -> Self {
let code = ErrorCode::TypeIdInvalid(invalid_id);
Self::from_inner(code, index)
}
pub(crate) fn bool_at(invalid: i8, index: usize) -> Self {
let code = ErrorCode::InvalidBoolByte(invalid);
Self::from_inner(code, index)
}
pub(crate) fn invalid_len_at(invalid: i16, index: usize) -> Self {
let code = ErrorCode::InvalidLength(invalid);
Self::from_inner(code, index)
}
pub(crate) fn slice_eof() -> Self {
let code = ErrorCode::SliceUnexpectedEof;
Self::from_inner(code, 0)
}
#[inline]
fn from_inner(code: ErrorCode, index: usize) -> Self {
Error {
err: Box::new(ErrorImpl { code, index }),
}
}
}
impl fmt::Debug for Error {
// todo: improve error message format
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.err.index == 0 {
fmt::Display::fmt(&self.err.code, f)
} else {
write!(f, "(NBT input:{}) {}", self.err.index, self.err.code)
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&*self.err, f)
}
}
impl fmt::Display for ErrorImpl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.index == 0 {
fmt::Display::fmt(&self.code, f)
} else {
// todo: improve message format
write!(f, "(NBT input:{}) {}", self.index, self.code)
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &*self {
ErrorCode::Message(ref msg) => f.write_str(msg),
ErrorCode::Io(ref err) => fmt::Display::fmt(err, f),
ErrorCode::UnsupportedType => f.write_str("unsupported NBT type"),
ErrorCode::UnsupportedListInnerType => f.write_str("unsupported NBT list-wrapped type"),
ErrorCode::UnsupportedArrayType => {
f.write_str("unsupported type for NBT arrays; a sequence is required")
}
ErrorCode::UnsupportedArrayInnerType => f.write_str("unsupported NBT array inner type"),
ErrorCode::InvalidStringLength => f.write_str("invalid NBT string length"),
ErrorCode::KeyMustBeAString => f.write_str("NBT key must be a string"),
ErrorCode::SequenceSizeUnknown => f.write_str("size of NBT sequence is unknown"),
ErrorCode::ListDifferentType => {
f.write_str("elements of one NBT list do not have the same type")
}
ErrorCode::ArrayDifferentType => {
f.write_str("elements of one NBT array do not have the same type")
}
ErrorCode::InvalidBoolByte(invalid) => f.write_fmt(format_args!(
"invalid NBT boolean byte {} (0x{:02X}), 0 or 1 expected",
invalid, invalid
)),
ErrorCode::InvalidUtf8String => f.write_str("invalid utf-8 NBT string"),
ErrorCode::TypeIdMismatch(invalid, expected) => f.write_fmt(format_args!(
"mismatched NBT type id {} (0x{:02X}), expected {} (0x{:02X})",
invalid, invalid, expected, expected
)),
ErrorCode::TypeIdInvalid(invalid) => f.write_fmt(format_args!(
"invalid type id {} (0x{:02X})",
invalid, invalid
)),
ErrorCode::InvalidLength(invalid) => f.write_fmt(format_args!(
"invalid length {} (0x{:04X}); length must be positive for NBT",
invalid, invalid
)),
ErrorCode::SliceUnexpectedEof => {
f.write_str("unexpected EOF when reading NBT source slice")
}
}
}
}
impl std::error::Error for Error {}
impl ser::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
let string = msg.to_string();
let code = ErrorCode::Message(string.into_boxed_str());
Self::from_inner(code, 0)
}
}
impl de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
let string = msg.to_string();
let code = ErrorCode::Message(string.into_boxed_str());
Self::from_inner(code, 0)
}
}
impl From<io::Error> for Error {
fn from(src: io::Error) -> Error {
Error::io(src)
}
}
|
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CurveInfo {
pub r#type: String,
pub arith: String,
pub value: f64,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Data {
pub level: usize,
pub curve_infos: Vec<CurveInfo>,
}
|
#![allow(dead_code)]
extern crate nalgebra_glm as glm;
extern crate opencv;
mod shader;
mod shader_program;
mod triangle;
mod rasterizer;
mod utility;
mod shader_utility;
use triangle::*;
use rasterizer::*;
use opencv::{core::{self, CV_32FC2, CV_32FC3, CV_8UC3, Vector}, highgui, imgcodecs::{self, IMREAD_COLOR, imwrite, imwritemulti}, imgproc::{self, COLOR_BGR2RGB, COLOR_RGB2BGR}, prelude::*, videoio};
use std::io::BufReader;
use std::default;
use crate::shader_program::*;
use opencv::imgcodecs::imread;
const MY_PI: f32 = 3.1415927;
const TWO_PI: f32 = 2.0 * MY_PI;
fn get_model_matrix(rotation_angle: f32, axis: &glm::Vec3) -> glm::Mat4x4 {
let _mat = glm::Mat4x4::identity();
// // 绕x -45°
// {
// let _r = -45. * 3.24 / 180.;
// _mat = glm::rotate(&_mat, _r, &glm::vec3(1., 0., 0.));
// }
let radians = rotation_angle * 3.14 / 180.0;
let mut _mat = glm::rotate(&_mat, radians, axis);
return _mat;
}
fn load_mesh(path: String) -> obj::ObjResult<(Vec<SVertex>, Vec<glm::U32Vec3>)> {
use obj::*;
let _file = std::fs::File::open(path)?;
let read_buf = BufReader::new(_file);
let wf_obj: Obj<TexturedVertex> = load_obj(read_buf)?;
let mut mesh = Vec::with_capacity(wf_obj.vertices.len());
for wf_v in &wf_obj.vertices {
let pos = glm::vec3(wf_v.position[0], wf_v.position[1], wf_v.position[2]);
let normal = glm::vec3(wf_v.normal[0], wf_v.normal[1], wf_v.normal[2]);
let uv = glm::vec3(wf_v.texture[0], wf_v.texture[1], wf_v.texture[2]);
let color = glm::vec3(0.619f32, 0.474, 0.360);
mesh.push(SVertex{
pos, normal, uv, color
});
}
let mut indices = Vec::with_capacity(wf_obj.indices.len());
for i in 0..wf_obj.indices.len()/3 {
indices.push(glm::vec3(
wf_obj.indices[i*3 + 0] as u32,
wf_obj.indices[i*3 + 1] as u32,
wf_obj.indices[i*3 + 2] as u32,
));
}
return Ok((mesh, indices))
}
fn load_static_mesh() -> obj::ObjResult<(Vec<SVertex>, Vec<glm::U32Vec3>)>{
let mut mesh = Vec::with_capacity(6);
mesh.push(SVertex{
pos: glm::vec3(2.0f32, 0.0, 0.0),
color: glm::vec3(1.0f32, 0.0, 0.0),
..Default::default()
});
mesh.push(SVertex{
pos: glm::vec3(0.0f32, 2.0, 0.0),
color: glm::vec3(0.0f32, 1.0, 0.0),
..Default::default()
});
mesh.push(SVertex{
pos: glm::vec3(-2.0f32, 0.0, 0.0),
color: glm::vec3(0.0f32, 0.0, 1.0),
..Default::default()
});
mesh.push(SVertex{
pos: glm::vec3(2.0f32, 2.0, -1.0),
color: glm::vec3(0.0f32, 1.0, 0.0),
..Default::default()
});
mesh.push(SVertex{
pos: glm::vec3(0.0f32, 2.0, 0.0),
color: glm::vec3(0.0f32, 1.0, 0.0),
..Default::default()
});
mesh.push(SVertex{
pos: glm::vec3(-1.5f32, -1.0, 1.0),
color: glm::vec3(0.0f32, 1.0, 0.0),
..Default::default()
});
let mut ind = Vec::with_capacity(2);
ind.push(glm::vec3(0, 1, 2));
ind.push(glm::vec3(3, 4, 5));
return Ok((mesh, ind));
}
const width : u32 = 700;
const height : u32 = 700;
fn main(){
println!("{:?}", std::fs::canonicalize("."));
let b1 = Buffer::COLOR;
let b2 = Buffer::DEPTH;
println!("Hello, world!, {}", f32::INFINITY);
let mut angle = -140.0;
let command_line = true;
// let command_line = false;
let mut rst = Rasterizer::new(width, height);
// 组装数据 --begin
// let (pos, ind) = load_static_mesh().unwrap();
let (pos, ind) = load_mesh("./models/spot/spot_triangulated_good.obj".to_string()).unwrap();
// 世界
let model_mat = glm::Mat4::identity();
// 相机
let eye = glm::vec3(0.0, 0.0, 5.0);
let at = glm::vec3(0.0, 0.0, 1.0);
let up = glm::vec3(0.0, 1.0, 0.0);
let view_mat = glm::look_at_lh(&eye, &at, &up);
// // 投影
// let proj_mat = glm::ortho_lh(-2.5, 2.5, -2.5, 2.5, 0.0, 100.0);
let proj_mat =
glm::perspective_fov_lh(3.14f32/6.0, width as f32, height as f32, 0.1, 100.0);
// set fragment shader
rst.set_frame_shader(Box::new(bump_fs));
// set fragment shader value
rst.set_cfv_eye_pos(eye.clone());
// 加载任意贴图
let texture0 = imread("./models/spot/hmap.jpg", IMREAD_COLOR).unwrap();
rst.set_cfv_texture0(texture0);
// 组装数据 --end
let pos_id = rst.load_position(pos);
let ind_id = rst.load_indices(ind);
if command_line {
rst.clear(Buffer::DEPTH | Buffer::COLOR);
rst.set_model(&get_model_matrix(angle, &glm::vec3(0., 1., 0.)));
rst.set_view(&view_mat);
rst.set_projection(&proj_mat);
rst.draw(pos_id, ind_id, Primitive::TRIANGLE);
let mat = unsafe {
Mat::new_nd_with_data(
&[width as i32, height as i32], CV_32FC3,
rst.frame_buf_ptr(),
None).unwrap()
};
let mut out_mat = Mat::default();
mat.convert_to(&mut out_mat, CV_8UC3, 255.0, 0.0).unwrap();
println!("{:?}", out_mat);
let mut params = Vector::new();
params.push(COLOR_BGR2RGB);
imwrite("output_dump5.png", &out_mat, ¶ms).unwrap();
return;
}
let win_name = "window";
highgui::named_window(win_name, highgui::WINDOW_NORMAL).unwrap();
let mut key = 0i32;
while key != 27 {
rst.clear(Buffer::DEPTH | Buffer::COLOR);
rst.set_model(&get_model_matrix(angle, &glm::vec3(0., 1., 0.)));
rst.set_view(&view_mat);
rst.set_projection(&proj_mat);
rst.draw(pos_id, ind_id, Primitive::TRIANGLE);
let mat = unsafe {
Mat::new_nd_with_data(
&[width as i32, height as i32], CV_32FC3,
rst.frame_buf_ptr(),
None).unwrap()
};
let mut out_mat = Mat::default();
mat.convert_to(&mut out_mat, CV_8UC3, 255.0, 0.0).unwrap();
highgui::imshow(win_name, &out_mat).unwrap();
key = highgui::wait_key(10).unwrap();
if key == ('a' as i32) {
angle += 10.0;
}
else if key == ('d' as i32) {
angle -= 10.0;
}
}
}
|
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
fn main() {
let filename = String::from("doc.txt");
let mut contents = String::new();
// let mut map = HashMap::new();
let mut f = File::open(filename).expect("file not found");
f.read_to_string(&mut contents).expect("error reading file");
// 1. remove punct
let no_punct = rm_punct(contents);
// 2. to lowercase
let lc = no_punct.to_lowercase();
let split = lc.split_whitespace();
let map = create_map(split);
let mut count_vec: Vec<_> = map.iter().collect();
count_vec.sort_by(|a, b| b.1.cmp(a.1));
for (word, cnt) in count_vec {
println!("{} - {}", word, cnt);
}
}
fn create_map(s: std::str::SplitWhitespace) -> HashMap<&str, i32> {
let mut map = HashMap::new();
for word in s {
let count = map.entry(word).or_insert(0);
*count += 1;
}
map
}
fn rm_punct(t: String) -> String {
let re = Regex::new(r"[[:punct:][:cntrl:]]").unwrap();
let result = re.replace_all(&*t, "");
String::from(result)
} |
//pub mod auth;
pub mod handlers;
pub mod stream_server;
|
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Writer for register CSR"]
pub type W = crate::W<u32, super::CSR>;
#[doc = "Register CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TSOM`"]
pub type TSOM_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TSOM`"]
pub struct TSOM_W<'a> {
w: &'a mut W,
}
impl<'a> TSOM_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 `TEOM`"]
pub type TEOM_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TEOM`"]
pub struct TEOM_W<'a> {
w: &'a mut W,
}
impl<'a> TEOM_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 `TERR`"]
pub type TERR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TERR`"]
pub struct TERR_W<'a> {
w: &'a mut W,
}
impl<'a> TERR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `TBTRF`"]
pub type TBTRF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TBTRF`"]
pub struct TBTRF_W<'a> {
w: &'a mut W,
}
impl<'a> TBTRF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `RSOM`"]
pub type RSOM_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RSOM`"]
pub struct RSOM_W<'a> {
w: &'a mut W,
}
impl<'a> RSOM_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `REOM`"]
pub type REOM_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `REOM`"]
pub struct REOM_W<'a> {
w: &'a mut W,
}
impl<'a> REOM_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `RERR`"]
pub type RERR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RERR`"]
pub struct RERR_W<'a> {
w: &'a mut W,
}
impl<'a> RERR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `RBTF`"]
pub type RBTF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RBTF`"]
pub struct RBTF_W<'a> {
w: &'a mut W,
}
impl<'a> RBTF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 0 - Tx start of message"]
#[inline(always)]
pub fn tsom(&self) -> TSOM_R {
TSOM_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Tx end of message"]
#[inline(always)]
pub fn teom(&self) -> TEOM_R {
TEOM_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Tx error"]
#[inline(always)]
pub fn terr(&self) -> TERR_R {
TERR_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Tx byte transfer request or block transfer finished"]
#[inline(always)]
pub fn tbtrf(&self) -> TBTRF_R {
TBTRF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Rx start of message"]
#[inline(always)]
pub fn rsom(&self) -> RSOM_R {
RSOM_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Rx end of message"]
#[inline(always)]
pub fn reom(&self) -> REOM_R {
REOM_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Rx error"]
#[inline(always)]
pub fn rerr(&self) -> RERR_R {
RERR_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Rx byte/block transfer finished"]
#[inline(always)]
pub fn rbtf(&self) -> RBTF_R {
RBTF_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Tx start of message"]
#[inline(always)]
pub fn tsom(&mut self) -> TSOM_W {
TSOM_W { w: self }
}
#[doc = "Bit 1 - Tx end of message"]
#[inline(always)]
pub fn teom(&mut self) -> TEOM_W {
TEOM_W { w: self }
}
#[doc = "Bit 2 - Tx error"]
#[inline(always)]
pub fn terr(&mut self) -> TERR_W {
TERR_W { w: self }
}
#[doc = "Bit 3 - Tx byte transfer request or block transfer finished"]
#[inline(always)]
pub fn tbtrf(&mut self) -> TBTRF_W {
TBTRF_W { w: self }
}
#[doc = "Bit 4 - Rx start of message"]
#[inline(always)]
pub fn rsom(&mut self) -> RSOM_W {
RSOM_W { w: self }
}
#[doc = "Bit 5 - Rx end of message"]
#[inline(always)]
pub fn reom(&mut self) -> REOM_W {
REOM_W { w: self }
}
#[doc = "Bit 6 - Rx error"]
#[inline(always)]
pub fn rerr(&mut self) -> RERR_W {
RERR_W { w: self }
}
#[doc = "Bit 7 - Rx byte/block transfer finished"]
#[inline(always)]
pub fn rbtf(&mut self) -> RBTF_W {
RBTF_W { w: self }
}
}
|
#![feature(generators, generator_trait, box_syntax)]
#![feature(inclusive_range_syntax)]
#![feature(specialization)]
#![feature(ord_max_min)]
#![feature(link_args)]
#![feature(const_fn)]
extern crate common;
extern crate noise;
pub use resources as res;
pub use common::*;
#[macro_use] pub mod bindings;
#[macro_use] pub mod coro_util;
pub mod mut_rc;
pub mod resources;
pub mod rendering;
pub mod console;
pub mod webgl;
mod events;
use coro_util::*;
use webgl::*;
use rendering::*;
use rendering::mesh_builder::*;
use std::time::Instant;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct ColorVertex(Vec3, Vec3);
impl Vertex for ColorVertex {
fn get_layout() -> VertexLayout {
VertexLayout::new::<Self>()
.add_binding(0, 3, 0)
.add_binding(1, 3, 12)
}
}
const CAMERA_PITCH: f32 = PI/8.0;
const CAMERA_YAW: f32 = PI/4.0;
const CAMERA_FOV: f32 = PI/4.0;
const CAMERA_DISTANCE: f32 = 12.0;
// #[link_args = "-s ASSERTIONS=1"] extern "C" {}
// #[link_args = "-g4"] extern "C" {}
fn main() {
set_coro_as_main_loop(|| {
console::init();
console::set_color("#222");
let gl_ctx = WebGLContext::new();
gl_ctx.set_background(Color::grey_a(0.0, 0.0));
let mut event_queue = Vec::new();
events::init_event_queue(&mut event_queue);
unsafe {
gl::Enable(gl::DEPTH_TEST);
gl::Enable(gl::BLEND);
gl::BlendEquation(gl::FUNC_ADD);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
}
let boat_mesh: Mesh = {
use ColorVertex as V;
let mut mb = MeshBuilder::new();
let color = Color::rgb8(211, 126, 78).into();
let color2 = Color::rgb8(187, 97, 53).into();
let vs = [
V(Vec3::new(-0.5, 0.2, 0.5), color),
V(Vec3::new( 0.9, 0.2, 0.0), color),
V(Vec3::new(-0.5, 0.2,-0.5), color),
V(Vec3::new(-0.1,-0.3, 0.0), color2),
];
let es = [
0, 1, 2,
0, 3, 1,
1, 3, 2,
2, 3, 0,
];
mb.add_direct(&vs, &es);
let mast_color = Color::rgb8(187, 112, 70).into();
let sail_color = Color::rgb8(171, 220, 107).into();
let mast_width = 0.02 * 2.0f32.sqrt();
let mast_offset = Vec3::new(0.5, 0.0, 0.0);
let mast_height = 1.5;
mb.add_quad(&[
V(Vec3::new(-mast_width, 0.18,-mast_width) + mast_offset, mast_color),
V(Vec3::new( mast_width, 0.18, mast_width) + mast_offset, mast_color),
V(Vec3::new( mast_width, mast_height, mast_width) + mast_offset, mast_color),
V(Vec3::new(-mast_width, mast_height,-mast_width) + mast_offset, mast_color),
]);
mb.add_quad(&[
V(Vec3::new(-mast_width, 0.18, mast_width) + mast_offset, mast_color),
V(Vec3::new( mast_width, 0.18,-mast_width) + mast_offset, mast_color),
V(Vec3::new( mast_width, mast_height,-mast_width) + mast_offset, mast_color),
V(Vec3::new(-mast_width, mast_height, mast_width) + mast_offset, mast_color),
]);
mb.add_convex_poly(&[
V(Vec3::new(-0.0, mast_height, 0.0) + mast_offset, sail_color),
V(Vec3::new(-0.45, 0.25, 0.0), sail_color),
V(Vec3::new(-0.1, 0.25, 0.1), sail_color),
V(Vec3::new(-0.0, 0.25, 0.0) + mast_offset, sail_color),
]);
mb.into()
};
let sea_mesh: Mesh = {
use ColorVertex as V;
let mut mb = MeshBuilder::new();
let color = Color::rgb8(122, 158, 198).into();
mb.add_quad(&[
V(Vec3::new(-1.0, 0.0,-1.0), color),
V(Vec3::new( 1.0, 0.0,-1.0), color),
V(Vec3::new( 1.0, 0.0, 1.0), color),
V(Vec3::new(-1.0, 0.0, 1.0), color),
]);
mb.into()
};
let view_mat = Mat4::translate(Vec3::new(0.0, 0.0,-CAMERA_DISTANCE))
* Mat4::xrot(CAMERA_PITCH)
* Mat4::yrot(CAMERA_YAW);
let shader = Shader::new(res::shaders::BASIC_VS, res::shaders::BASIC_FS);
shader.use_program();
shader.set_view(&Mat4::ident());
let drag_threshold = 50.0;
let mut drag_start = None;
let mut wave_phase = 0.0;
let mut target_heading = -3.0 * CAMERA_YAW / 2.0;
let mut target_speed = 0.0;
let mut boat_heading_rate = 0.0;
let mut boat_heading = target_heading;
let mut boat_speed = 0.0;
loop {
let frame_start = Instant::now();
use events::Event;
for e in event_queue.iter() {
match *e {
Event::Resize(sz) => unsafe {
gl::Viewport(0, 0, sz.x, sz.y);
let aspect = sz.x as f32 / sz.y as f32;
let proj_mat = Mat4::perspective(CAMERA_FOV, aspect, 1.0, 100.0);
let proj_view = proj_mat * view_mat;
shader.set_proj(&proj_view);
}
Event::Down(pos) => {
drag_start = Some(pos);
}
Event::Move(pos) => if drag_start.is_some() {
let drag_start = drag_start.unwrap_or(pos);
let diff = pos - drag_start;
let dist = diff.length();
if dist > drag_threshold {
target_speed = (dist - drag_threshold).min(100.0) / 100.0;
target_heading = diff.to_vec2().to_angle() - CAMERA_YAW;
} else {
target_speed = 0.0;
}
}
Event::Up(_) => {
drag_start = None;
}
}
}
event_queue.clear();
boat_speed += (target_speed - boat_speed) / 60.0;
let mut heading_diff = target_heading - boat_heading;
if heading_diff.abs() > PI {
heading_diff -= 2.0 * PI * heading_diff.signum();
}
let heading_factor = 1.0 / 30.0;
boat_heading_rate *= 1.0 - heading_factor;
boat_heading_rate += heading_diff.max(-PI/6.0).min(PI/6.0) * heading_factor;
boat_heading += (1.0 - (1.0 - boat_heading_rate/PI).powf(1.2)) * PI / 60.0;
let wave_phase_offset = (wave_phase*PI/5.0).sin();
let wave_omega = wave_phase*PI/3.0 + wave_phase_offset;
let wave_translate = wave_omega.sin();
let wave_slope = wave_omega.cos() * (PI/5.0 * (wave_phase*PI/5.0).cos() + PI/3.0);
// wolfram alpha: d sin(sin(pi x/5) + pi x/3) / dx
let boat_roll = boat_heading_rate / 3.0;
let boat_translate = 0.05 * wave_translate - 0.6 * boat_roll.abs() / PI;
wave_phase += 1.0/60.0 + boat_speed * 1.0 / 60.0;
console::set_section("boat_heading_rate", format!("{}", boat_heading_rate));
console::set_section("boat_heading", format!("{}", boat_heading));
console::set_section("boat_speed", format!("{}", boat_speed));
console::set_section("boat_roll", format!("{}", boat_roll));
let boat_model_mat = Mat4::translate(Vec3::new(0.0, boat_translate, 0.0))
* Mat4::yrot(boat_heading)
* Mat4::xrot(boat_roll)
* Mat4::zrot(PI / 64.0 * wave_slope);
shader.set_view(&boat_model_mat);
boat_mesh.bind();
boat_mesh.draw(gl::TRIANGLES);
shader.set_view(&Mat4::ident());
sea_mesh.bind();
sea_mesh.draw(gl::TRIANGLES);
let now = Instant::now();
if now > frame_start {
let dur = now - frame_start;
console::set_section("Stats", format!("frame time: {:.1}ms", dur.subsec_nanos() as f64 / 1000_000.0));
console::update();
}
yield;
}
});
}
#[allow(dead_code)]
fn screen_to_gl(screen_size: Vec2i, v: Vec2i) -> Vec2{
let sz = screen_size.to_vec2();
let aspect = sz.x as f32 / sz.y as f32;
let norm = v.to_vec2() / screen_size.to_vec2() * 2.0 - Vec2::splat(1.0);
norm * Vec2::new(aspect, -1.0)
}
|
use rocket::http::{ Status, ContentType };
use rocket::local::Client;
use crate::rocket;
fn client() -> Client {
let rocket = rocket();
Client::new(rocket).expect("valid rocket client")
}
#[test]
fn test_hello_page() {
let client = client();
let mut response = client.get("/hello").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.content_type(), Some(ContentType::Plain));
assert_eq!(response.body_string(), Some("Hello Rocket!".into()));
}
|
//! The implementation of the `#[export_root_module]` attribute.
use super::*;
use as_derive_utils::return_spanned_err;
use syn::Ident;
use proc_macro2::Span;
use abi_stable_shared::mangled_root_module_loader_name;
#[doc(hidden)]
pub fn export_root_module_attr(_attr: TokenStream1, item: TokenStream1) -> TokenStream1 {
parse_or_compile_err(item, export_root_module_inner).into()
}
#[cfg(test)]
fn export_root_module_str(item: &str) -> Result<TokenStream2, syn::Error> {
syn::parse_str(item).and_then(export_root_module_inner)
}
fn export_root_module_inner(mut input: ItemFn) -> Result<TokenStream2, syn::Error> {
let vis = &input.vis;
let unsafe_no_layout_constant_path =
syn::parse_str::<syn::Path>("unsafe_no_layout_constant").expect("BUG");
let mut found_unsafe_no_layout_constant = false;
input.attrs.retain(|attr| {
let is_it = attr.path == unsafe_no_layout_constant_path;
found_unsafe_no_layout_constant = found_unsafe_no_layout_constant || is_it;
!is_it
});
let check_ty_layout_variant = Ident::new(
if found_unsafe_no_layout_constant {
"No"
} else {
"Yes"
},
Span::call_site(),
);
let ret_ty = match &input.sig.output {
syn::ReturnType::Default => {
return_spanned_err!(input.sig.ident, "The return type can't be `()`")
}
syn::ReturnType::Type(_, ty) => ty,
};
let original_fn_ident = &input.sig.ident;
let export_name = Ident::new(&mangled_root_module_loader_name(), Span::call_site());
Ok(quote!(
#input
#[no_mangle]
#vis static #export_name: ::abi_stable::library::LibHeader = {
pub extern "C" fn _sabi_erased_module()-> ::abi_stable::library::RootModuleResult {
::abi_stable::library::__call_root_module_loader(#original_fn_ident)
}
type __SABI_Module = <#ret_ty as ::abi_stable::library::IntoRootModuleResult>::Module;
unsafe{
::abi_stable::library::LibHeader::from_constructor::<__SABI_Module>(
_sabi_erased_module,
::abi_stable::library::CheckTypeLayout::#check_ty_layout_variant,
)
}
};
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_output() {
let list = vec![
(
r##"
pub fn hello()->RString{}
"##,
"CheckTypeLayout::Yes",
),
(
r##"
#[unsafe_no_layout_constant]
pub fn hello()->RString{}
"##,
"CheckTypeLayout::No",
),
(
r##"
#[hello]
#[unsafe_no_layout_constant]
pub fn hello()->RString{}
"##,
"CheckTypeLayout::No",
),
(
r##"
#[hello]
#[unsafe_no_layout_constant]
#[hello]
pub fn hello()->RString{}
"##,
"CheckTypeLayout::No",
),
(
r##"
#[unsafe_no_layout_constant]
#[hello]
pub fn hello()->RString{}
"##,
"CheckTypeLayout::No",
),
];
for (item, expected_const) in list {
let str_out = export_root_module_str(item)
.unwrap()
.to_string()
.chars()
.filter(|c| !c.is_whitespace())
.collect::<String>();
assert!(str_out.contains(expected_const));
}
}
}
|
// Binary file using a tcp communication protocol to the client
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
mod gui;
mod i2c;
mod protocol;
mod shared;
use protocol::{IncomingMsg, OutgoingMsg};
use shared::{Event, SerialEvent};
// Launch function for an interface module using i2c for communication
pub fn launch(tx: Sender<Event>, rx: Receiver<SerialEvent>) {
// Create listener for a tcp connection of port 6969
let listener = TcpListener::bind("0.0.0.0:6969").unwrap();
// Block the thread until a client connects
let (stream_rx, _addr) = listener.accept().unwrap();
let mut stream_tx = stream_rx.try_clone().unwrap();
// Spawn a thread for sending OutgoingMsg to the client over tcp
thread::spawn(move || {
for message in rx.iter() {
stream_tx
.write_all(
serde_json::to_string(&OutgoingMsg::from(message))
.unwrap()
.as_bytes(),
)
.unwrap();
}
});
let mut buf_reader = BufReader::new(stream_rx);
// Read data over tcp and parse that data into IncomingMsg in the system
loop {
let mut content = String::new();
match buf_reader.read_line(&mut content) {
Ok(_) => {
let message: IncomingMsg = serde_json::from_str(content.as_ref()).unwrap();
tx.send(Event::from(message)).unwrap();
}
Err(e) => {
let error = format!("{:?}", e);
tx.send(Event::Gui(gui::GuiEvent::Log(error))).unwrap();
break;
}
}
}
}
// Launch the main thread using a tcp interface
fn main() {
shared::start(launch);
}
|
use reqwest::blocking::Client;
use std::env;
use std::io;
use oauth2::pkce::PkceToken;
use oauth2::util;
fn build_auth_url(
auth_url: &str,
redirect_uri: &str,
client_id: &str,
pkce_token: &PkceToken,
state: &str,
) -> String {
format!(
"{}?{}&{}&{}&{}&{}&{}&{}",
auth_url,
"response_type=code",
"scope=photos",
format!("client_id={}", client_id),
format!("state={}", state),
format!("redirect_uri={}", redirect_uri),
format!("code_challenge={}", pkce_token.code_challenge),
"code_challenge_method=S256"
)
}
fn build_code_redeem_body(
redirect_uri: &str,
client_id: &str,
client_secret: &str,
pkce_token: &PkceToken,
auth_code: &str,
) -> String {
format!(
"{{ {}, {}, {}, {}, {}, {}, {} }}",
"\"grant_type\": \"authorization_code\"",
format!(" \"redirect_uri\": \"{}\"", redirect_uri),
format!(" \"client_id\": \"{}\"", client_id),
format!(" \"client_secret\": \"{}\"", client_secret),
format!(" \"redirect_uri\": \"{}\"", redirect_uri),
format!(" \"code_verifier\": \"{}\"", pkce_token.code_verifier),
format!(" \"code\": \"{}\"", auth_code)
)
}
fn main() {
let client = Client::new();
let auth_endpoint = env::var("OAUTH_AUTH_ENDPOINT").unwrap();
let client_id = env::var("PUBLIC_CLIENT_KEY").unwrap();
let pkce_token = PkceToken::new();
let state = util::generate_random_string(10);
let redirect_uri = "https://example-app.com/redirect";
let auth_url = build_auth_url(
&auth_endpoint,
redirect_uri,
&client_id,
&pkce_token,
&state,
);
println!(
"Client running.\nAuthorization url: {}\nState: {}\nCode verifier: {}",
auth_url, state, pkce_token.code_verifier
);
println!("Enter code: ");
let mut s = String::new();
let auth_code = match io::stdin().read_line(&mut s) {
Ok(_) => s.trim(),
_ => panic!("Could not read code."),
};
println!("Code: {}", auth_code);
let token_endpoint = env::var("OAUTH_TOKEN_ENDPOINT").unwrap();
let client_secret = env::var("SECRET_CLIENT_KEY").unwrap();
let token_body = build_code_redeem_body(
redirect_uri,
&client_id,
&client_secret,
&pkce_token,
auth_code,
);
println!("Token body: {}", token_body);
let response = client.post(token_endpoint).body(token_body).send().unwrap();
println!("Response: {:?}", response);
println!("Response text: {}", response.text().unwrap());
}
|
// 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.
// The logic for parsing Kleene operators in macros has a special case to disambiguate `?`.
// Specifically, `$(pat)?` is the ZeroOrOne operator whereas `$(pat)?+` or `$(pat)?*` are the
// ZeroOrMore and OneOrMore operators using `?` as a separator. These tests are intended to
// exercise that logic in the macro parser.
//
// Moreover, we also throw in some tests for using a separator with `?`, which is meaningless but
// included for consistency with `+` and `*`.
//
// This test focuses on non-error cases and making sure the correct number of repetitions happen.
// compile-flags: --edition=2018
#![feature(macro_at_most_once_rep)]
macro_rules! foo {
($($a:ident)? ; $num:expr) => { {
let mut x = 0;
$(
x += $a;
)?
assert_eq!(x, $num);
} }
}
pub fn main() {
let a = 1;
// accept 0 or 1 repetitions
foo!( ; 0);
foo!(a ; 1);
}
|
use std::{iter, mem};
use proc_macro2::TokenStream;
use syn::{
punctuated::Punctuated, token, Attribute, Block, Expr, ExprBlock, ExprCall, ExprPath,
ExprTuple, Path, PathSegment, Stmt,
};
mod attrs;
pub(crate) use self::attrs::{Attrs, AttrsMut};
// =================================================================================================
// Extension traits
pub(crate) trait VecExt<T> {
fn find_remove(&mut self, predicate: impl FnMut(&T) -> bool) -> Option<T>;
}
impl<T> VecExt<T> for Vec<T> {
fn find_remove(&mut self, predicate: impl FnMut(&T) -> bool) -> Option<T> {
self.iter().position(predicate).map(|i| self.remove(i))
}
}
// =================================================================================================
// Functions
pub(crate) fn path(segments: impl IntoIterator<Item = PathSegment>) -> Path {
Path { leading_colon: None, segments: segments.into_iter().collect() }
}
pub(crate) fn block(stmts: Vec<Stmt>) -> Block {
Block { brace_token: token::Brace::default(), stmts }
}
pub(crate) fn expr_block(block: Block) -> Expr {
Expr::Block(ExprBlock { attrs: Vec::new(), label: None, block })
}
pub(crate) fn expr_call(attrs: Vec<Attribute>, path: Path, arg: Expr) -> Expr {
Expr::Call(ExprCall {
attrs,
func: Box::new(Expr::Path(ExprPath { attrs: Vec::new(), qself: None, path })),
paren_token: token::Paren::default(),
args: iter::once(arg).collect(),
})
}
/// Generate an expression to fill in where the error occurred during the visit.
/// These will eventually need to be replaced with the original error message.
pub(super) fn expr_unimplemented() -> Expr {
syn::parse_quote!(compile_error!("#[auto_enum] failed to generate error message"))
}
pub(crate) fn unit() -> Expr {
Expr::Tuple(ExprTuple {
attrs: Vec::new(),
paren_token: token::Paren::default(),
elems: Punctuated::new(),
})
}
pub(crate) fn replace_expr(this: &mut Expr, f: impl FnOnce(Expr) -> Expr) {
*this = f(mem::replace(this, Expr::Verbatim(TokenStream::new())));
}
pub(crate) fn replace_block(this: &mut Block, f: impl FnOnce(Block) -> Expr) {
*this = block(vec![Stmt::Expr(f(mem::replace(this, block(Vec::new()))))]);
}
// =================================================================================================
// Macros
macro_rules! error {
($span:expr, $msg:expr) => {
syn::Error::new_spanned(&$span, $msg)
};
($span:expr, $($tt:tt)*) => {
error!($span, format!($($tt)*))
};
}
|
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::term::prelude::*;
use super::seq_trace::flag_is_not_a_supported_atom;
// See https://github.com/lumen/otp/blob/30e2bfb9f1fd5c65bd7d9a4159f88cdcf72023fa/erts/emulator/beam/erl_bif_trace.c#L1705-L1828
#[native_implemented::function(erlang:seq_trace/2)]
pub fn result(flag: Term, _value: Term) -> exception::Result<Term> {
let flag_name = term_try_into_atom!(flag)?.name();
match flag_name {
"label" => unimplemented!(),
"monotonic_timestamp" => unimplemented!(),
"print" => unimplemented!(),
"receive" => unimplemented!(),
"send" => unimplemented!(),
"serial" => unimplemented!(),
"spawn" => unimplemented!(),
"strict_monotonic_timestamp" => unimplemented!(),
"timestamp" => unimplemented!(),
_ => flag_is_not_a_supported_atom(flag),
}
}
|
// =======================================================================
// LIBRARY IMPORTS
// =======================================================================
use serde_json;
use std::borrow::Borrow;
use std::hash::Hash;
// =======================================================================
// TRAIT DECLARATION
// =======================================================================
/// Adds a `contains_keys()` method to any Map like object
pub trait ContainsKeys<K> {
fn contains_keys<Q: ?Sized>(&self, keys: &[&Q]) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + Ord;
}
// =======================================================================
// TRAIT IMPLEMENTATION
// =======================================================================
impl ContainsKeys<String> for serde_json::Value {
fn contains_keys<Q: ?Sized>(&self, keys: &[&Q]) -> bool
where
String: Borrow<Q>,
Q: Hash + Eq + Ord
{
self.as_object().map_or(
false,
|obj| keys.iter().all(|ref key| obj.contains_key(key))
)
}
}
impl ContainsKeys<String> for serde_json::map::Map<String, serde_json::Value> {
fn contains_keys<Q: ?Sized>(&self, keys: &[&Q]) -> bool
where
String: Borrow<Q>,
Q: Hash + Eq + Ord
{
keys.iter().all(|ref key| self.contains_key(key))
}
}
// =======================================================================
// UNIT TESTS
// =======================================================================
#[cfg(test)]
mod tests {
use serde_json;
use super::ContainsKeys;
#[test]
fn contains_keys() {
let obj: serde_json::Value = serde_json::from_str(r#"{"a": 1, "b": 2}"#).unwrap();
assert_eq!(obj.contains_keys(&["a", "b"]), true);
assert_eq!(obj.contains_keys(&["a", "b", "c"]), false);
}
} |
use ouroboros::self_referencing;
pub type I32Ref<'a> = &'a i32;
#[self_referencing]
struct I32CellImpl {
owner: Box<i32>,
#[borrows(owner)]
#[covariant]
dependent: I32Ref<'this>,
}
pub struct I32Cell(I32CellImpl);
impl I32Cell {
pub fn new(owner: i32, dependent_builder: impl for<'a> FnOnce(&'a i32) -> I32Ref<'a>) -> Self {
Self(
I32CellImplBuilder {
owner: Box::new(owner),
dependent_builder,
}
.build(),
)
}
pub fn try_new<E>(
owner: i32,
dependent_builder: impl for<'a> FnOnce(&'a i32) -> Result<I32Ref<'a>, E>,
) -> Result<Self, E> {
Ok(Self(
I32CellImplTryBuilder {
owner: Box::new(owner),
dependent_builder,
}
.try_build()?,
))
}
pub fn borrow_owner(&self) -> &i32 {
self.0.borrow_owner()
}
pub fn borrow_dependent(&self) -> &I32Ref {
self.0.borrow_dependent()
}
}
pub type Ast<'a> = Vec<&'a str>;
#[self_referencing]
pub struct StringCellImpl {
owner: String,
#[borrows(owner)]
#[covariant]
dependent: Ast<'this>,
}
pub struct StringCell(StringCellImpl);
impl StringCell {
pub fn new(owner: String, dependent_builder: impl for<'a> FnOnce(&'a str) -> Ast<'a>) -> Self {
Self(
StringCellImplBuilder {
owner,
dependent_builder,
}
.build(),
)
}
pub fn try_new<E>(
owner: String,
dependent_builder: impl for<'a> FnOnce(&'a str) -> Result<Ast<'a>, E>,
) -> Result<Self, E> {
Ok(Self(
StringCellImplTryBuilder {
owner,
dependent_builder,
}
.try_build()?,
))
}
pub fn borrow_owner(&self) -> &String {
self.0.borrow_owner()
}
pub fn borrow_dependent(&self) -> &Ast {
self.0.borrow_dependent()
}
}
|
use crate::{Judge, PlayCount, UpdatedAt, UserId};
use serde::Serialize;
use std::cmp::Ordering;
#[derive(Debug, Serialize)]
pub struct PlayerStats {
pub log: Vec<PlayerStat>,
}
impl PlayerStats {
pub fn new(log: Vec<PlayerStat>) -> PlayerStats {
PlayerStats { log }
}
pub fn last(&self) -> Option<&PlayerStat> {
self.log.iter().last()
}
pub fn diff(&self) -> Vec<PlayerStatDiff> {
let mut log = self.log.clone();
log.sort_by(PlayerStat::cmp_by_date);
let mut ret = Vec::new();
for i in 1..log.len() {
let before = log[i - 1].clone();
let after = log[i].clone();
ret.push(PlayerStatDiff::new(
before.date,
after.date,
after.play_count - before.play_count,
after.clear_count - before.clear_count,
after.play_time - before.play_time,
after.total_judge - before.total_judge,
));
}
ret
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PlayerStat {
pub play_count: PlayCount,
pub clear_count: PlayCount,
pub play_time: PlayTime,
pub date: UpdatedAt,
pub total_judge: TotalJudge,
}
impl PlayerStat {
pub fn new(
play_count: PlayCount,
clear_count: PlayCount,
play_time: PlayTime,
date: UpdatedAt,
total_judge: TotalJudge,
) -> PlayerStat {
PlayerStat {
play_count,
clear_count,
play_time,
date,
total_judge,
}
}
pub fn cmp_by_date(&self, other: &PlayerStat) -> Ordering {
self.date.cmp(&other.date)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PlayerStatDiff {
before_date: UpdatedAt,
after_date: UpdatedAt,
play_count: PlayCount,
clear_count: PlayCount,
play_time: PlayTime,
total_judge: TotalJudge,
}
impl PlayerStatDiff {
pub fn new(
before_date: UpdatedAt,
after_date: UpdatedAt,
play_count: PlayCount,
clear_count: PlayCount,
play_time: PlayTime,
total_judge: TotalJudge,
) -> PlayerStatDiff {
PlayerStatDiff {
before_date,
after_date,
play_count,
clear_count,
play_time,
total_judge,
}
}
}
/// PlayTime(seconds)
#[derive(Debug, Clone, Serialize)]
pub struct PlayTime(pub i32);
impl PlayTime {
pub fn new(seconds: i32) -> PlayTime {
PlayTime(seconds)
}
}
impl std::ops::Sub<PlayTime> for PlayTime {
type Output = PlayTime;
fn sub(self, rhs: PlayTime) -> PlayTime {
PlayTime::new(self.0 - rhs.0)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct TotalJudge(Judge);
impl TotalJudge {
pub fn new(judge: Judge) -> TotalJudge {
TotalJudge(judge)
}
pub fn judge(&self) -> &Judge {
&self.0
}
}
impl std::ops::Sub<TotalJudge> for TotalJudge {
type Output = TotalJudge;
fn sub(self, rhs: TotalJudge) -> TotalJudge {
TotalJudge::new(self.0 - rhs.0)
}
}
#[derive(Serialize)]
pub struct VisibleAccount {
pub id: UserId,
pub name: String,
}
|
extern crate rsa;
use rand::rngs::OsRng;
use rsa::{PaddingScheme, PublicKey, RSAPrivateKey, RSAPublicKey};
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub enum Outcome {
Success,
Failure,
}
#[wasm_bindgen]
pub struct RSAEncryptionManager {
priv_key: Option<RSAPrivateKey>,
pub_key: Option<RSAPublicKey>,
}
#[wasm_bindgen]
impl RSAEncryptionManager {
pub fn init() -> Self {
RSAEncryptionManager {
priv_key: None,
pub_key: None,
}
}
fn rsa_key_parser() -> Box<dyn Fn(&str) -> String> {
Box::new(|rsa_key: &str| -> String {
rsa_key
.lines()
.filter(|line| {
!line.starts_with("-")
&& !line.starts_with("Proc-Type:")
&& !line.starts_with("DEK-Info:")
})
.fold(String::new(), |mut data, line| {
data.push_str(&line);
data
})
})
}
pub fn load_pub_key(&mut self, pub_key: &str) -> Outcome {
let der_encoded = Self::rsa_key_parser()(pub_key);
let der_bytes = base64::decode(der_encoded).unwrap();
let rsa_public_key = RSAPublicKey::from_pkcs1(&der_bytes).unwrap();
self.pub_key = Some(rsa_public_key);
Outcome::Success
}
pub fn load_priv_key(&mut self, priv_key: &str) -> Outcome {
let der_encoded = Self::rsa_key_parser()(priv_key);
let der_bytes = base64::decode(der_encoded).unwrap();
let rsa_private_key = RSAPrivateKey::from_pkcs1(&der_bytes).unwrap();
let rsa_public_key = rsa_private_key.to_public_key();
self.priv_key = Some(rsa_private_key);
self.pub_key = Some(rsa_public_key);
Outcome::Success
}
pub fn encrypt(&self, msg: &[u8]) -> Option<Vec<u8>> {
let mut rng = OsRng;
let padding = PaddingScheme::new_pkcs1v15_encrypt();
match &self.pub_key {
Some(public_key) => {
let encrypted_msg = public_key.encrypt(&mut rng, padding, msg).unwrap();
Some(encrypted_msg)
}
_ => None,
}
}
pub fn decrypt(&self, msg: &[u8]) -> Option<Vec<u8>> {
let padding = PaddingScheme::new_pkcs1v15_encrypt();
match &self.priv_key {
Some(private_key) => {
let decrypted_msg = private_key.decrypt(padding, msg).unwrap();
Some(decrypted_msg)
}
_ => None,
}
}
}
|
use crate::config::{DEFAULT_COL_HEADER_HEIGHT, DEFAULT_ROW_HEADER_WIDTH};
use crate::{AxisMeasurementType, Remap};
use druid::{Cursor, Data, Point, Rect, Size};
use float_ord::FloatOrd;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::iter::Map;
use std::ops::{Add, RangeInclusive, Sub};
use std::rc::Rc;
use TableAxis::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Data, Ord, PartialOrd)]
pub enum TableAxis {
Rows, // Rows means the Y axis. A single row spans the X axis, but rows stack downwards.
Columns, // The X axis. A column is vertical, but columns go along horizontally
}
// Acts as an enum map
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct AxisPair<T: Debug> {
pub row: T,
pub col: T,
}
impl<T: Copy + Default + Debug> Copy for AxisPair<T> {}
impl<T: Data + Debug + Default> Data for AxisPair<T> {
fn same(&self, other: &Self) -> bool {
self.row.same(&other.row) && self.col.same(&other.col)
}
}
impl TableAxis {
pub fn cross_axis(&self) -> TableAxis {
match self {
Rows => Columns,
Columns => Rows,
}
}
pub fn length_from_size(&self, size: &Size) -> f64 {
match self {
Rows => size.height,
Columns => size.width,
}
}
pub fn main_pixel_from_point(&self, point: &Point) -> f64 {
match self {
Rows => point.y,
Columns => point.x,
}
}
pub fn pixels_from_rect(&self, rect: &Rect) -> (f64, f64) {
match self {
Rows => (rect.y0, rect.y1),
Columns => (rect.x0, rect.x1),
}
}
pub fn default_header_cross(&self) -> f64 {
match self {
Rows => DEFAULT_ROW_HEADER_WIDTH,
Columns => DEFAULT_COL_HEADER_HEIGHT,
}
}
pub fn coords(&self, main: f64, cross: f64) -> (f64, f64) {
match self {
Rows => (cross, main),
Columns => (main, cross),
}
}
pub fn size(&self, main: f64, cross: f64) -> Size {
self.coords(main, cross).into()
}
pub fn cell_origin(&self, main: f64, cross: f64) -> Point {
self.coords(main, cross).into()
}
pub fn resize_cursor(&self) -> &'static Cursor {
match self {
Rows => &Cursor::ResizeUpDown,
Columns => &Cursor::ResizeLeftRight,
}
}
}
#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq, Data, Default, Hash)]
pub struct VisIdx(pub usize);
#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq, Data, Default)]
pub struct VisOffset(pub isize);
#[derive(Clone, Copy, Debug, Ord, PartialOrd, Eq, PartialEq, Data, Default, Hash)]
pub struct LogIdx(pub usize);
impl From<usize> for LogIdx {
fn from(a: usize) -> Self {
Self(a)
}
}
impl From<LogIdx> for usize {
fn from(a: LogIdx) -> Self {
a.0
}
}
impl VisIdx {
// Todo work out how to support custom range
pub fn range_inc_iter(
from_inc: VisIdx,
to_inc: VisIdx,
) -> Map<RangeInclusive<usize>, fn(usize) -> VisIdx> {
((from_inc.0)..=(to_inc.0)).map(VisIdx)
}
pub(crate) fn ascending(a: VisIdx, b: VisIdx) -> (VisIdx, VisIdx) {
if a < b {
(a, b)
} else {
(b, a)
}
}
}
impl Add<VisOffset> for VisIdx {
type Output = Self;
fn add(self, rhs: VisOffset) -> Self::Output {
// TODO this is dodgy
VisIdx(((self.0 as isize) + rhs.0).max(0) as usize)
}
}
impl Sub<VisOffset> for VisIdx {
type Output = Self;
fn sub(self, rhs: VisOffset) -> Self::Output {
VisIdx(((self.0 as isize) - rhs.0).max(0) as usize)
}
}
#[derive(Debug, Clone)]
pub struct AxisMeasure {
inner: AxisMeasureInner,
version: u64,
}
impl Data for AxisMeasure {
fn same(&self, other: &Self) -> bool {
self.version == other.version
}
}
impl AxisMeasure {
pub fn new(amt: AxisMeasurementType, pixels_per_unit: f64) -> AxisMeasure {
AxisMeasure {
inner: match amt {
AxisMeasurementType::Uniform => {
AxisMeasureInner::Fixed(FixedAxisMeasure::new(pixels_per_unit))
}
AxisMeasurementType::Individual => AxisMeasureInner::Stored(Rc::new(RefCell::new(
StoredAxisMeasure::new(pixels_per_unit),
))),
},
version: 0,
}
}
}
#[derive(Debug, Clone)]
enum AxisMeasureInner {
Fixed(FixedAxisMeasure),
Stored(Rc<RefCell<StoredAxisMeasure>>),
}
use AxisMeasureInner::*;
impl AxisMeasure {
fn border(&self) -> f64 {
match &self.inner {
Fixed(f) => f.border,
Stored(s) => s.borrow().border(),
}
}
pub fn set_axis_properties(&mut self, border: f64, len: usize, remap: &Remap) {
if match &mut self.inner {
Fixed(f) => f.set_axis_properties(border, len, remap),
Stored(s) => s.borrow_mut().set_axis_properties(border, len, remap),
} {
self.version += 1
}
}
pub fn vis_range_from_pixels(&self, p0: f64, p1: f64) -> (VisIdx, VisIdx) {
let start = self.vis_idx_from_pixel(p0).unwrap_or(VisIdx(0));
let end = self
.vis_idx_from_pixel(p1)
.unwrap_or_else(|| self.last_vis_idx());
(start, end)
}
pub fn total_pixel_length(&self) -> f64 {
match &self.inner {
Fixed(f) => f.total_pixel_length(),
Stored(s) => s.borrow().total_pixel_length(),
}
}
fn last_vis_idx(&self) -> VisIdx {
let len = match &self.inner {
Fixed(f) => f.len,
Stored(s) => s.borrow().vis_pix_lengths.len(),
};
VisIdx(len - 1)
}
pub(crate) fn pixel_near_border(&self, pixel: f64) -> Option<VisIdx> {
let idx = self.vis_idx_from_pixel(pixel)?;
let idx_border_middle = self.first_pixel_from_vis(idx).unwrap_or(0.) - self.border() / 2.;
let next_border_middle = self
.first_pixel_from_vis(idx + VisOffset(1))
.unwrap_or_else(|| self.total_pixel_length())
- self.border() / 2.;
if f64::abs(pixel - idx_border_middle) < MOUSE_MOVE_EPSILON {
Some(idx)
} else if f64::abs(pixel - next_border_middle) < MOUSE_MOVE_EPSILON {
Some(idx + VisOffset(1))
} else {
None
}
}
pub fn vis_idx_from_pixel(&self, pixel: f64) -> Option<VisIdx> {
match &self.inner {
Fixed(f) => f.vis_idx_from_pixel(pixel),
Stored(s) => s.borrow().vis_idx_from_pixel(pixel),
}
}
pub fn first_pixel_from_vis(&self, idx: VisIdx) -> Option<f64> {
match &self.inner {
Fixed(f) => f.first_pixel_from_vis(idx),
Stored(s) => s.borrow().first_pixel_from_vis(idx),
}
}
pub fn pixels_length_for_vis(&self, idx: VisIdx) -> Option<f64> {
match &self.inner {
Fixed(f) => f.pixels_length_for_vis(idx),
Stored(s) => s.borrow().pixels_length_for_vis(idx),
}
}
pub fn can_resize(&self, idx: VisIdx) -> bool {
match &self.inner {
Fixed(f) => f.can_resize(idx),
Stored(s) => s.borrow().can_resize(idx),
}
}
pub fn set_far_pixel_for_vis(&mut self, idx: VisIdx, pixel: f64) {
// Check if changed
if match &mut self.inner {
Fixed(f) => f.set_far_pixel_for_vis(idx, pixel),
Stored(s) => s.borrow_mut().set_far_pixel_for_vis(idx, pixel),
} {
self.version += 1;
}
}
pub(crate) fn far_pixel_from_vis(&self, idx: VisIdx) -> Option<f64> {
self.first_pixel_from_vis(idx)
.map(|p| self.pixels_length_for_vis(idx).map(|l| p + l))
.flatten()
}
}
trait AxisMeasureT: Debug {
fn border(&self) -> f64;
fn total_pixel_length(&self) -> f64;
fn vis_idx_from_pixel(&self, pixel: f64) -> Option<VisIdx>;
fn first_pixel_from_vis(&self, idx: VisIdx) -> Option<f64>;
fn pixels_length_for_vis(&self, idx: VisIdx) -> Option<f64>;
fn can_resize(&self, idx: VisIdx) -> bool;
fn set_axis_properties(&mut self, border: f64, len: usize, remap: &Remap) -> bool;
fn set_far_pixel_for_vis(&mut self, idx: VisIdx, pixel: f64) -> bool;
}
#[derive(Debug, Clone, Copy)]
pub struct FixedAxisMeasure {
pixels_per_unit: f64,
border: f64,
len: usize,
}
impl FixedAxisMeasure {
pub fn new(pixels_per_unit: f64) -> Self {
FixedAxisMeasure {
pixels_per_unit,
border: 0.,
len: 0,
}
}
fn full_pixels_per_unit(&self) -> f64 {
self.pixels_per_unit + self.border
}
}
const MOUSE_MOVE_EPSILON: f64 = 3.;
impl AxisMeasureT for FixedAxisMeasure {
fn border(&self) -> f64 {
self.border
}
fn total_pixel_length(&self) -> f64 {
self.full_pixels_per_unit() * (self.len as f64)
}
fn vis_idx_from_pixel(&self, pixel: f64) -> Option<VisIdx> {
let index = (pixel / self.full_pixels_per_unit()).floor() as usize;
if index < self.len {
Some(VisIdx(index))
} else {
None
}
}
fn first_pixel_from_vis(&self, idx: VisIdx) -> Option<f64> {
if idx.0 < self.len {
Some((idx.0 as f64) * self.full_pixels_per_unit())
} else {
None
}
}
fn pixels_length_for_vis(&self, idx: VisIdx) -> Option<f64> {
if idx.0 < self.len {
Some(self.pixels_per_unit)
} else {
None
}
}
fn can_resize(&self, _idx: VisIdx) -> bool {
false
}
fn set_axis_properties(&mut self, border: f64, len: usize, _remap: &Remap) -> bool {
let changed = border != self.border || len != self.len;
self.border = border;
self.len = len;
// We don't care about remap as every item is the same... I think.
// TODO: Maybe we should care about the length?
changed
}
fn set_far_pixel_for_vis(&mut self, _idx: VisIdx, _pixel: f64) -> bool {
false
}
}
#[derive(Clone)]
pub struct StoredAxisMeasure {
remap: Remap,
log_pix_lengths: Vec<f64>,
vis_pix_lengths: Vec<f64>,
first_pixels: BTreeMap<VisIdx, f64>, // TODO newtypes
pixels_to_vis: BTreeMap<FloatOrd<f64>, VisIdx>,
default_pixels: f64,
border: f64,
total_pixel_length: f64,
}
impl Debug for StoredAxisMeasure {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
let fp = &self.first_pixels;
let pti = &self.pixels_to_vis;
fmt.debug_struct("StoredAxisMeasure")
.field("log_pix_lengths", &self.log_pix_lengths)
.field("vis_pix_lengths", &self.vis_pix_lengths)
.field("default_pixels", &self.default_pixels)
.field("border", &self.border)
.field("total_pixel_length", &self.total_pixel_length)
.field(
"first_pixels",
debug_fn!(|f| f.debug_map().entries(fp.iter()).finish()),
)
.field(
"pixels_to_index",
debug_fn!(|f| f
.debug_map()
.entries(pti.iter().map(|(k, v)| (k.0, v)))
.finish()),
)
.finish()
}
}
impl StoredAxisMeasure {
pub fn new(default_pixels: f64) -> Self {
StoredAxisMeasure {
remap: Remap::new(),
log_pix_lengths: Default::default(),
vis_pix_lengths: Default::default(),
first_pixels: Default::default(),
pixels_to_vis: Default::default(),
default_pixels,
border: 0.,
total_pixel_length: 0.,
}
}
fn build_maps(&mut self) {
let mut cur = 0.;
self.vis_pix_lengths.clear();
if self.remap.is_pristine() {
self.vis_pix_lengths
.extend_from_slice(&self.log_pix_lengths)
} else {
for vis_idx in VisIdx::range_inc_iter(
VisIdx(0),
self.remap.max_vis_idx(self.log_pix_lengths.len()),
) {
if let Some(log_idx) = self.remap.get_log_idx(vis_idx) {
self.vis_pix_lengths.push(self.log_pix_lengths[log_idx.0]);
}
}
}
self.first_pixels.clear();
self.pixels_to_vis.clear();
for (idx, pixels) in self.vis_pix_lengths.iter().enumerate() {
self.first_pixels.insert(VisIdx(idx), cur);
self.pixels_to_vis.insert(FloatOrd(cur), VisIdx(idx));
cur += pixels + self.border;
}
self.total_pixel_length = cur;
}
}
impl AxisMeasureT for StoredAxisMeasure {
fn border(&self) -> f64 {
self.border
}
fn total_pixel_length(&self) -> f64 {
self.total_pixel_length
}
fn vis_idx_from_pixel(&self, pixel: f64) -> Option<VisIdx> {
self.pixels_to_vis
.range(..=FloatOrd(pixel))
.next_back()
.map(|(_, v)| *v)
}
fn first_pixel_from_vis(&self, idx: VisIdx) -> Option<f64> {
self.first_pixels.get(&idx).copied()
}
fn pixels_length_for_vis(&self, idx: VisIdx) -> Option<f64> {
self.vis_pix_lengths.get(idx.0).copied()
}
fn can_resize(&self, _idx: VisIdx) -> bool {
true
}
fn set_axis_properties(&mut self, border: f64, len: usize, remap: &Remap) -> bool {
self.border = border;
self.remap = remap.clone(); // Todo: pass by ref where needed? Or make the measure own it
let old_len = self.log_pix_lengths.len();
match old_len.cmp(&len) {
Ordering::Greater => self.log_pix_lengths.truncate(len),
Ordering::Less => {
let extra = vec![self.default_pixels; len - old_len];
self.log_pix_lengths.extend_from_slice(&extra[..]);
assert_eq!(self.log_pix_lengths.len(), len);
}
_ => (),
}
self.build_maps();
true
}
fn set_far_pixel_for_vis(&mut self, vis_idx: VisIdx, pixel: f64) -> bool {
let length = f64::max(0., pixel - *self.first_pixels.get(&vis_idx).unwrap_or(&0.));
// Todo Option
if let Some(log_idx) = self.remap.get_log_idx(vis_idx) {
if let Some(place) = self.log_pix_lengths.get_mut(log_idx.0) {
if *place != length {
*place = length;
self.build_maps(); // TODO : modify efficiently instead of rebuilding
return true;
}
}
}
false
}
}
#[cfg(not)]
mod test {
use crate::axis_measure::{AxisMeasureT, VisIdx};
use crate::{FixedAxisMeasure, Remap, StoredAxisMeasure};
use float_ord::FloatOrd;
use std::collections::HashSet;
use std::fmt::Debug;
#[test]
fn fixed_axis() {
let mut ax = FixedAxisMeasure::new(99.0);
test_equal_sized(&mut ax);
assert_eq!(ax.set_far_pixel_for_vis(VisIdx(12), 34.), 99.);
}
fn test_equal_sized<AX: AxisMeasureT + Debug>(ax: &mut AX) {
ax.set_axis_properties(1.0, 4, &Remap::Pristine);
println!("Axis:{:#?}", ax);
assert_eq!(ax.total_pixel_length(), 400.);
assert_eq!(ax.vis_idx_from_pixel(350.0), Some(VisIdx(3)));
assert_eq!(ax.first_pixel_from_vis(VisIdx(0)), Some(0.));
assert_eq!(ax.vis_idx_from_pixel(0.0), Some(VisIdx(0)));
assert_eq!(ax.vis_idx_from_pixel(100.0), Some(VisIdx(1)));
assert_eq!(ax.vis_idx_from_pixel(1.0), Some(VisIdx(0)));
assert_eq!(ax.first_pixel_from_vis(VisIdx(1)), Some(100.0));
assert_eq!(
(199..=201)
.into_iter()
.map(|n| ax.vis_idx_from_pixel(n as f64).unwrap())
.collect::<Vec<VisIdx>>(),
vec![VisIdx(1), VisIdx(2), VisIdx(2)]
);
assert_eq!(
ax.vis_range_from_pixels(105.0, 295.0),
(VisIdx(1), VisIdx(2))
);
assert_eq!(
ax.vis_range_from_pixels(100.0, 300.0),
(VisIdx(1), VisIdx(3))
);
let lengths = (1usize..=3)
.into_iter()
.map(|i| FloatOrd(ax.pixels_length_for_vis(VisIdx(i)).unwrap()))
.collect::<HashSet<FloatOrd<f64>>>();
assert_eq!(lengths.len(), 1);
assert_eq!(lengths.iter().next().unwrap().0, 99.0)
}
#[test]
fn stored_axis() {
let mut ax = StoredAxisMeasure::new(99.);
test_equal_sized(&mut ax);
assert_eq!(ax.set_pixel_length_for_vis(VisIdx(2), 49.), 49.);
assert_eq!(ax.set_far_pixel_for_vis(VisIdx(1), 109.), 9.);
assert_eq!(ax.total_pixel_length(), 260.0)
}
}
|
use std::convert::TryInto;
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use num_bigint::RandBigInt;
use prime_factorization::{factorization, gen_prime, is_prime};
fn millar_rabin_bench(c: &mut Criterion) {
let mut rng = rand::thread_rng();
let cases = [16, 32, 64, 128, 1024, 2048, 4096];
for &bits in cases.iter() {
c.bench_function(&format!("millar_rabin {}bit", bits), |b| {
b.iter_batched(
|| rng.gen_biguint(bits),
|n| is_prime(&n),
BatchSize::LargeInput,
)
});
}
}
fn gen_semiprime(bits: usize) -> u128 {
let mut rng = rand::thread_rng();
(gen_prime(bits, &mut rng) * gen_prime(bits, &mut rng))
.try_into()
.unwrap()
}
fn factorization_bench(c: &mut Criterion) {
let cases = [8, 16, 24, 32, 40, 48];
for &bits in cases.iter() {
c.bench_function(&format!("factor semiprime {}bit", bits * 2), |b| {
b.iter_batched(
|| gen_semiprime(bits),
|n| factorization(n),
BatchSize::LargeInput,
)
});
}
}
criterion_group!(benches, millar_rabin_bench, factorization_bench);
criterion_main!(benches);
|
use crate::il::Expression as Expr;
use crate::il::*;
use crate::Error;
use falcon_capstone::capstone;
use falcon_capstone::capstone_sys::ppc_reg;
use std::cmp::Ordering;
/// Struct for dealing with x86 registers
pub struct PpcRegister {
name: &'static str,
// The capstone enum value for this register.
capstone_reg: ppc_reg,
/// The size of this register in bits
bits: usize,
}
impl PpcRegister {
// pub fn bits(&self) -> usize {
// self.bits
// }
pub fn name(&self) -> &str {
self.name
}
pub fn scalar(&self) -> Scalar {
scalar(self.name, self.bits)
}
pub fn expression(&self) -> Expr {
expr_scalar(self.name, self.bits)
}
}
const PPC_REGISTERS: &[PpcRegister] = &[
PpcRegister {
name: "r0",
capstone_reg: ppc_reg::PPC_REG_R0,
bits: 32,
},
PpcRegister {
name: "r1",
capstone_reg: ppc_reg::PPC_REG_R1,
bits: 32,
},
PpcRegister {
name: "r2",
capstone_reg: ppc_reg::PPC_REG_R2,
bits: 32,
},
PpcRegister {
name: "r3",
capstone_reg: ppc_reg::PPC_REG_R3,
bits: 32,
},
PpcRegister {
name: "r4",
capstone_reg: ppc_reg::PPC_REG_R4,
bits: 32,
},
PpcRegister {
name: "r5",
capstone_reg: ppc_reg::PPC_REG_R5,
bits: 32,
},
PpcRegister {
name: "r6",
capstone_reg: ppc_reg::PPC_REG_R6,
bits: 32,
},
PpcRegister {
name: "r7",
capstone_reg: ppc_reg::PPC_REG_R7,
bits: 32,
},
PpcRegister {
name: "r8",
capstone_reg: ppc_reg::PPC_REG_R8,
bits: 32,
},
PpcRegister {
name: "r9",
capstone_reg: ppc_reg::PPC_REG_R9,
bits: 32,
},
PpcRegister {
name: "r10",
capstone_reg: ppc_reg::PPC_REG_R10,
bits: 32,
},
PpcRegister {
name: "r11",
capstone_reg: ppc_reg::PPC_REG_R11,
bits: 32,
},
PpcRegister {
name: "r12",
capstone_reg: ppc_reg::PPC_REG_R12,
bits: 32,
},
PpcRegister {
name: "r13",
capstone_reg: ppc_reg::PPC_REG_R13,
bits: 32,
},
PpcRegister {
name: "r14",
capstone_reg: ppc_reg::PPC_REG_R14,
bits: 32,
},
PpcRegister {
name: "r15",
capstone_reg: ppc_reg::PPC_REG_R15,
bits: 32,
},
PpcRegister {
name: "r16",
capstone_reg: ppc_reg::PPC_REG_R16,
bits: 32,
},
PpcRegister {
name: "r17",
capstone_reg: ppc_reg::PPC_REG_R17,
bits: 32,
},
PpcRegister {
name: "r18",
capstone_reg: ppc_reg::PPC_REG_R18,
bits: 32,
},
PpcRegister {
name: "r19",
capstone_reg: ppc_reg::PPC_REG_R19,
bits: 32,
},
PpcRegister {
name: "r20",
capstone_reg: ppc_reg::PPC_REG_R20,
bits: 32,
},
PpcRegister {
name: "r21",
capstone_reg: ppc_reg::PPC_REG_R21,
bits: 32,
},
PpcRegister {
name: "r22",
capstone_reg: ppc_reg::PPC_REG_R22,
bits: 32,
},
PpcRegister {
name: "r23",
capstone_reg: ppc_reg::PPC_REG_R23,
bits: 32,
},
PpcRegister {
name: "r24",
capstone_reg: ppc_reg::PPC_REG_R24,
bits: 32,
},
PpcRegister {
name: "r25",
capstone_reg: ppc_reg::PPC_REG_R25,
bits: 32,
},
PpcRegister {
name: "r26",
capstone_reg: ppc_reg::PPC_REG_R26,
bits: 32,
},
PpcRegister {
name: "r27",
capstone_reg: ppc_reg::PPC_REG_R27,
bits: 32,
},
PpcRegister {
name: "r28",
capstone_reg: ppc_reg::PPC_REG_R28,
bits: 32,
},
PpcRegister {
name: "r29",
capstone_reg: ppc_reg::PPC_REG_R29,
bits: 32,
},
PpcRegister {
name: "r30",
capstone_reg: ppc_reg::PPC_REG_R30,
bits: 32,
},
PpcRegister {
name: "r31",
capstone_reg: ppc_reg::PPC_REG_R31,
bits: 32,
},
PpcRegister {
name: "cr0",
capstone_reg: ppc_reg::PPC_REG_CR0,
bits: 32,
},
PpcRegister {
name: "cr1",
capstone_reg: ppc_reg::PPC_REG_CR1,
bits: 32,
},
PpcRegister {
name: "cr2",
capstone_reg: ppc_reg::PPC_REG_CR2,
bits: 32,
},
PpcRegister {
name: "cr3",
capstone_reg: ppc_reg::PPC_REG_CR3,
bits: 32,
},
PpcRegister {
name: "cr4",
capstone_reg: ppc_reg::PPC_REG_CR4,
bits: 32,
},
PpcRegister {
name: "cr5",
capstone_reg: ppc_reg::PPC_REG_CR5,
bits: 32,
},
PpcRegister {
name: "cr6",
capstone_reg: ppc_reg::PPC_REG_CR6,
bits: 32,
},
PpcRegister {
name: "cr7",
capstone_reg: ppc_reg::PPC_REG_CR7,
bits: 32,
},
PpcRegister {
name: "ctr",
capstone_reg: ppc_reg::PPC_REG_CTR,
bits: 32,
},
];
/// Takes a capstone register enum and returns a `MIPSRegister`
pub fn get_register(capstone_id: ppc_reg) -> Result<&'static PpcRegister, Error> {
for register in PPC_REGISTERS.iter() {
if register.capstone_reg == capstone_id {
return Ok(register);
}
}
Err("Could not find register".into())
}
/// Returns the details section of a mips capstone instruction.
pub fn details(instruction: &capstone::Instr) -> Result<capstone::cs_ppc, Error> {
let detail = instruction.detail.as_ref().unwrap();
match detail.arch {
capstone::DetailsArch::PPC(x) => Ok(x),
_ => Err("Could not get instruction details".into()),
}
}
pub fn set_condition_register_signed(
block: &mut Block,
condition_register: Scalar,
lhs: Expression,
rhs: Expression,
) -> Result<(), Error> {
let lt = Expression::ite(
Expression::cmplts(lhs.clone(), rhs.clone())?,
expr_const(0b0100, 4),
expr_const(0b0000, 4),
)?;
let gt = Expression::ite(
Expression::cmplts(rhs.clone(), lhs.clone())?,
expr_const(0b0010, 4),
expr_const(0b0000, 4),
)?;
let eq = Expression::ite(
Expression::cmplts(rhs, lhs)?,
expr_const(0b0001, 4),
expr_const(0b0000, 4),
)?;
block.assign(scalar(format!("{}-lt", condition_register.name()), 1), lt);
block.assign(scalar(format!("{}-gt", condition_register.name()), 1), gt);
block.assign(scalar(format!("{}-eq", condition_register.name()), 1), eq);
Ok(())
}
pub fn set_condition_register_unsigned(
block: &mut Block,
condition_register: Scalar,
lhs: Expression,
rhs: Expression,
) -> Result<(), Error> {
let lt = Expression::ite(
Expression::cmpltu(lhs.clone(), rhs.clone())?,
expr_const(0b0100, 4),
expr_const(0b0000, 4),
)?;
let gt = Expression::ite(
Expression::cmpltu(rhs.clone(), lhs.clone())?,
expr_const(0b0010, 4),
expr_const(0b0000, 4),
)?;
let eq = Expression::ite(
Expression::cmpltu(rhs, lhs)?,
expr_const(0b0001, 4),
expr_const(0b0000, 4),
)?;
block.assign(scalar(format!("{}-lt", condition_register.name()), 1), lt);
block.assign(scalar(format!("{}-gt", condition_register.name()), 1), gt);
block.assign(scalar(format!("{}-eq", condition_register.name()), 1), eq);
Ok(())
}
pub fn set_condition_register_summary_overflow(
block: &mut Block,
condition_register: Scalar,
summary_overflow: Expression,
) {
block.assign(
scalar(format!("{}-so", condition_register.name()), 1),
summary_overflow,
);
}
pub fn condition_register_bit_to_flag(condition_register_bit: usize) -> Result<Scalar, Error> {
Ok(match condition_register_bit {
0 => scalar("cr0-lt", 1),
1 => scalar("cr0-gt", 1),
2 => scalar("cr0-eq", 1),
3 => scalar("cr0-so", 1),
4 => scalar("cr1-lt", 1),
5 => scalar("cr1-gt", 1),
6 => scalar("cr1-eq", 1),
7 => scalar("cr1-so", 1),
8 => scalar("cr2-lt", 1),
9 => scalar("cr2-gt", 1),
10 => scalar("cr2-eq", 1),
11 => scalar("cr2-so", 1),
12 => scalar("cr3-lt", 1),
13 => scalar("cr3-gt", 1),
14 => scalar("cr3-eq", 1),
15 => scalar("cr3-so", 1),
16 => scalar("cr4-lt", 1),
17 => scalar("cr4-gt", 1),
18 => scalar("cr4-eq", 1),
19 => scalar("cr4-so", 1),
20 => scalar("cr5-lt", 1),
21 => scalar("cr5-gt", 1),
22 => scalar("cr5-eq", 1),
23 => scalar("cr5-so", 1),
24 => scalar("cr6-lt", 1),
25 => scalar("cr6-gt", 1),
26 => scalar("cr6-eq", 1),
27 => scalar("cr6-so", 1),
28 => scalar("cr7-lt", 1),
29 => scalar("cr7-gt", 1),
30 => scalar("cr7-eq", 1),
31 => scalar("cr7-so", 1),
_ => return Err(Error::Custom("Invalid condition register bit".to_string())),
})
}
pub fn rlwinm_(
control_flow_graph: &mut ControlFlowGraph,
ra: Scalar,
rs: Expression,
sh: u64,
mb: u64,
me: u64,
) -> Result<(), Error> {
/*
- If the MB value is less than the ME value + 1, then the mask bits between
and including the starting point and the end point are set to ones. All
other bits are set to zeros.
- If the MB value is the same as the ME value + 1, then all 32 mask bits are
set to ones.
- If the MB value is greater than the ME value + 1, then all of the mask
bits between and including the ME value +1 and the MB value -1 are set to
zeros. All other bits are set to ones.
*/
let mask = match mb.cmp(&(me + 1)) {
Ordering::Less => {
let mb = 32 - mb;
let me = 32 - me;
let mask = (1 << (mb - me)) - 1;
mask << me
}
Ordering::Equal => 0xffff_ffff,
Ordering::Greater => {
let mb = 32 - mb;
let me = 32 - me;
let mask = (1 << (me - mb)) - 1;
let mask = mask << mb;
mask ^ 0xffff_ffff
}
};
let block_index = {
let block = control_flow_graph.new_block()?;
let value = Expr::rotl(rs, expr_const(sh, 32))?;
let value = Expr::and(value, expr_const(mask, 32))?;
block.assign(ra, value);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn add(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let rhs = get_register(detail.operands[2].reg())?.expression();
let block_index = {
let block = control_flow_graph.new_block()?;
let src = Expression::add(lhs, rhs)?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn addi(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let rhs = expr_const(detail.operands[2].imm() as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let src = Expression::add(lhs, rhs)?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn addis(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let rhs = expr_const((detail.operands[2].imm() as u64) << 16, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let src = Expression::add(lhs, rhs)?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn addze(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let block_index = {
let block = control_flow_graph.new_block()?;
let src = Expression::add(
lhs.clone(),
Expression::zext(lhs.bits(), expr_scalar("carry", 1))?,
)?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn bl(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = expr_const(detail.operands[0].imm() as u32 as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
block.assign(scalar("lr", 32), expr_const(instruction.address + 4, 32));
block.branch(dst);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn bclr(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let bo = detail.operands[0].imm() as usize;
let bi = detail.operands[1].imm() as usize;
let ctr = scalar("ctr", 32);
let branch_target = expr_scalar("lr", 32);
match bo & 0x1f {
0b00000 | 0b00001 | 0b00010 | 0b00011 => {
// Decrement the CTR, then branch if condition is false
let head_index = {
let block = control_flow_graph.new_block()?;
block.assign(
ctr.clone(),
Expression::sub(ctr.clone().into(), expr_const(1, ctr.bits()))?,
);
block.index()
};
let true_index = {
let block = control_flow_graph.new_block()?;
block.branch(branch_target);
block.index()
};
let false_index = { control_flow_graph.new_block()?.index() };
let false_condition: Expression = condition_register_bit_to_flag(bi)?.into();
let true_condition = Expression::cmpeq(false_condition.clone(), expr_const(0, 1))?;
control_flow_graph.conditional_edge(head_index, true_index, true_condition)?;
control_flow_graph.conditional_edge(head_index, false_index, false_condition)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(false_index)?;
}
0b00100 | 0b00101 | 0b00110 | 0b00111 => {
// Branch if the condition is false
let head_index = { control_flow_graph.new_block()?.index() };
let true_index = {
let block = control_flow_graph.new_block()?;
block.branch(branch_target);
block.index()
};
let false_index = { control_flow_graph.new_block()?.index() };
let false_condition: Expression = condition_register_bit_to_flag(bi)?.into();
let true_condition = Expression::cmpeq(false_condition.clone(), expr_const(0, 1))?;
control_flow_graph.conditional_edge(head_index, true_index, true_condition)?;
control_flow_graph.conditional_edge(head_index, false_index, false_condition)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(false_index)?;
}
0b01000 | 0b01001 | 0b01010 | 0b01011 => {
// Decrement the CTR, then branch if condition is true
let head_index = {
let block = control_flow_graph.new_block()?;
block.assign(
ctr.clone(),
Expression::sub(ctr.clone().into(), expr_const(1, ctr.bits()))?,
);
block.index()
};
let true_index = {
let block = control_flow_graph.new_block()?;
block.branch(branch_target);
block.index()
};
let false_index = { control_flow_graph.new_block()?.index() };
let true_condition: Expression = condition_register_bit_to_flag(bi)?.into();
let false_condition = Expression::cmpeq(true_condition.clone(), expr_const(0, 1))?;
control_flow_graph.conditional_edge(head_index, true_index, true_condition)?;
control_flow_graph.conditional_edge(head_index, false_index, false_condition)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(false_index)?;
}
0b01100 | 0b01101 | 0b01110 | 0b01111 => {
// Branch if the condition is true
let head_index = { control_flow_graph.new_block()?.index() };
let true_index = {
let block = control_flow_graph.new_block()?;
block.branch(branch_target);
block.index()
};
let false_index = { control_flow_graph.new_block()?.index() };
let true_condition: Expression = condition_register_bit_to_flag(bi)?.into();
let false_condition = Expression::cmpeq(true_condition.clone(), expr_const(0, 1))?;
control_flow_graph.conditional_edge(head_index, true_index, true_condition)?;
control_flow_graph.conditional_edge(head_index, false_index, false_condition)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(false_index)?;
}
0b10000 | 0b10001 | 0b11000 | 0b11001 => {
// Decrement the CTF, then branch if CTR != 0
let head_index = {
let block = control_flow_graph.new_block()?;
block.assign(
ctr.clone(),
Expression::sub(ctr.clone().into(), expr_const(1, ctr.bits()))?,
);
block.index()
};
let true_index = {
let block = control_flow_graph.new_block()?;
block.branch(branch_target);
block.index()
};
let false_index = { control_flow_graph.new_block()?.index() };
let true_condition = Expression::cmpneq(ctr.clone().into(), expr_const(0, ctr.bits()))?;
let false_condition = Expression::cmpeq(ctr.clone().into(), expr_const(0, ctr.bits()))?;
control_flow_graph.conditional_edge(head_index, true_index, true_condition)?;
control_flow_graph.conditional_edge(head_index, false_index, false_condition)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(false_index)?;
}
0b10010 | 0b10011 | 0b11010 | 0b11011 => {
// Decrement the CTR, then branch if CTR == 0
let head_index = {
let block = control_flow_graph.new_block()?;
block.assign(
ctr.clone(),
Expression::sub(ctr.clone().into(), expr_const(1, ctr.bits()))?,
);
block.index()
};
let true_index = {
let block = control_flow_graph.new_block()?;
block.branch(branch_target);
block.index()
};
let false_index = { control_flow_graph.new_block()?.index() };
let true_condition = Expression::cmpeq(ctr.clone().into(), expr_const(0, ctr.bits()))?;
let false_condition =
Expression::cmpneq(ctr.clone().into(), expr_const(0, ctr.bits()))?;
control_flow_graph.conditional_edge(head_index, true_index, true_condition)?;
control_flow_graph.conditional_edge(head_index, false_index, false_condition)?;
control_flow_graph.set_entry(head_index)?;
control_flow_graph.set_exit(false_index)?;
}
0b10100 | 0b10101 | 0b10110 | 0b10111 | 0b11100 | 0b11101 | 0b11110 | 0b11111 => {
// Always branch
let block_index = {
let block = control_flow_graph.new_block()?;
block.branch(branch_target);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
}
_ => return Err(Error::Custom(format!("Invalid bo for bclr: {}", bo))),
}
Ok(())
}
pub fn bctr(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<(), Error> {
// get operands
let block_index = {
let block = control_flow_graph.new_block()?;
block.branch(expr_scalar("ctr", 32));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cmpwi(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let cr = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let rhs = expr_const(detail.operands[2].imm() as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
set_condition_register_signed(block, cr, lhs, rhs)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn cmplwi(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let cr = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let rhs = expr_const(detail.operands[2].imm() as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
set_condition_register_unsigned(block, cr, lhs, rhs)?;
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn lbz(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let base = get_register(detail.operands[1].mem().base)?.expression();
let offset = detail.operands[1].mem().disp;
let offset = expr_const(offset as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let ea = Expr::add(offset, base)?;
let temp = Scalar::temp(instruction.address, 8);
block.load(temp.clone(), ea);
block.assign(dst.clone(), Expression::zext(dst.bits(), temp.into())?);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn li(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let src = expr_const(detail.operands[1].imm() as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn lwz(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let base = get_register(detail.operands[1].mem().base)?.expression();
let offset = detail.operands[1].mem().disp;
let offset = expr_const(offset as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let ea = Expr::add(offset, base)?;
block.load(dst, ea);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn lwzu(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let base = get_register(detail.operands[1].mem().base)?.scalar();
let offset = detail.operands[1].mem().disp;
let offset = expr_const(offset as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let ea = Expr::add(offset, base.clone().into())?;
block.load(dst, ea.clone());
block.assign(base, ea);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn lis(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let src = expr_const(detail.operands[1].imm() as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let src = Expression::or(
Expression::and(src.clone(), expr_const(0x0000_ffff, 32))?,
Expression::shl(src, expr_const(16, 32))?,
)?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn mr(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let src = get_register(detail.operands[1].reg())?.expression();
let block_index = {
let block = control_flow_graph.new_block()?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn mflr(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let block_index = {
let block = control_flow_graph.new_block()?;
block.assign(dst, expr_scalar("lr", 32));
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn mtctr(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let src = expr_const(detail.operands[1].imm() as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn mtlr(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let src = get_register(detail.operands[0].reg())?.expression();
let block_index = {
let block = control_flow_graph.new_block()?;
block.assign(scalar("lr", 32), src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn nop(control_flow_graph: &mut ControlFlowGraph, _: &capstone::Instr) -> Result<(), Error> {
let block_index = {
let block = control_flow_graph.new_block()?;
block.nop();
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn rlwinm(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
let ra = get_register(detail.operands[0].reg())?.scalar();
let rs = get_register(detail.operands[1].reg())?.expression();
let sh = detail.operands[2].imm() as u64;
let mb = detail.operands[3].imm() as u64;
let me = detail.operands[4].imm() as u64;
rlwinm_(control_flow_graph, ra, rs, sh, mb, me)
}
pub fn slwi(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
let ra = get_register(detail.operands[0].reg())?.scalar();
let rs = get_register(detail.operands[1].reg())?.expression();
let sh = detail.operands[2].imm() as u64;
rlwinm_(control_flow_graph, ra, rs, sh, 0, 31 - sh)
}
pub fn srawi(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let rhs = expr_const(detail.operands[2].imm() as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
block.assign(dst, Expression::sra(lhs, rhs)?);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn stw(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let src = get_register(detail.operands[0].reg())?.expression();
let base = get_register(detail.operands[1].mem().base)?.expression();
let offset = detail.operands[1].mem().disp;
let offset = expr_const(offset as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let ea = Expr::add(offset, base)?;
block.store(ea, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn stmw(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let base = get_register(detail.operands[1].mem().base)?.expression();
let offset = detail.operands[1].mem().disp;
let mut offset = const_(offset as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let mut start_register: Option<usize> = None;
for (i, reg) in PPC_REGISTERS.iter().enumerate() {
if reg.capstone_reg == detail.operands[0].reg() {
start_register = Some(i);
break;
}
}
let mut i = match start_register {
Some(i) => i,
None => {
return Err(Error::Custom(
"Failed to find start register for stmwu".to_string(),
))
}
};
while PPC_REGISTERS[i].capstone_reg != ppc_reg::PPC_REG_CR0 {
let register = PPC_REGISTERS[i].expression();
let ea = Expr::add(offset.clone().into(), base.clone())?;
block.store(ea, register);
offset = offset.add(&const_(4, offset.bits()))?;
i += 1;
}
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn stwu(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let src = get_register(detail.operands[0].reg())?.expression();
let base = get_register(detail.operands[1].mem().base)?.scalar();
let offset = detail.operands[1].mem().disp;
let offset = expr_const(offset as u64, 32);
let block_index = {
let block = control_flow_graph.new_block()?;
let ea = Expr::add(offset, base.clone().into())?;
block.store(ea.clone(), src);
block.assign(base, ea);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
pub fn subf(
control_flow_graph: &mut ControlFlowGraph,
instruction: &capstone::Instr,
) -> Result<(), Error> {
let detail = details(instruction)?;
// get operands
let dst = get_register(detail.operands[0].reg())?.scalar();
let lhs = get_register(detail.operands[1].reg())?.expression();
let rhs = get_register(detail.operands[2].reg())?.expression();
let block_index = {
let block = control_flow_graph.new_block()?;
let src = Expression::add(
Expression::add(Expression::xor(lhs, expr_const(0xffff_ffff, 32))?, rhs)?,
expr_const(1, 32),
)?;
block.assign(dst, src);
block.index()
};
control_flow_graph.set_entry(block_index)?;
control_flow_graph.set_exit(block_index)?;
Ok(())
}
|
/// Contains the conversion logic from a `trace::span::Span` to `thrift::jaeger::Span`
use crate::thrift::jaeger::{self, SpanRef};
use trace::{
ctx::TraceId,
span::{MetaValue, Span, SpanEvent, SpanStatus},
};
/// Split [`TraceId`] into high and low part.
fn split_trace_id(trace_id: TraceId) -> (i64, i64) {
let trace_id = trace_id.get();
let trace_id_high = (trace_id >> 64) as i64;
let trace_id_low = trace_id as i64;
(trace_id_high, trace_id_low)
}
impl From<Span> for jaeger::Span {
fn from(mut s: Span) -> Self {
let (trace_id_high, trace_id_low) = split_trace_id(s.ctx.trace_id);
// A parent span id of 0 indicates no parent span ID (span IDs are non-zero)
let parent_span_id = s.ctx.parent_span_id.map(|id| id.get()).unwrap_or_default() as i64;
let (start_time, duration) = match (s.start, s.end) {
(Some(start), Some(end)) => (
start.timestamp_nanos() / 1000,
(end - start).num_microseconds().expect("no overflow"),
),
(Some(start), _) => (start.timestamp_nanos() / 1000, 0),
_ => (0, 0),
};
// These don't appear to be standardised, however, the jaeger UI treats
// the presence of an "error" tag as indicating an error
match s.status {
SpanStatus::Ok => {
s.metadata
.entry("ok".into())
.or_insert(MetaValue::Bool(true));
}
SpanStatus::Err => {
s.metadata
.entry("error".into())
.or_insert(MetaValue::Bool(true));
}
SpanStatus::Unknown => {}
}
let tags = match s.metadata.is_empty() {
true => None,
false => Some(
s.metadata
.into_iter()
.map(|(name, value)| tag_from_meta(name.to_string(), value))
.collect(),
),
};
let logs = match s.events.is_empty() {
true => None,
false => Some(s.events.into_iter().map(Into::into).collect()),
};
let references = if s.ctx.links.is_empty() {
None
} else {
Some(
s.ctx
.links
.into_iter()
.map(|(trace_id, span_id)| {
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk_exporters/jaeger.md#links
let (trace_id_high, trace_id_low) = split_trace_id(trace_id);
SpanRef {
ref_type: jaeger::SpanRefType::FollowsFrom,
trace_id_high,
trace_id_low,
span_id: span_id.get() as i64,
}
})
.collect(),
)
};
Self {
trace_id_low,
trace_id_high,
span_id: s.ctx.span_id.get() as i64,
parent_span_id,
operation_name: s.name.to_string(),
references,
flags: 0,
start_time,
duration,
tags,
logs,
}
}
}
impl From<SpanEvent> for jaeger::Log {
fn from(event: SpanEvent) -> Self {
Self {
timestamp: event.time.timestamp_nanos() / 1000,
fields: vec![jaeger::Tag {
key: "event".to_string(),
v_type: jaeger::TagType::String,
v_str: Some(event.msg.to_string()),
v_double: None,
v_bool: None,
v_long: None,
v_binary: None,
}],
}
}
}
fn tag_from_meta(key: String, value: MetaValue) -> jaeger::Tag {
let mut tag = jaeger::Tag {
key,
v_type: jaeger::TagType::String,
v_str: None,
v_double: None,
v_bool: None,
v_long: None,
v_binary: None,
};
match value {
MetaValue::String(v) => {
tag.v_type = jaeger::TagType::String;
tag.v_str = Some(v.to_string())
}
MetaValue::Float(v) => {
tag.v_type = jaeger::TagType::Double;
tag.v_double = Some(v.into())
}
MetaValue::Int(v) => {
tag.v_type = jaeger::TagType::Long;
tag.v_long = Some(v)
}
MetaValue::Bool(v) => {
tag.v_type = jaeger::TagType::Bool;
tag.v_bool = Some(v)
}
};
tag
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_split_trace_id_integer_conversion() {
// test case from
// https://github.com/open-telemetry/opentelemetry-specification/blob/639c7443e78800b085d2c9826d1b300f5e81fded/specification/trace/sdk_exporters/jaeger.md#ids
let trace_id = TraceId::new(0xFF00000000000000).unwrap();
let (high, low) = split_trace_id(trace_id);
assert_eq!(high, 0);
assert_eq!(low, -72057594037927936);
}
}
|
pub use __cargo_equip::prelude::*;
use proconio::{input, marker::Usize1};
use union_find::UnionFind;
fn main() {
input! {
n: usize,
m: usize,
abcd: [(Usize1, char, Usize1, char); m],
};
let vv = |v: usize, c: char| {
if c == 'R' {
v
} else {
n + v
}
};
let mut uf = UnionFind::new(n * 2);
for i in 0..n {
uf.unite(vv(i, 'R'), vv(i, 'B'));
}
for &(a, b, c, d) in &abcd {
uf.unite(vv(a, b), vv(c, d));
}
let mut e = vec![0; n * 2];
for &(a, b, _, _) in &abcd {
e[uf.find(vv(a, b))] += 1;
}
let mut ans1 = 0;
let mut ans2 = 0;
for i in 0..n * 2 {
if uf.find(i) == i {
if uf.get_size(i) == e[i] * 2 {
ans1 += 1;
} else {
ans2 += 1;
}
}
}
println!("{} {}", ans1, ans2);
}
// The following code was expanded by `cargo-equip`.
/// # Bundled libraries
///
/// - `union_find 0.1.0 (git+https://github.com/ia7ck/rust-competitive-programming#5273e2d6570a53eaaf99a41e2dfcc797c918a6ea)` licensed under **missing** as `crate::__cargo_equip::crates::union_find`
#[cfg_attr(any(), rustfmt::skip)]
#[allow(unused)]
mod __cargo_equip {
pub(crate) mod crates {
pub mod union_find {pub struct UnionFind{par:Vec<usize>,size:Vec<usize>,}impl UnionFind{pub fn new(n:usize)->UnionFind{UnionFind{par:(0..n).collect(),size:vec![1;n],}}pub fn find(&mut self,i:usize)->usize{if self.par[i]!=i{self.par[i]=self.find(self.par[i]);}self.par[i]}pub fn unite(&mut self,i:usize,j:usize){let i=self.find(i);let j=self.find(j);if i==j{return;}let(i,j)=if self.size[i]>=self.size[j]{(i,j)}else{(j,i)};self.par[j]=i;self.size[i]+=self.size[j];}pub fn get_size(&mut self,i:usize)->usize{let p=self.find(i);self.size[p]}pub fn same(&mut self,i:usize,j:usize)->bool{self.find(i)==self.find(j)}}}
}
pub(crate) mod macros {
pub mod union_find {}
}
pub(crate) mod prelude {pub use crate::__cargo_equip::crates::*;}
mod preludes {
pub mod union_find {}
}
}
|
use bootstrap::window::Window;
use gl;
use gl::*;
use std::cell::RefCell;
use std::ffi::CStr;
use std::ptr;
use std::rc::Rc;
#[derive(Debug)]
pub struct Context {
raw: gl::Context,
inner: Rc<RefCell<ContextInner>>,
}
impl Context {
/// Creates a new rendering context for the specified window.
pub fn from_window(window: &Window) -> Result<Context, Error> {
let device_context = window.platform().device_context();
Context::from_device_context(device_context)
}
/// Initializes global OpenGL state and creates the OpenGL context needed to perform rendering.
fn from_device_context(device_context: gl::DeviceContext) -> Result<Context, Error> {
pub extern "system" fn debug_callback(
source: DebugSource,
message_type: DebugType,
object_id: u32,
severity: DebugSeverity,
_length: i32,
message: *const u8,
_user_param: *mut ()
) {
use std::ffi::CStr;
let message = unsafe { CStr::from_ptr(message as *const _) }.to_string_lossy();
println!(
r#"Recieved some kind of debug message.
source: {:?},
type: {:?},
object_id: 0x{:x},
severity: {:?},
message: {}"#,
source,
message_type,
object_id,
severity,
message);
}
unsafe {
let context =
gl::create_context(device_context)
.ok_or(Error::UnableToCreateRenderContext)?;
{
let _guard = ::context::ContextGuard::new(context);
gl::enable(ServerCapability::DebugOutput);
gl::debug_message_callback(Some(debug_callback), ptr::null_mut());
let vendor = CStr::from_ptr(gl::get_string(StringName::Vendor)).to_str().unwrap();
let renderer = CStr::from_ptr(gl::get_string(StringName::Renderer)).to_str().unwrap();
let version = CStr::from_ptr(gl::get_string(StringName::Version)).to_str().unwrap();
let glsl_version = CStr::from_ptr(gl::get_string(StringName::ShadingLanguageVersion)).to_str().unwrap();
println!("OpenGL Information:");
println!("\tvendor: {}", vendor);
println!("\trenderer: {}", renderer);
println!("\tversion: {}", version);
println!("\tglsl version: {}", glsl_version);
// Load a bunch of proc pointers for funsies.
gl::get_attrib_location::load();
gl::gen_vertex_arrays::load();
gl::enable(ServerCapability::FramebufferSrgb);
gl::enable(ServerCapability::Blend);
}
let inner = Rc::new(RefCell::new(ContextInner {
raw: context,
server_srgb_enabled: true,
server_cull_enabled: false,
server_depth_test_enabled: false,
server_blend_enabled: true,
bound_vertex_array: None,
front_polygon_mode: PolygonMode::default(),
back_polygon_mode: PolygonMode::default(),
program: None,
cull_mode: Face::default(),
winding_order: WindingOrder::default(),
depth_test: Comparison::Less,
blend: Default::default(),
}));
Ok(Context {
raw: context,
inner: inner,
})
}
}
/// TODO: Take clear mask (and values) as parameters.
pub fn clear(&self) {
let _guard = ::context::ContextGuard::new(self.raw);
unsafe { gl::clear(ClearBufferMask::Color | ClearBufferMask::Depth); }
}
pub fn swap_buffers(&self) {
let _guard = ::context::ContextGuard::new(self.raw);
unsafe { gl::platform::swap_buffers(self.raw); }
}
pub(crate) fn raw(&self) -> gl::Context {
self.raw
}
pub(crate) fn inner(&self) -> Rc<RefCell<ContextInner>> {
self.inner.clone()
}
}
#[derive(Debug)]
pub(crate) struct ContextInner {
raw: gl::Context,
server_srgb_enabled: bool,
server_cull_enabled: bool,
server_depth_test_enabled: bool,
server_blend_enabled: bool,
bound_vertex_array: Option<VertexArrayName>,
front_polygon_mode: PolygonMode,
back_polygon_mode: PolygonMode,
program: Option<ProgramObject>,
cull_mode: Face,
winding_order: WindingOrder,
depth_test: Comparison,
blend: (SourceFactor, DestFactor),
}
impl ContextInner {
pub(crate) fn raw(&self) -> gl::Context {
self.raw
}
pub(crate) fn bind_vertex_array(&mut self, vertex_array_name: VertexArrayName) {
if Some(vertex_array_name) != self.bound_vertex_array {
unsafe { gl::bind_vertex_array(vertex_array_name); }
self.bound_vertex_array = Some(vertex_array_name);
}
}
pub(crate) fn unbind_vertex_array(&mut self, vertex_array_name: VertexArrayName) {
if Some(vertex_array_name) == self.bound_vertex_array {
unsafe { gl::bind_vertex_array(VertexArrayName::null()); }
self.bound_vertex_array = None;
}
}
pub(crate) fn polygon_mode(&mut self, mode: PolygonMode) {
if mode != self.front_polygon_mode || mode != self.back_polygon_mode {
unsafe { gl::polygon_mode(Face::FrontAndBack, mode); }
self.front_polygon_mode = mode;
self.back_polygon_mode = mode;
}
}
pub(crate) fn use_program(&mut self, program: Option<ProgramObject>) {
if program != self.program {
match program {
Some(program) => unsafe { gl::use_program(program); },
None => unsafe { gl::use_program(ProgramObject::null()); },
}
self.program = program;
}
}
pub(crate) fn enable_server_cull(&mut self, enabled: bool) {
if enabled != self.server_cull_enabled {
match enabled {
true => unsafe { gl::enable(ServerCapability::CullFace); },
false => unsafe { gl::disable(ServerCapability::CullFace); },
}
self.server_cull_enabled = enabled;
}
}
pub(crate) fn enable_server_depth_test(&mut self, enabled: bool) {
if enabled != self.server_depth_test_enabled {
match enabled {
true => unsafe { gl::enable(ServerCapability::DepthTest); },
false => unsafe { gl::disable(ServerCapability::DepthTest); },
}
self.server_depth_test_enabled = enabled;
}
}
pub(crate) fn cull_mode(&mut self, face: Face) {
if self.cull_mode != face {
unsafe { gl::cull_face(face); }
self.cull_mode = face;
}
}
pub(crate) fn winding_order(&mut self, winding_order: WindingOrder) {
if self.winding_order != winding_order {
unsafe { gl::front_face(winding_order); }
self.winding_order = winding_order;
}
}
pub(crate) fn depth_test(&mut self, comparison: Comparison) {
if comparison != self.depth_test {
unsafe { gl::depth_func(comparison); }
self.depth_test = comparison;
}
}
pub(crate) fn blend(&mut self, source_factor: SourceFactor, dest_factor: DestFactor) {
if (source_factor, dest_factor) != self.blend {
unsafe { gl::blend_func(source_factor, dest_factor); }
self.blend = (source_factor, dest_factor);
}
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
gl::make_current(self.raw);
gl::debug_message_callback(None, ptr::null_mut());
gl::destroy_context(self.raw)
}
}
}
#[derive(Debug)]
pub enum Error {
/// Indicates that the program was unable to find an active device context.
///
/// This error can occur if no compatible window is active, or if the program was unable to
/// find the device context for the window.
NoDeviceContext,
/// Indicates that the program failed the create the rendering context.
///
/// This might happen because reasons.
UnableToCreateRenderContext,
}
#[derive(Debug)]
pub(crate) struct ContextGuard(gl::Context);
impl ContextGuard {
pub fn new(context: gl::Context) -> ContextGuard {
let old = unsafe { gl::make_current(context) };
ContextGuard(old)
}
}
impl Drop for ContextGuard {
fn drop(&mut self) {
// TODO: Assert that the context is still current.
unsafe { gl::make_current(self.0); }
}
}
|
/**
* 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::storage::bv_storage::*;
use crate::storage::primitive_storage::PrimitiveStorage;
use crate::storage::Bounded;
use crate::world::Interceptable;
pub struct Collector {
pub bounded_elements: Vec<Box<Bounded>>,
pub elements: Vec<Box<Interceptable + 'static>>,
}
impl<'a> Collector {
pub fn new() -> Self {
Collector {
bounded_elements: Vec::new(),
elements: Vec::new(),
}
}
pub fn add(&mut self, element: Box<Interceptable>) -> () {
self.elements.push(element);
}
pub fn add_bounded(&mut self, element: Box<Bounded>) -> () {
self.bounded_elements.push(element);
}
pub fn into_storage(mut self) -> Box<Interceptable> {
let bounded_elements = Box::new(BVStorage::new(self.bounded_elements));
self.elements.push(bounded_elements);
//self.elements.append(&mut bounded2interceptable(self.bounded_elements));
Box::new(PrimitiveStorage {
elements: self.elements,
})
}
}
|
// Copyright 2020-2021, The Tremor 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.
use crate::connectors::qos;
use crate::errors::Result;
use crate::sink::prelude::*;
use simd_json_derive::Serialize;
pub struct Cb {}
///
/// CB event provoking offramp for testing sources and operators for their handling of CB events
///
/// Put a single string or an array of strings under the `cb` key into the meta or value to trigger the corresponding events.
///
/// Examples: `{"cb": "ack"}` or `{"cb": ["fail", "close"]}`
///
impl offramp::Impl for Cb {
fn from_config(_config: &Option<OpConfig>) -> Result<Box<dyn Offramp>> {
Ok(SinkManager::new_box(Self {}))
}
}
#[async_trait::async_trait]
impl Sink for Cb {
async fn on_event(
&mut self,
_input: &str,
_codec: &mut dyn Codec,
_codec_map: &halfbrown::HashMap<String, Box<dyn Codec>>,
event: Event,
) -> ResultVec {
let mut res = Vec::with_capacity(event.len());
for (value, meta) in event.value_meta_iter() {
// let event = event.clone();
debug!(
"[Sink::CB] {} {}",
&event.id.event_id(),
value.json_string()?
);
if let Some(cb) = meta.get("cb").or_else(|| value.get("cb")) {
let cb_cmds = if let Some(array) = cb.as_array() {
array
.iter()
.filter_map(|v| v.as_str().map(ToString::to_string))
.collect()
} else if let Some(str) = cb.as_str() {
vec![str.to_string()]
} else {
vec![]
};
// Acknowledgement tracking
let mut insight = event.clone();
if cb_cmds.contains(&"ack".to_string()) {
res.push(qos::ack(&mut insight));
} else if cb_cmds.contains(&"fail".to_string()) {
res.push(qos::fail(&mut insight));
}
// Circuit breaker tracking
let mut insight = event.clone();
if cb_cmds.contains(&"close".to_string())
|| cb_cmds.contains(&"trigger".to_string())
{
res.push(qos::close(&mut insight));
} else if cb_cmds.contains(&"open".to_string())
|| cb_cmds.contains(&"restore".to_string())
{
res.push(qos::open(&mut insight));
}
}
}
Ok(Some(res))
}
async fn on_signal(&mut self, _signal: Event) -> ResultVec {
// TODO: add signal reaction via config
Ok(None)
}
#[allow(clippy::too_many_arguments)]
async fn init(
&mut self,
_sink_uid: u64,
_sink_url: &TremorUrl,
_codec: &dyn Codec,
_codec_map: &halfbrown::HashMap<String, Box<dyn Codec>>,
_processors: Processors<'_>,
_is_linked: bool,
_reply_channel: Sender<Reply>,
) -> Result<()> {
Ok(())
}
#[cfg(not(tarpaulin_include))]
fn is_active(&self) -> bool {
true
}
#[cfg(not(tarpaulin_include))]
fn auto_ack(&self) -> bool {
false
}
#[cfg(not(tarpaulin_include))]
fn default_codec(&self) -> &str {
"json"
}
async fn terminate(&mut self) {}
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::BorrowMut;
use tremor_pipeline::{EventId, OpMeta};
#[async_std::test]
async fn cb_meta() -> Result<()> {
let mut codec = crate::codec::lookup("json")?;
let mut cb = Cb {};
let url = TremorUrl::parse("/offramp/cb/instance")?;
let codec_map = halfbrown::HashMap::new();
let (tx, _rx) = async_channel::bounded(1);
let in_ = "IN";
cb.init(
0x00,
&url,
codec.as_ref(),
&codec_map,
Processors::default(),
false,
tx,
)
.await?;
let mut data = Value::object_with_capacity(1);
data.insert("cb", "ack")?;
let id = EventId::new(1, 2, 3);
let origin_uri = Some(EventOriginUri {
uid: 1,
scheme: "test".to_string(),
host: "localhost".to_string(),
port: Some(1),
path: vec![],
});
let mut op_meta = OpMeta::default();
op_meta.insert(1, "foo");
let event = Event {
id: id.clone(),
data: (data, Value::null()).into(),
op_meta: op_meta.clone(),
origin_uri: origin_uri.clone(),
..Event::default()
};
let c: &mut dyn Codec = codec.borrow_mut();
let res = cb.on_event(in_, c, &codec_map, event).await?;
assert!(res.is_some(), "got nothing back");
if let Some(replies) = res {
assert_eq!(1, replies.len());
if let Some(Reply::Insight(insight)) = replies.first() {
assert_eq!(CbAction::Ack, insight.cb);
assert_eq!(id, insight.id);
assert_eq!(op_meta, insight.op_meta);
assert_eq!(origin_uri, insight.origin_uri);
} else {
assert!(
false,
"expected to get anm insight back. Got {:?}",
replies.first()
);
}
}
// meta takes precedence
let mut meta = Value::object_with_capacity(1);
meta.insert("cb", "fail")?;
let mut data = Value::object_with_capacity(1);
data.insert("cb", "ack")?;
let event = Event {
id: id.clone(),
data: (data, meta).into(),
op_meta: op_meta.clone(),
origin_uri: origin_uri.clone(),
..Event::default()
};
let c: &mut dyn Codec = codec.borrow_mut();
let res = cb.on_event(in_, c, &codec_map, event).await?;
assert!(res.is_some(), "got nothing back");
if let Some(replies) = res {
assert_eq!(1, replies.len());
if let Some(Reply::Insight(insight)) = replies.first() {
assert_eq!(CbAction::Fail, insight.cb);
assert_eq!(id, insight.id);
assert_eq!(op_meta, insight.op_meta);
assert_eq!(origin_uri, insight.origin_uri);
} else {
assert!(
false,
"expected to get anm insight back. Got {:?}",
replies.first()
);
}
}
// array data - second ack/fail will be ignored, just one from ack/fail or open/close (trigger/restore) is returned
let meta = literal!(
{"cb": ["ack", "open", "fail"]}
);
let event = Event {
id: id.clone(),
data: (Value::null(), meta).into(),
op_meta: op_meta.clone(),
origin_uri: origin_uri.clone(),
..Event::default()
};
let c: &mut dyn Codec = codec.borrow_mut();
let res = cb.on_event(in_, c, &codec_map, event).await?;
assert!(res.is_some(), "got nothing back");
if let Some(replies) = res {
assert_eq!(2, replies.len());
match replies.as_slice() {
[Reply::Insight(insight1), Reply::Insight(insight2)] => {
assert_eq!(CbAction::Ack, insight1.cb);
assert_eq!(id, insight1.id);
assert_eq!(op_meta, insight1.op_meta);
assert_eq!(origin_uri, insight1.origin_uri);
assert_eq!(CbAction::Open, insight2.cb);
assert_eq!(op_meta, insight2.op_meta);
assert_eq!(origin_uri, insight2.origin_uri);
}
_ => assert!(
false,
"expected to get two insights back. Got {:?}",
replies
),
}
}
// array data - second ack/fail will be ignored, just one from ack/fail or open/close (trigger/restore) is returned
let data = literal!({
"cb": ["trigger", "fail"]
});
let event = Event {
id: id.clone(),
data: (data, Value::null()).into(),
op_meta: op_meta.clone(),
origin_uri: origin_uri.clone(),
..Event::default()
};
let c: &mut dyn Codec = codec.borrow_mut();
let res = cb.on_event(in_, c, &codec_map, event).await?;
assert!(res.is_some(), "got nothing back");
if let Some(replies) = res {
assert_eq!(2, replies.len());
match replies.as_slice() {
[Reply::Insight(insight1), Reply::Insight(insight2)] => {
assert_eq!(CbAction::Fail, insight1.cb);
assert_eq!(id, insight1.id);
assert_eq!(op_meta, insight1.op_meta);
assert_eq!(origin_uri, insight1.origin_uri);
assert_eq!(CbAction::Close, insight2.cb);
assert_eq!(op_meta, insight2.op_meta);
assert_eq!(origin_uri, insight2.origin_uri);
}
_ => assert!(
false,
"expected to get two insights back. Got {:?}",
replies
),
}
}
cb.terminate().await;
Ok(())
}
}
|
use bus::*;
use csr::*;
pub struct IntReg {
values: [u32; 32],
}
impl IntReg {
pub fn new() -> IntReg {
IntReg { values: [0; 32] }
}
pub fn read(&self, index: usize) -> u32 {
self.values[index]
}
pub fn write(&mut self, index: usize, value: u32) {
if index != 0 {
self.values[index] = value
}
}
}
#[test]
fn test_int_reg() {
let mut reg = IntReg::new();
reg.write(0, 100);
reg.write(1, 200);
assert_eq!(reg.read(0), 0);
assert_eq!(reg.read(1), 200);
}
pub struct Core<'a> {
pub csr: Csr,
pub int_reg: IntReg,
pub pc: u32,
pub next_pc: u32,
pub bus: &'a mut Bus<'a>,
pub host_io_addr: u32,
}
impl<'a> Core<'a> {
pub fn new(bus: &'a mut Bus<'a>) -> Core<'a> {
Core { csr: Csr::new(), int_reg: IntReg::new(), pc: 0, next_pc: 0, bus: bus, host_io_addr: 0 }
}
pub fn fetch(&self) -> u32 {
self.bus.read_u32(self.pc)
}
pub fn read_host_io(&self) -> u32 {
self.bus.read_u32(self.host_io_addr)
}
}
|
extern crate chrono;
extern crate olin;
use self::chrono::TimeZone;
use log::info;
/// This tests for https://github.com/CommonWA/cwa-spec/blob/master/ns/time.md
pub extern "C" fn test() -> Result<(), i32> {
info!("running ns::time tests");
let now: i64 = olin::time::ts();
let dt = chrono::Utc.timestamp(now, 0);
info!("ts: {}, dt: {}", now, dt.to_rfc3339());
let now = olin::time::now();
info!("time::now(): {}", now.to_rfc3339());
info!("ns::time tests passed");
Ok(())
}
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtNetwork/qnetworkinterface.h
// dst-file: /src/network/qnetworkinterface.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
use super::qhostaddress::QHostAddress; // 773
use super::super::core::qstring::QString; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QNetworkAddressEntry_Class_Size() -> c_int;
// proto: void QNetworkAddressEntry::swap(QNetworkAddressEntry & other);
fn _ZN20QNetworkAddressEntry4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkAddressEntry::setPrefixLength(int length);
fn _ZN20QNetworkAddressEntry15setPrefixLengthEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QNetworkAddressEntry::prefixLength();
fn _ZNK20QNetworkAddressEntry12prefixLengthEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QHostAddress QNetworkAddressEntry::netmask();
fn _ZNK20QNetworkAddressEntry7netmaskEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QNetworkAddressEntry::setBroadcast(const QHostAddress & newBroadcast);
fn _ZN20QNetworkAddressEntry12setBroadcastERK12QHostAddress(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkAddressEntry::QNetworkAddressEntry();
fn _ZN20QNetworkAddressEntryC2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QNetworkAddressEntry::setIp(const QHostAddress & newIp);
fn _ZN20QNetworkAddressEntry5setIpERK12QHostAddress(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkAddressEntry::setNetmask(const QHostAddress & newNetmask);
fn _ZN20QNetworkAddressEntry10setNetmaskERK12QHostAddress(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkAddressEntry::QNetworkAddressEntry(const QNetworkAddressEntry & other);
fn _ZN20QNetworkAddressEntryC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QHostAddress QNetworkAddressEntry::broadcast();
fn _ZNK20QNetworkAddressEntry9broadcastEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QNetworkAddressEntry::~QNetworkAddressEntry();
fn _ZN20QNetworkAddressEntryD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QHostAddress QNetworkAddressEntry::ip();
fn _ZNK20QNetworkAddressEntry2ipEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
fn QNetworkInterface_Class_Size() -> c_int;
// proto: static QNetworkInterface QNetworkInterface::interfaceFromName(const QString & name);
fn _ZN17QNetworkInterface17interfaceFromNameERK7QString(arg0: *mut c_void) -> *mut c_void;
// proto: void QNetworkInterface::QNetworkInterface();
fn _ZN17QNetworkInterfaceC2Ev(qthis: u64 /* *mut c_void*/);
// proto: QString QNetworkInterface::hardwareAddress();
fn _ZNK17QNetworkInterface15hardwareAddressEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QNetworkInterface::name();
fn _ZNK17QNetworkInterface4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QNetworkInterface::swap(QNetworkInterface & other);
fn _ZN17QNetworkInterface4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static QList<QHostAddress> QNetworkInterface::allAddresses();
fn _ZN17QNetworkInterface12allAddressesEv();
// proto: QString QNetworkInterface::humanReadableName();
fn _ZNK17QNetworkInterface17humanReadableNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QNetworkInterface::index();
fn _ZNK17QNetworkInterface5indexEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QNetworkInterface::isValid();
fn _ZNK17QNetworkInterface7isValidEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QNetworkInterface::QNetworkInterface(const QNetworkInterface & other);
fn _ZN17QNetworkInterfaceC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static QList<QNetworkInterface> QNetworkInterface::allInterfaces();
fn _ZN17QNetworkInterface13allInterfacesEv();
// proto: QList<QNetworkAddressEntry> QNetworkInterface::addressEntries();
fn _ZNK17QNetworkInterface14addressEntriesEv(qthis: u64 /* *mut c_void*/);
// proto: void QNetworkInterface::~QNetworkInterface();
fn _ZN17QNetworkInterfaceD2Ev(qthis: u64 /* *mut c_void*/);
// proto: static QNetworkInterface QNetworkInterface::interfaceFromIndex(int index);
fn _ZN17QNetworkInterface18interfaceFromIndexEi(arg0: c_int) -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QNetworkAddressEntry)=1
#[derive(Default)]
pub struct QNetworkAddressEntry {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QNetworkInterface)=1
#[derive(Default)]
pub struct QNetworkInterface {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QNetworkAddressEntry {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkAddressEntry {
return QNetworkAddressEntry{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QNetworkAddressEntry::swap(QNetworkAddressEntry & other);
impl /*struct*/ QNetworkAddressEntry {
pub fn swap<RetType, T: QNetworkAddressEntry_swap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.swap(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_swap<RetType> {
fn swap(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: void QNetworkAddressEntry::swap(QNetworkAddressEntry & other);
impl<'a> /*trait*/ QNetworkAddressEntry_swap<()> for (&'a QNetworkAddressEntry) {
fn swap(self , rsthis: & QNetworkAddressEntry) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntry4swapERS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkAddressEntry4swapERS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkAddressEntry::setPrefixLength(int length);
impl /*struct*/ QNetworkAddressEntry {
pub fn setPrefixLength<RetType, T: QNetworkAddressEntry_setPrefixLength<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPrefixLength(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_setPrefixLength<RetType> {
fn setPrefixLength(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: void QNetworkAddressEntry::setPrefixLength(int length);
impl<'a> /*trait*/ QNetworkAddressEntry_setPrefixLength<()> for (i32) {
fn setPrefixLength(self , rsthis: & QNetworkAddressEntry) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntry15setPrefixLengthEi()};
let arg0 = self as c_int;
unsafe {_ZN20QNetworkAddressEntry15setPrefixLengthEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QNetworkAddressEntry::prefixLength();
impl /*struct*/ QNetworkAddressEntry {
pub fn prefixLength<RetType, T: QNetworkAddressEntry_prefixLength<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.prefixLength(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_prefixLength<RetType> {
fn prefixLength(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: int QNetworkAddressEntry::prefixLength();
impl<'a> /*trait*/ QNetworkAddressEntry_prefixLength<i32> for () {
fn prefixLength(self , rsthis: & QNetworkAddressEntry) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QNetworkAddressEntry12prefixLengthEv()};
let mut ret = unsafe {_ZNK20QNetworkAddressEntry12prefixLengthEv(rsthis.qclsinst)};
return ret as i32;
// return 1;
}
}
// proto: QHostAddress QNetworkAddressEntry::netmask();
impl /*struct*/ QNetworkAddressEntry {
pub fn netmask<RetType, T: QNetworkAddressEntry_netmask<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.netmask(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_netmask<RetType> {
fn netmask(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: QHostAddress QNetworkAddressEntry::netmask();
impl<'a> /*trait*/ QNetworkAddressEntry_netmask<QHostAddress> for () {
fn netmask(self , rsthis: & QNetworkAddressEntry) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QNetworkAddressEntry7netmaskEv()};
let mut ret = unsafe {_ZNK20QNetworkAddressEntry7netmaskEv(rsthis.qclsinst)};
let mut ret1 = QHostAddress::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkAddressEntry::setBroadcast(const QHostAddress & newBroadcast);
impl /*struct*/ QNetworkAddressEntry {
pub fn setBroadcast<RetType, T: QNetworkAddressEntry_setBroadcast<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBroadcast(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_setBroadcast<RetType> {
fn setBroadcast(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: void QNetworkAddressEntry::setBroadcast(const QHostAddress & newBroadcast);
impl<'a> /*trait*/ QNetworkAddressEntry_setBroadcast<()> for (&'a QHostAddress) {
fn setBroadcast(self , rsthis: & QNetworkAddressEntry) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntry12setBroadcastERK12QHostAddress()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkAddressEntry12setBroadcastERK12QHostAddress(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkAddressEntry::QNetworkAddressEntry();
impl /*struct*/ QNetworkAddressEntry {
pub fn new<T: QNetworkAddressEntry_new>(value: T) -> QNetworkAddressEntry {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QNetworkAddressEntry_new {
fn new(self) -> QNetworkAddressEntry;
}
// proto: void QNetworkAddressEntry::QNetworkAddressEntry();
impl<'a> /*trait*/ QNetworkAddressEntry_new for () {
fn new(self) -> QNetworkAddressEntry {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntryC2Ev()};
let ctysz: c_int = unsafe{QNetworkAddressEntry_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
unsafe {_ZN20QNetworkAddressEntryC2Ev(qthis_ph)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkAddressEntry{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QNetworkAddressEntry::setIp(const QHostAddress & newIp);
impl /*struct*/ QNetworkAddressEntry {
pub fn setIp<RetType, T: QNetworkAddressEntry_setIp<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setIp(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_setIp<RetType> {
fn setIp(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: void QNetworkAddressEntry::setIp(const QHostAddress & newIp);
impl<'a> /*trait*/ QNetworkAddressEntry_setIp<()> for (&'a QHostAddress) {
fn setIp(self , rsthis: & QNetworkAddressEntry) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntry5setIpERK12QHostAddress()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkAddressEntry5setIpERK12QHostAddress(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkAddressEntry::setNetmask(const QHostAddress & newNetmask);
impl /*struct*/ QNetworkAddressEntry {
pub fn setNetmask<RetType, T: QNetworkAddressEntry_setNetmask<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setNetmask(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_setNetmask<RetType> {
fn setNetmask(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: void QNetworkAddressEntry::setNetmask(const QHostAddress & newNetmask);
impl<'a> /*trait*/ QNetworkAddressEntry_setNetmask<()> for (&'a QHostAddress) {
fn setNetmask(self , rsthis: & QNetworkAddressEntry) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntry10setNetmaskERK12QHostAddress()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkAddressEntry10setNetmaskERK12QHostAddress(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkAddressEntry::QNetworkAddressEntry(const QNetworkAddressEntry & other);
impl<'a> /*trait*/ QNetworkAddressEntry_new for (&'a QNetworkAddressEntry) {
fn new(self) -> QNetworkAddressEntry {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntryC2ERKS_()};
let ctysz: c_int = unsafe{QNetworkAddressEntry_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN20QNetworkAddressEntryC2ERKS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkAddressEntry{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QHostAddress QNetworkAddressEntry::broadcast();
impl /*struct*/ QNetworkAddressEntry {
pub fn broadcast<RetType, T: QNetworkAddressEntry_broadcast<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.broadcast(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_broadcast<RetType> {
fn broadcast(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: QHostAddress QNetworkAddressEntry::broadcast();
impl<'a> /*trait*/ QNetworkAddressEntry_broadcast<QHostAddress> for () {
fn broadcast(self , rsthis: & QNetworkAddressEntry) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QNetworkAddressEntry9broadcastEv()};
let mut ret = unsafe {_ZNK20QNetworkAddressEntry9broadcastEv(rsthis.qclsinst)};
let mut ret1 = QHostAddress::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkAddressEntry::~QNetworkAddressEntry();
impl /*struct*/ QNetworkAddressEntry {
pub fn free<RetType, T: QNetworkAddressEntry_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_free<RetType> {
fn free(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: void QNetworkAddressEntry::~QNetworkAddressEntry();
impl<'a> /*trait*/ QNetworkAddressEntry_free<()> for () {
fn free(self , rsthis: & QNetworkAddressEntry) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN20QNetworkAddressEntryD2Ev()};
unsafe {_ZN20QNetworkAddressEntryD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QHostAddress QNetworkAddressEntry::ip();
impl /*struct*/ QNetworkAddressEntry {
pub fn ip<RetType, T: QNetworkAddressEntry_ip<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.ip(self);
// return 1;
}
}
pub trait QNetworkAddressEntry_ip<RetType> {
fn ip(self , rsthis: & QNetworkAddressEntry) -> RetType;
}
// proto: QHostAddress QNetworkAddressEntry::ip();
impl<'a> /*trait*/ QNetworkAddressEntry_ip<QHostAddress> for () {
fn ip(self , rsthis: & QNetworkAddressEntry) -> QHostAddress {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK20QNetworkAddressEntry2ipEv()};
let mut ret = unsafe {_ZNK20QNetworkAddressEntry2ipEv(rsthis.qclsinst)};
let mut ret1 = QHostAddress::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
impl /*struct*/ QNetworkInterface {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkInterface {
return QNetworkInterface{qclsinst: qthis, ..Default::default()};
}
}
// proto: static QNetworkInterface QNetworkInterface::interfaceFromName(const QString & name);
impl /*struct*/ QNetworkInterface {
pub fn interfaceFromName_s<RetType, T: QNetworkInterface_interfaceFromName_s<RetType>>( overload_args: T) -> RetType {
return overload_args.interfaceFromName_s();
// return 1;
}
}
pub trait QNetworkInterface_interfaceFromName_s<RetType> {
fn interfaceFromName_s(self ) -> RetType;
}
// proto: static QNetworkInterface QNetworkInterface::interfaceFromName(const QString & name);
impl<'a> /*trait*/ QNetworkInterface_interfaceFromName_s<QNetworkInterface> for (&'a QString) {
fn interfaceFromName_s(self ) -> QNetworkInterface {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterface17interfaceFromNameERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN17QNetworkInterface17interfaceFromNameERK7QString(arg0)};
let mut ret1 = QNetworkInterface::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkInterface::QNetworkInterface();
impl /*struct*/ QNetworkInterface {
pub fn new<T: QNetworkInterface_new>(value: T) -> QNetworkInterface {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QNetworkInterface_new {
fn new(self) -> QNetworkInterface;
}
// proto: void QNetworkInterface::QNetworkInterface();
impl<'a> /*trait*/ QNetworkInterface_new for () {
fn new(self) -> QNetworkInterface {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterfaceC2Ev()};
let ctysz: c_int = unsafe{QNetworkInterface_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
unsafe {_ZN17QNetworkInterfaceC2Ev(qthis_ph)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkInterface{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QString QNetworkInterface::hardwareAddress();
impl /*struct*/ QNetworkInterface {
pub fn hardwareAddress<RetType, T: QNetworkInterface_hardwareAddress<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hardwareAddress(self);
// return 1;
}
}
pub trait QNetworkInterface_hardwareAddress<RetType> {
fn hardwareAddress(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: QString QNetworkInterface::hardwareAddress();
impl<'a> /*trait*/ QNetworkInterface_hardwareAddress<QString> for () {
fn hardwareAddress(self , rsthis: & QNetworkInterface) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QNetworkInterface15hardwareAddressEv()};
let mut ret = unsafe {_ZNK17QNetworkInterface15hardwareAddressEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QNetworkInterface::name();
impl /*struct*/ QNetworkInterface {
pub fn name<RetType, T: QNetworkInterface_name<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.name(self);
// return 1;
}
}
pub trait QNetworkInterface_name<RetType> {
fn name(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: QString QNetworkInterface::name();
impl<'a> /*trait*/ QNetworkInterface_name<QString> for () {
fn name(self , rsthis: & QNetworkInterface) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QNetworkInterface4nameEv()};
let mut ret = unsafe {_ZNK17QNetworkInterface4nameEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkInterface::swap(QNetworkInterface & other);
impl /*struct*/ QNetworkInterface {
pub fn swap<RetType, T: QNetworkInterface_swap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.swap(self);
// return 1;
}
}
pub trait QNetworkInterface_swap<RetType> {
fn swap(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: void QNetworkInterface::swap(QNetworkInterface & other);
impl<'a> /*trait*/ QNetworkInterface_swap<()> for (&'a QNetworkInterface) {
fn swap(self , rsthis: & QNetworkInterface) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterface4swapERS_()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN17QNetworkInterface4swapERS_(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static QList<QHostAddress> QNetworkInterface::allAddresses();
impl /*struct*/ QNetworkInterface {
pub fn allAddresses_s<RetType, T: QNetworkInterface_allAddresses_s<RetType>>( overload_args: T) -> RetType {
return overload_args.allAddresses_s();
// return 1;
}
}
pub trait QNetworkInterface_allAddresses_s<RetType> {
fn allAddresses_s(self ) -> RetType;
}
// proto: static QList<QHostAddress> QNetworkInterface::allAddresses();
impl<'a> /*trait*/ QNetworkInterface_allAddresses_s<()> for () {
fn allAddresses_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterface12allAddressesEv()};
unsafe {_ZN17QNetworkInterface12allAddressesEv()};
// return 1;
}
}
// proto: QString QNetworkInterface::humanReadableName();
impl /*struct*/ QNetworkInterface {
pub fn humanReadableName<RetType, T: QNetworkInterface_humanReadableName<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.humanReadableName(self);
// return 1;
}
}
pub trait QNetworkInterface_humanReadableName<RetType> {
fn humanReadableName(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: QString QNetworkInterface::humanReadableName();
impl<'a> /*trait*/ QNetworkInterface_humanReadableName<QString> for () {
fn humanReadableName(self , rsthis: & QNetworkInterface) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QNetworkInterface17humanReadableNameEv()};
let mut ret = unsafe {_ZNK17QNetworkInterface17humanReadableNameEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QNetworkInterface::index();
impl /*struct*/ QNetworkInterface {
pub fn index<RetType, T: QNetworkInterface_index<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.index(self);
// return 1;
}
}
pub trait QNetworkInterface_index<RetType> {
fn index(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: int QNetworkInterface::index();
impl<'a> /*trait*/ QNetworkInterface_index<i32> for () {
fn index(self , rsthis: & QNetworkInterface) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QNetworkInterface5indexEv()};
let mut ret = unsafe {_ZNK17QNetworkInterface5indexEv(rsthis.qclsinst)};
return ret as i32;
// return 1;
}
}
// proto: bool QNetworkInterface::isValid();
impl /*struct*/ QNetworkInterface {
pub fn isValid<RetType, T: QNetworkInterface_isValid<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isValid(self);
// return 1;
}
}
pub trait QNetworkInterface_isValid<RetType> {
fn isValid(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: bool QNetworkInterface::isValid();
impl<'a> /*trait*/ QNetworkInterface_isValid<i8> for () {
fn isValid(self , rsthis: & QNetworkInterface) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QNetworkInterface7isValidEv()};
let mut ret = unsafe {_ZNK17QNetworkInterface7isValidEv(rsthis.qclsinst)};
return ret as i8;
// return 1;
}
}
// proto: void QNetworkInterface::QNetworkInterface(const QNetworkInterface & other);
impl<'a> /*trait*/ QNetworkInterface_new for (&'a QNetworkInterface) {
fn new(self) -> QNetworkInterface {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterfaceC2ERKS_()};
let ctysz: c_int = unsafe{QNetworkInterface_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN17QNetworkInterfaceC2ERKS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkInterface{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: static QList<QNetworkInterface> QNetworkInterface::allInterfaces();
impl /*struct*/ QNetworkInterface {
pub fn allInterfaces_s<RetType, T: QNetworkInterface_allInterfaces_s<RetType>>( overload_args: T) -> RetType {
return overload_args.allInterfaces_s();
// return 1;
}
}
pub trait QNetworkInterface_allInterfaces_s<RetType> {
fn allInterfaces_s(self ) -> RetType;
}
// proto: static QList<QNetworkInterface> QNetworkInterface::allInterfaces();
impl<'a> /*trait*/ QNetworkInterface_allInterfaces_s<()> for () {
fn allInterfaces_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterface13allInterfacesEv()};
unsafe {_ZN17QNetworkInterface13allInterfacesEv()};
// return 1;
}
}
// proto: QList<QNetworkAddressEntry> QNetworkInterface::addressEntries();
impl /*struct*/ QNetworkInterface {
pub fn addressEntries<RetType, T: QNetworkInterface_addressEntries<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addressEntries(self);
// return 1;
}
}
pub trait QNetworkInterface_addressEntries<RetType> {
fn addressEntries(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: QList<QNetworkAddressEntry> QNetworkInterface::addressEntries();
impl<'a> /*trait*/ QNetworkInterface_addressEntries<()> for () {
fn addressEntries(self , rsthis: & QNetworkInterface) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QNetworkInterface14addressEntriesEv()};
unsafe {_ZNK17QNetworkInterface14addressEntriesEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QNetworkInterface::~QNetworkInterface();
impl /*struct*/ QNetworkInterface {
pub fn free<RetType, T: QNetworkInterface_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QNetworkInterface_free<RetType> {
fn free(self , rsthis: & QNetworkInterface) -> RetType;
}
// proto: void QNetworkInterface::~QNetworkInterface();
impl<'a> /*trait*/ QNetworkInterface_free<()> for () {
fn free(self , rsthis: & QNetworkInterface) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterfaceD2Ev()};
unsafe {_ZN17QNetworkInterfaceD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: static QNetworkInterface QNetworkInterface::interfaceFromIndex(int index);
impl /*struct*/ QNetworkInterface {
pub fn interfaceFromIndex_s<RetType, T: QNetworkInterface_interfaceFromIndex_s<RetType>>( overload_args: T) -> RetType {
return overload_args.interfaceFromIndex_s();
// return 1;
}
}
pub trait QNetworkInterface_interfaceFromIndex_s<RetType> {
fn interfaceFromIndex_s(self ) -> RetType;
}
// proto: static QNetworkInterface QNetworkInterface::interfaceFromIndex(int index);
impl<'a> /*trait*/ QNetworkInterface_interfaceFromIndex_s<QNetworkInterface> for (i32) {
fn interfaceFromIndex_s(self ) -> QNetworkInterface {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QNetworkInterface18interfaceFromIndexEi()};
let arg0 = self as c_int;
let mut ret = unsafe {_ZN17QNetworkInterface18interfaceFromIndexEi(arg0)};
let mut ret1 = QNetworkInterface::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.