text stringlengths 8 4.13M |
|---|
// This file is part of syslog. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog/master/COPYRIGHT. No part of syslog, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2016 The developers of syslog. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/syslog/master/COPYRIGHT.
#![feature(const_fn)]
#![feature(stmt_expr_attributes)]
#[macro_use] extern crate bitflags;
#[macro_use] extern crate cfg_if;
#[macro_use] extern crate once;
extern crate libc;
use std::ffi::CStr;
mod severity;
pub use severity::Severity;
mod facility;
pub use facility::Facility;
mod priority;
pub use priority::Priority;
pub use priority::PriorityTrait;
mod logMask;
pub use logMask::LogMask;
pub use logMask::LogMaskTrait;
pub use logMask::default_log_mask;
mod logOptions;
pub use logOptions::LogOptions;
mod vecU8PushStr;
pub use vecU8PushStr::VecU8PushStr;
pub use syslogRfcConstructor::SyslogRfcConstructor;
mod syslogRfcConstructor;
pub use syslogRfc::SyslogRfc;
mod syslogRfc;
pub mod syslogSenders;
pub mod rfc5424;
pub fn syslog_cstr_currentLoggingFacility(severity: Severity, message: &CStr)
{
let priority = severity.toPriorityForCurrentLoggingFacility();
syslog_cstr(priority, message);
}
// Exists because we need byte string constants, and these are for UNSIGNED bytes
pub fn syslog_bytes_currentLoggingFacility(severity: Severity, message: &[u8])
{
let priority = severity.toPriorityForCurrentLoggingFacility();
syslog_bytes(priority, message);
}
pub fn syslog_cstr_withFacility(severity: Severity, message: &CStr, facility: Facility)
{
let priority = severity.toPriority(facility);
syslog_cstr(priority, message);
}
// Exists because we need byte string constants, and these are for UNSIGNED bytes
pub fn syslog_bytes_withFacility(severity: Severity, message: &[u8], facility: Facility)
{
let priority = severity.toPriority(facility);
syslog_bytes(priority, message);
}
#[cfg(any(target_os = "windows", target_os = "solaris"))]
static mut OpenLogProgramName: Option<CString> = None;
#[cfg(any(target_os = "windows", target_os = "solaris"))]
static mut OpenLogDoNotLogToStandardError: bool = true;
#[cfg(any(target_os = "windows", target_os = "solaris"))]
static mut OpenLogDefaultFacility: Facility = Default::default();
#[cfg(any(target_os = "windows", target_os = "solaris"))]
pub fn log_to_standard_error_for_windows_and_solaris_bytes(priority: Priority, message: &[u8])
{
let message = unsafe { CStr.from_bytes_with_nul_unchecked(message) };
log_to_standard_error_for_windows_and_solaris_cstr(priority, message);
}
#[cfg(any(target_os = "windows", target_os = "solaris"))]
pub fn enable_logging_to_standard_error(programName: &CStr, logToStandardErrorAsWell: bool, defaultFacility: Facility)
{
unsafe
{
OpenLogProgramName = Some(programName.to_owned());
OpenLogDoNotLogToStandardError = !logToStandardErrorAsWell;
OpenLogDefaultFacility = defaultFacility;
}
}
#[cfg(any(target_os = "windows", target_os = "solaris"))]
pub fn log_to_standard_error_for_windows_and_solaris_cstr(priority: Priority, message: &CStr)
{
if OpenLogDoNotLogToStandardError
{
return;
}
let message: &str = message.to_string_lossy();
let timeNow = time::now_utc();
let messageFacility = priority.facility();
let chosenFacility = match priority.facility()
{
Facility::LOG_KERN => OpenLogDefaultFacility,
everythingElse @ _ => everythingElse,
};
let message = format_message_rfc3164(&CurrentProcess.hostName, &OpenLogProgramName, &CurrentProcess.pid, timeNow, chosenFacility.toRfc3164Facility(), priority.severity(), message);
// We do not use the writeln! macro here, as it is not clear that it gets the line delimiter correct (and after the breaking changes to the lines() logic in rust, I no longer trust the std library in this area)
write!(&mut w, "{}\r\n", message).unwrap();
}
cfg_if!
{
if #[cfg(windows)]
{
mod windows;
pub use windows::*;
}
else if #[cfg(unix)]
{
mod unix;
pub use unix::*;
}
else
{
// Unsupported
}
}
#[test]
#[should_panic]
fn writesToSyslogAndCleansUpOnPanic()
{
with_open_syslog(&CString::new("progname").unwrap(), true, Default::default(), ||
{
static TestString: &'static [u8] = b"Test of syslog_bytes*\0";
let cstr = CString::new("Test of syslog_cstr*").unwrap();
syslog_cstr_currentLoggingFacility(Severity::LOG_CRIT, &cstr);
syslog_bytes_currentLoggingFacility(Severity::LOG_CRIT, &TestString);
syslog_cstr_withFacility(Severity::LOG_CRIT, &cstr, Facility::LOG_LOCAL0);
syslog_bytes_withFacility(Severity::LOG_CRIT, &TestString, Facility::LOG_LOCAL0);
syslog_cstr(Severity::LOG_CRIT.toPriority(Facility::LOG_LOCAL0), &CString::new("Test of syslog_cstr").unwrap());
syslog_bytes(Severity::LOG_CRIT.toPriority(Facility::LOG_LOCAL0), &TestString);
panic!("hello");
});
}
|
use std::env;
use std::process::Command;
use std::str;
use std::str::FromStr;
fn main() {
if rustc_has_dyn_trait() {
println!("cargo:rustc-cfg=has_dyn_trait");
}
}
fn rustc_has_dyn_trait() -> bool {
let rustc = match env::var_os("RUSTC") {
Some(rustc) => rustc,
None => return false,
};
let output = match Command::new(rustc).arg("--version").output() {
Ok(output) => output,
Err(_) => return false,
};
let version = match str::from_utf8(&output.stdout) {
Ok(version) => version,
Err(_) => return false,
};
let mut pieces = version.split('.');
if pieces.next() != Some("rustc 1") {
return true;
}
let next = match pieces.next() {
Some(next) => next,
None => return false,
};
u32::from_str(next).unwrap_or(0) >= 27
}
|
use crate::{Point, MEAN_EARTH_RADIUS};
use num_traits::{Float, FromPrimitive};
/// Returns a new Point using the distance to the existing Point and a bearing for the direction
pub trait HaversineDestination<T: Float> {
/// Returns a new Point using distance to the existing Point and a bearing for the direction
///
/// # Units
///
/// - `bearing`: degrees
/// - `distance`: meters
///
/// # Examples
///
/// ```
/// use geo::algorithm::haversine_destination::HaversineDestination;
/// use geo::Point;
///
/// let p_1 = Point::<f64>::new(9.177789688110352, 48.776781529534965);
/// let p_2 = p_1.haversine_destination(45., 10000.);
/// assert_eq!(p_2, Point::<f64>::new(9.274410083250379, 48.84033282787534))
/// ```
fn haversine_destination(&self, bearing: T, distance: T) -> Point<T>;
}
impl<T> HaversineDestination<T> for Point<T>
where
T: Float + FromPrimitive,
{
fn haversine_destination(&self, bearing: T, distance: T) -> Point<T> {
let center_lng = self.x().to_radians();
let center_lat = self.y().to_radians();
let bearing_rad = bearing.to_radians();
let rad = distance / T::from(MEAN_EARTH_RADIUS).unwrap();
let lat =
{ center_lat.sin() * rad.cos() + center_lat.cos() * rad.sin() * bearing_rad.cos() }
.asin();
let lng = { bearing_rad.sin() * rad.sin() * center_lat.cos() }
.atan2(rad.cos() - center_lat.sin() * lat.sin())
+ center_lng;
Point::new(lng.to_degrees(), lat.to_degrees())
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::algorithm::haversine_distance::HaversineDistance;
use num_traits::pow;
#[test]
fn returns_a_new_point() {
let p_1 = Point::<f64>::new(9.177789688110352, 48.776781529534965);
let p_2 = p_1.haversine_destination(45., 10000.);
assert_eq!(p_2, Point::<f64>::new(9.274410083250379, 48.84033282787534));
let distance = p_1.haversine_distance(&p_2);
assert_relative_eq!(distance, 10000., epsilon = 1.0e-6)
}
#[test]
fn direct_and_indirect_destinations_are_close() {
let p_1 = Point::<f64>::new(9.177789688110352, 48.776781529534965);
let p_2 = p_1.haversine_destination(45., 10000.);
let square_edge = { pow(10000., 2) / 2. }.sqrt();
let p_3 = p_1.haversine_destination(0., square_edge);
let p_4 = p_3.haversine_destination(90., square_edge);
assert_relative_eq!(p_4.x(), p_2.x(), epsilon = 1.0e-6);
assert_relative_eq!(p_4.y(), p_2.y(), epsilon = 1.0e-6);
}
}
|
use std::collections::HashMap;
use std::sync::Arc;
use futures_core::future::BoxFuture;
use serde::de::DeserializeOwned;
use crate::connection::ConnectionSource;
use crate::cursor::Cursor;
use crate::executor::Execute;
use crate::mysql::{MySql, MySqlArguments, MySqlConnection, MySqlRow, MySqlTypeInfo};
use crate::mysql::protocol::{ColumnCount, ColumnDefinition, Row, Status};
use crate::pool::Pool;
use crate::decode::json_decode;
pub struct MySqlCursor<'c, 'q> {
source: ConnectionSource<'c, MySqlConnection>,
query: Option<(&'q str, Option<MySqlArguments>)>,
column_names: Arc<HashMap<Box<str>, u16>>,
column_types: Vec<MySqlTypeInfo>,
binary: bool,
}
impl crate::cursor::private::Sealed for MySqlCursor<'_, '_> {}
impl<'c, 'q> Cursor<'c, 'q> for MySqlCursor<'c, 'q> {
type Database = MySql;
#[doc(hidden)]
fn from_pool<E>(pool: &Pool<MySqlConnection>, query: E) -> Self
where
Self: Sized,
E: Execute<'q, MySql>,
{
Self {
source: ConnectionSource::Pool(pool.clone()),
column_names: Arc::default(),
column_types: Vec::new(),
binary: true,
query: Some(query.into_parts()),
}
}
#[doc(hidden)]
fn from_connection<E>(conn: &'c mut MySqlConnection, query: E) -> Self
where
Self: Sized,
E: Execute<'q, MySql>,
{
Self {
source: ConnectionSource::ConnectionRef(conn),
column_names: Arc::default(),
column_types: Vec::new(),
binary: true,
query: Some(query.into_parts()),
}
}
fn next(&mut self) -> BoxFuture<crate::Result<Option<MySqlRow<'_>>>> {
Box::pin(next(self))
}
fn decode_json<T>(&mut self) -> BoxFuture<Result<T, crate::Error>>
where T: DeserializeOwned {
Box::pin(async move {
let arr = self.fetch_json().await?;
let r = json_decode(arr)?;
return Ok(r);
})
}
fn fetch_json(&mut self) -> BoxFuture<Result<Vec<serde_json::Value>, crate::Error>> {
Box::pin(async move {
let mut arr = vec![];
while let Some(row) = self.next().await? as Option<MySqlRow<'_>> {
let mut m = serde_json::Map::new();
let keys = row.names.keys();
for x in keys {
let key = x.to_string();
let key_str=key.as_str();
let v:serde_json::Value = row.json_decode_impl(key_str)?;
m.insert(key, v);
}
arr.push(serde_json::Value::Object(m));
}
return Ok(arr);
})
}
}
async fn next<'a, 'c: 'a, 'q: 'a>(
cursor: &'a mut MySqlCursor<'c, 'q>,
) -> crate::Result<Option<MySqlRow<'a>>> {
let mut conn = cursor.source.resolve().await?;
// The first time [next] is called we need to actually execute our
// contained query. We guard against this happening on _all_ next calls
// by using [Option::take] which replaces the potential value in the Option with `None
let mut initial = if let Some((query, arguments)) = cursor.query.take() {
let statement = conn.run(query, arguments).await?;
// No statement ID = TEXT mode
cursor.binary = statement.is_some();
true
} else {
false
};
loop {
let packet_id = conn.stream.receive().await?[0];
match packet_id {
// OK or EOF packet
0x00 | 0xFE
if conn.stream.packet().len() < 0xFF_FF_FF && (packet_id != 0x00 || initial) =>
{
let status = if let Some(eof) = conn.stream.maybe_handle_eof()? {
eof.status
} else {
conn.stream.handle_ok()?.status
};
if status.contains(Status::SERVER_MORE_RESULTS_EXISTS) {
// There is more to this query
initial = true;
} else {
conn.is_ready = true;
return Ok(None);
}
}
// ERR packet
0xFF => {
conn.is_ready = true;
return conn.stream.handle_err();
}
_ if initial => {
// At the start of the results we expect to see a
// COLUMN_COUNT followed by N COLUMN_DEF
let cc = ColumnCount::read(conn.stream.packet())?;
// We use these definitions to get the actual column types that is critical
// in parsing the rows coming back soon
cursor.column_types.clear();
cursor.column_types.reserve(cc.columns as usize);
let mut column_names = HashMap::with_capacity(cc.columns as usize);
for i in 0..cc.columns {
let column = ColumnDefinition::read(conn.stream.receive().await?)?;
cursor
.column_types
.push(MySqlTypeInfo::from_nullable_column_def(&column));
if let Some(name) = column.name() {
column_names.insert(name.to_owned().into_boxed_str(), i as u16);
}
}
if cc.columns > 0 {
conn.stream.maybe_receive_eof().await?;
}
cursor.column_names = Arc::new(column_names);
initial = false;
}
_ if !cursor.binary || packet_id == 0x00 => {
let row = Row::read(
conn.stream.packet(),
&cursor.column_types,
&mut conn.current_row_values,
cursor.binary,
)?;
let row = MySqlRow {
row,
names: Arc::clone(&cursor.column_names),
};
return Ok(Some(row));
}
_ => {
return conn.stream.handle_unexpected();
}
}
}
}
|
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT.
/// Does not contain the root, empty label.
///
/// RFC 2065 asserts that the maximum number of labels is 127; this makes sense if every label bar the last (which is Root) is 1 byte long and so occupies 2 bytes.
/// However, the maximum reasonable length is an IPv6 reverse DNS look up, which requires 33 labels (32 for each nibble and 2 for `ip6.arpa` less 1 for the omitted root label) of a `SRV` entry such as `_mqtt._tcp`, thus 35 labels.
#[derive(Default, Debug, Clone)]
pub struct WithoutCompressionParsedNameIterator<'message>
{
pointer_to_label: usize,
marker: PhantomData<&'message ()>,
}
impl<'message> Iterator for WithoutCompressionParsedNameIterator<'message>
{
type Item = LabelBytes<'message>;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item>
{
let (label, pointer_to_label) = iterator_next_label!(self);
bytes_label!(self, label, pointer_to_label)
}
}
impl<'message> WithoutCompressionParsedNameIterator<'message>
{
#[inline(always)]
pub(crate) fn new(pointer_to_label: usize) -> Self
{
Self
{
pointer_to_label,
marker: PhantomData,
}
}
}
|
use super::sys::*;
use super::tree::*;
use super::utils::*;
#[derive(Debug, Clone)]
pub struct Chunk {
self_ptr: *const cabocha_chunk_t,
}
impl Chunk {
pub fn new(raw_ptr: *const cabocha_chunk_t) -> Chunk {
Chunk { self_ptr: raw_ptr }
}
pub fn link(&self) -> i32 {
unsafe { (*self.self_ptr).link }
}
pub fn head_pos(&self) -> usize {
unsafe { (*self.self_ptr).head_pos }
}
pub fn func_pos(&self) -> usize {
unsafe { (*self.self_ptr).func_pos }
}
pub fn token_size(&self) -> usize {
unsafe { (*self.self_ptr).token_size }
}
pub fn token_pos(&self) -> usize {
unsafe { (*self.self_ptr).token_pos }
}
pub fn score(&self) -> f32 {
unsafe { (*self.self_ptr).score }
}
pub fn feature_list(&self) -> Vec<String> {
unsafe {
let chunk = &*self.self_ptr;
ptr_to_vec_string(chunk.feature_list, chunk.feature_list_size as usize)
}
}
pub fn additional_info(&self) -> String {
unsafe { ptr_to_string((*self.self_ptr).additional_info) }
}
pub fn feature_list_size(&self) -> u16 {
unsafe { (*self.self_ptr).feature_list_size }
}
}
pub struct ChunkIter<'a> {
tree: &'a Tree,
pos: usize,
}
impl<'a> Iterator for ChunkIter<'a> {
type Item = Chunk;
fn next(&mut self) -> Option<Chunk> {
let chunk = self.tree.chunk(self.pos);
self.pos += 1;
chunk
}
}
impl<'a> ChunkIter<'a> {
pub fn new(tree: &Tree) -> ChunkIter {
ChunkIter { tree, pos: 0 }
}
}
|
#[macro_use] extern crate quote;
extern crate proc_macro;
extern crate serde;
extern crate serde_json;
extern crate syn;
use std::fs::File;
use proc_macro::TokenStream;
use serde::de::IgnoredAny;
use syn::{DeriveInput, Lit, Meta, MetaNameValue};
#[proc_macro_derive(Validate, attributes(path))]
pub fn validate_file(input: TokenStream) -> TokenStream {
// Parse tokens of the input struct
let ast: DeriveInput = syn::parse(input)
.expect("validate_macros: Failed to parse Derive Input");
// Interpret unstructured tokens of the `#[path = $path]` attribute into a
// structured meta-item representation
let meta = ast.attrs[0].interpret_meta().unwrap();
// Expect the `$path` to be a string literal
let path = match meta {
Meta::NameValue(MetaNameValue { lit: Lit::Str(s), .. }) => s.value(),
_ => panic!("validate_macros: Expected #[path = \"...\"]"),
};
// Validate JSON without parsing it into any particular data structure
let file = File::open(&path).unwrap_or_else(|err| panic!("{}", err));
match serde_json::from_reader(file) {
Ok(IgnoredAny) => {}
Err(err) => panic!("Failed to parse {}: {}", path, err),
}
// If successful, produce empty token stream as output
quote!().into()
}
|
//! A writfield1 buffer, with one or more snapshots.
use arrow::record_batch::RecordBatch;
use data_types::{sequence_number_set::SequenceNumberSet, TimestampMinMax};
use iox_query::util::compute_timenanosecond_min_max;
use schema::{merge::merge_record_batch_schemas, Schema};
use super::BufferState;
use crate::{
buffer_tree::partition::buffer::traits::Queryable, query::projection::OwnedProjection,
};
/// An immutable set of [`RecordBatch`] in the process of being persisted.
#[derive(Debug)]
pub(crate) struct Persisting {
/// Snapshots generated from previous buffer contents to be persisted.
///
/// INVARIANT: this array is always non-empty.
snapshots: Vec<RecordBatch>,
/// Statistics describing the data in snapshots.
row_count: usize,
timestamp_stats: TimestampMinMax,
schema: Schema,
}
impl Persisting {
pub(super) fn new(
snapshots: Vec<RecordBatch>,
row_count: usize,
timestamp_stats: TimestampMinMax,
schema: Schema,
) -> Self {
// Invariant: the summary statistics provided must match the actual
// data.
debug_assert_eq!(
row_count,
snapshots.iter().map(|v| v.num_rows()).sum::<usize>()
);
debug_assert_eq!(
timestamp_stats,
compute_timenanosecond_min_max(snapshots.iter()).unwrap()
);
debug_assert_eq!(schema, merge_record_batch_schemas(&snapshots));
Self {
snapshots,
row_count,
timestamp_stats,
schema,
}
}
}
impl Queryable for Persisting {
fn get_query_data(&self, projection: &OwnedProjection) -> Vec<RecordBatch> {
projection.project_record_batch(&self.snapshots)
}
fn rows(&self) -> usize {
self.row_count
}
fn timestamp_stats(&self) -> Option<TimestampMinMax> {
Some(self.timestamp_stats)
}
fn schema(&self) -> Option<schema::Schema> {
Some(self.schema.clone()) // Ref clone
}
}
impl BufferState<Persisting> {
/// Consume `self` and all references to the buffered data, returning the owned
/// [`SequenceNumberSet`] within it.
pub(crate) fn into_sequence_number_set(self) -> SequenceNumberSet {
self.sequence_numbers
}
}
|
#![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 ISecondaryAuthenticationFactorAuthentication(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorAuthentication {
type Vtable = ISecondaryAuthenticationFactorAuthentication_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x020a16e5_6a25_40a3_8c00_50a023f619d1);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthentication_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_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, devicehmac: ::windows::core::RawPtr, sessionhmac: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, errorlogmessage: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorAuthenticationResult {
type Vtable = ISecondaryAuthenticationFactorAuthenticationResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9cbb5987_ef6d_4bc2_bf49_4617515a0f9a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationResult_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut SecondaryAuthenticationFactorAuthenticationStatus) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
type Vtable = ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd4a5ee56_7291_4073_bc1f_ccb8f5afdf96);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationStageInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorAuthenticationStageInfo {
type Vtable = ISecondaryAuthenticationFactorAuthenticationStageInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x56fec28b_e8aa_4c0f_8e4c_a559e73add88);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationStageInfo_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut SecondaryAuthenticationFactorAuthenticationStage) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut SecondaryAuthenticationFactorAuthenticationScenario) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorAuthenticationStatics {
type Vtable = ISecondaryAuthenticationFactorAuthenticationStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3f582656_28f8_4e0f_ae8c_5898b9ae2469);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorAuthenticationStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, devicename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, message: SecondaryAuthenticationFactorAuthenticationMessage, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, serviceauthenticationnonce: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics {
type Vtable = ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x90499a19_7ef2_4523_951c_a417a24acf93);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, deviceinstancepath: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, monitoringmode: SecondaryAuthenticationFactorDevicePresenceMonitoringMode, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub unsafe extern "system" fn(
this: ::windows::core::RawPtr,
deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>,
deviceinstancepath: ::core::mem::ManuallyDrop<::windows::core::HSTRING>,
monitoringmode: SecondaryAuthenticationFactorDevicePresenceMonitoringMode,
devicefriendlyname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>,
devicemodelnumber: ::core::mem::ManuallyDrop<::windows::core::HSTRING>,
deviceconfigurationdata: ::windows::core::RawPtr,
result__: *mut ::windows::core::RawPtr,
) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorInfo(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorInfo {
type Vtable = ISecondaryAuthenticationFactorInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e2ba861_8533_4fce_839b_ecb72410ac14);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorInfo_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Storage_Streams"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorInfo2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorInfo2 {
type Vtable = ISecondaryAuthenticationFactorInfo2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x14d981a3_fc26_4ff7_abc3_48e82a512a0a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorInfo2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut SecondaryAuthenticationFactorDevicePresenceMonitoringMode) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, presencestate: SecondaryAuthenticationFactorDevicePresence, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorRegistration(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorRegistration {
type Vtable = ISecondaryAuthenticationFactorRegistration_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f4cbbb4_8cba_48b0_840d_dbb22a54c678);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorRegistration_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceconfigurationdata: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, errorlogmessage: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorRegistrationResult(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorRegistrationResult {
type Vtable = ISecondaryAuthenticationFactorRegistrationResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa4fe35f0_ade3_4981_af6b_ec195921682a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorRegistrationResult_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut SecondaryAuthenticationFactorRegistrationStatus) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorRegistrationStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryAuthenticationFactorRegistrationStatics {
type Vtable = ISecondaryAuthenticationFactorRegistrationStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1adf0f65_e3b7_4155_997f_b756ef65beba);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryAuthenticationFactorRegistrationStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, capabilities: SecondaryAuthenticationFactorDeviceCapabilities, devicefriendlyname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, devicemodelnumber: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, devicekey: ::windows::core::RawPtr, mutualauthenticationkey: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, querytype: SecondaryAuthenticationFactorDeviceFindScope, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, deviceconfigurationdata: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryAuthenticationFactorAuthentication(pub ::windows::core::IInspectable);
impl SecondaryAuthenticationFactorAuthentication {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Storage_Streams")]
pub fn ServiceAuthenticationHmac(&self) -> ::windows::core::Result<super::super::super::super::Storage::Streams::IBuffer> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Storage::Streams::IBuffer>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Storage_Streams")]
pub fn SessionNonce(&self) -> ::windows::core::Result<super::super::super::super::Storage::Streams::IBuffer> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Storage::Streams::IBuffer>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Storage_Streams")]
pub fn DeviceNonce(&self) -> ::windows::core::Result<super::super::super::super::Storage::Streams::IBuffer> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Storage::Streams::IBuffer>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Storage_Streams")]
pub fn DeviceConfigurationData(&self) -> ::windows::core::Result<super::super::super::super::Storage::Streams::IBuffer> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Storage::Streams::IBuffer>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn FinishAuthenticationAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>>(&self, devicehmac: Param0, sessionhmac: Param1) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorFinishAuthenticationStatus>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), devicehmac.into_param().abi(), sessionhmac.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorFinishAuthenticationStatus>>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AbortAuthenticationAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, errorlogmessage: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), errorlogmessage.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn ShowNotificationMessageAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(devicename: Param0, message: SecondaryAuthenticationFactorAuthenticationMessage) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
Self::ISecondaryAuthenticationFactorAuthenticationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), devicename.into_param().abi(), message, &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn StartAuthenticationAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>>(deviceid: Param0, serviceauthenticationnonce: Param1) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorAuthenticationResult>> {
Self::ISecondaryAuthenticationFactorAuthenticationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), serviceauthenticationnonce.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorAuthenticationResult>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AuthenticationStageChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::EventHandler<SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs>>>(handler: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::EventRegistrationToken> {
Self::ISecondaryAuthenticationFactorAuthenticationStatics(|this| unsafe {
let mut result__: super::super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::EventRegistrationToken>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RemoveAuthenticationStageChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> {
Self::ISecondaryAuthenticationFactorAuthenticationStatics(|this| unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() })
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn GetAuthenticationStageInfoAsync() -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorAuthenticationStageInfo>> {
Self::ISecondaryAuthenticationFactorAuthenticationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorAuthenticationStageInfo>>(result__)
})
}
pub fn ISecondaryAuthenticationFactorAuthenticationStatics<R, F: FnOnce(&ISecondaryAuthenticationFactorAuthenticationStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SecondaryAuthenticationFactorAuthentication, ISecondaryAuthenticationFactorAuthenticationStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthentication {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthentication;{020a16e5-6a25-40a3-8c00-50a023f619d1})");
}
unsafe impl ::windows::core::Interface for SecondaryAuthenticationFactorAuthentication {
type Vtable = ISecondaryAuthenticationFactorAuthentication_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x020a16e5_6a25_40a3_8c00_50a023f619d1);
}
impl ::windows::core::RuntimeName for SecondaryAuthenticationFactorAuthentication {
const NAME: &'static str = "Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthentication";
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthentication> for ::windows::core::IUnknown {
fn from(value: SecondaryAuthenticationFactorAuthentication) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthentication> for ::windows::core::IUnknown {
fn from(value: &SecondaryAuthenticationFactorAuthentication) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryAuthenticationFactorAuthentication {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecondaryAuthenticationFactorAuthentication {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthentication> for ::windows::core::IInspectable {
fn from(value: SecondaryAuthenticationFactorAuthentication) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthentication> for ::windows::core::IInspectable {
fn from(value: &SecondaryAuthenticationFactorAuthentication) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryAuthenticationFactorAuthentication {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecondaryAuthenticationFactorAuthentication {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryAuthenticationFactorAuthentication {}
unsafe impl ::core::marker::Sync for SecondaryAuthenticationFactorAuthentication {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorAuthenticationMessage(pub i32);
impl SecondaryAuthenticationFactorAuthenticationMessage {
pub const Invalid: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(0i32);
pub const SwipeUpWelcome: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(1i32);
pub const TapWelcome: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(2i32);
pub const DeviceNeedsAttention: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(3i32);
pub const LookingForDevice: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(4i32);
pub const LookingForDevicePluggedin: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(5i32);
pub const BluetoothIsDisabled: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(6i32);
pub const NfcIsDisabled: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(7i32);
pub const WiFiIsDisabled: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(8i32);
pub const ExtraTapIsRequired: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(9i32);
pub const DisabledByPolicy: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(10i32);
pub const TapOnDeviceRequired: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(11i32);
pub const HoldFinger: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(12i32);
pub const ScanFinger: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(13i32);
pub const UnauthorizedUser: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(14i32);
pub const ReregisterRequired: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(15i32);
pub const TryAgain: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(16i32);
pub const SayPassphrase: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(17i32);
pub const ReadyToSignIn: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(18i32);
pub const UseAnotherSignInOption: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(19i32);
pub const ConnectionRequired: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(20i32);
pub const TimeLimitExceeded: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(21i32);
pub const CanceledByUser: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(22i32);
pub const CenterHand: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(23i32);
pub const MoveHandCloser: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(24i32);
pub const MoveHandFarther: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(25i32);
pub const PlaceHandAbove: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(26i32);
pub const RecognitionFailed: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(27i32);
pub const DeviceUnavailable: SecondaryAuthenticationFactorAuthenticationMessage = SecondaryAuthenticationFactorAuthenticationMessage(28i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorAuthenticationMessage {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorAuthenticationMessage {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthenticationMessage {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationMessage;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorAuthenticationMessage {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryAuthenticationFactorAuthenticationResult(pub ::windows::core::IInspectable);
impl SecondaryAuthenticationFactorAuthenticationResult {
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorAuthenticationStatus> {
let this = self;
unsafe {
let mut result__: SecondaryAuthenticationFactorAuthenticationStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorAuthenticationStatus>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Authentication(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorAuthentication> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorAuthentication>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthenticationResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationResult;{9cbb5987-ef6d-4bc2-bf49-4617515a0f9a})");
}
unsafe impl ::windows::core::Interface for SecondaryAuthenticationFactorAuthenticationResult {
type Vtable = ISecondaryAuthenticationFactorAuthenticationResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9cbb5987_ef6d_4bc2_bf49_4617515a0f9a);
}
impl ::windows::core::RuntimeName for SecondaryAuthenticationFactorAuthenticationResult {
const NAME: &'static str = "Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationResult";
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthenticationResult> for ::windows::core::IUnknown {
fn from(value: SecondaryAuthenticationFactorAuthenticationResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthenticationResult> for ::windows::core::IUnknown {
fn from(value: &SecondaryAuthenticationFactorAuthenticationResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryAuthenticationFactorAuthenticationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecondaryAuthenticationFactorAuthenticationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthenticationResult> for ::windows::core::IInspectable {
fn from(value: SecondaryAuthenticationFactorAuthenticationResult) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthenticationResult> for ::windows::core::IInspectable {
fn from(value: &SecondaryAuthenticationFactorAuthenticationResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryAuthenticationFactorAuthenticationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecondaryAuthenticationFactorAuthenticationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryAuthenticationFactorAuthenticationResult {}
unsafe impl ::core::marker::Sync for SecondaryAuthenticationFactorAuthenticationResult {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorAuthenticationScenario(pub i32);
impl SecondaryAuthenticationFactorAuthenticationScenario {
pub const SignIn: SecondaryAuthenticationFactorAuthenticationScenario = SecondaryAuthenticationFactorAuthenticationScenario(0i32);
pub const CredentialPrompt: SecondaryAuthenticationFactorAuthenticationScenario = SecondaryAuthenticationFactorAuthenticationScenario(1i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorAuthenticationScenario {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorAuthenticationScenario {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthenticationScenario {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationScenario;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorAuthenticationScenario {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorAuthenticationStage(pub i32);
impl SecondaryAuthenticationFactorAuthenticationStage {
pub const NotStarted: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(0i32);
pub const WaitingForUserConfirmation: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(1i32);
pub const CollectingCredential: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(2i32);
pub const SuspendingAuthentication: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(3i32);
pub const CredentialCollected: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(4i32);
pub const CredentialAuthenticated: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(5i32);
pub const StoppingAuthentication: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(6i32);
pub const ReadyForLock: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(7i32);
pub const CheckingDevicePresence: SecondaryAuthenticationFactorAuthenticationStage = SecondaryAuthenticationFactorAuthenticationStage(8i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorAuthenticationStage {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorAuthenticationStage {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthenticationStage {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationStage;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorAuthenticationStage {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs(pub ::windows::core::IInspectable);
impl SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
#[cfg(feature = "deprecated")]
pub fn StageInfo(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorAuthenticationStageInfo> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorAuthenticationStageInfo>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs;{d4a5ee56-7291-4073-bc1f-ccb8f5afdf96})");
}
unsafe impl ::windows::core::Interface for SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
type Vtable = ISecondaryAuthenticationFactorAuthenticationStageChangedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd4a5ee56_7291_4073_bc1f_ccb8f5afdf96);
}
impl ::windows::core::RuntimeName for SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
const NAME: &'static str = "Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs";
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {}
unsafe impl ::core::marker::Sync for SecondaryAuthenticationFactorAuthenticationStageChangedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryAuthenticationFactorAuthenticationStageInfo(pub ::windows::core::IInspectable);
impl SecondaryAuthenticationFactorAuthenticationStageInfo {
#[cfg(feature = "deprecated")]
pub fn Stage(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorAuthenticationStage> {
let this = self;
unsafe {
let mut result__: SecondaryAuthenticationFactorAuthenticationStage = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorAuthenticationStage>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Scenario(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorAuthenticationScenario> {
let this = self;
unsafe {
let mut result__: SecondaryAuthenticationFactorAuthenticationScenario = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorAuthenticationScenario>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthenticationStageInfo {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationStageInfo;{56fec28b-e8aa-4c0f-8e4c-a559e73add88})");
}
unsafe impl ::windows::core::Interface for SecondaryAuthenticationFactorAuthenticationStageInfo {
type Vtable = ISecondaryAuthenticationFactorAuthenticationStageInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x56fec28b_e8aa_4c0f_8e4c_a559e73add88);
}
impl ::windows::core::RuntimeName for SecondaryAuthenticationFactorAuthenticationStageInfo {
const NAME: &'static str = "Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationStageInfo";
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthenticationStageInfo> for ::windows::core::IUnknown {
fn from(value: SecondaryAuthenticationFactorAuthenticationStageInfo) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthenticationStageInfo> for ::windows::core::IUnknown {
fn from(value: &SecondaryAuthenticationFactorAuthenticationStageInfo) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryAuthenticationFactorAuthenticationStageInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecondaryAuthenticationFactorAuthenticationStageInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryAuthenticationFactorAuthenticationStageInfo> for ::windows::core::IInspectable {
fn from(value: SecondaryAuthenticationFactorAuthenticationStageInfo) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorAuthenticationStageInfo> for ::windows::core::IInspectable {
fn from(value: &SecondaryAuthenticationFactorAuthenticationStageInfo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryAuthenticationFactorAuthenticationStageInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecondaryAuthenticationFactorAuthenticationStageInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryAuthenticationFactorAuthenticationStageInfo {}
unsafe impl ::core::marker::Sync for SecondaryAuthenticationFactorAuthenticationStageInfo {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorAuthenticationStatus(pub i32);
impl SecondaryAuthenticationFactorAuthenticationStatus {
pub const Failed: SecondaryAuthenticationFactorAuthenticationStatus = SecondaryAuthenticationFactorAuthenticationStatus(0i32);
pub const Started: SecondaryAuthenticationFactorAuthenticationStatus = SecondaryAuthenticationFactorAuthenticationStatus(1i32);
pub const UnknownDevice: SecondaryAuthenticationFactorAuthenticationStatus = SecondaryAuthenticationFactorAuthenticationStatus(2i32);
pub const DisabledByPolicy: SecondaryAuthenticationFactorAuthenticationStatus = SecondaryAuthenticationFactorAuthenticationStatus(3i32);
pub const InvalidAuthenticationStage: SecondaryAuthenticationFactorAuthenticationStatus = SecondaryAuthenticationFactorAuthenticationStatus(4i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorAuthenticationStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorAuthenticationStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorAuthenticationStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorAuthenticationStatus;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorAuthenticationStatus {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorDeviceCapabilities(pub u32);
impl SecondaryAuthenticationFactorDeviceCapabilities {
pub const None: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(0u32);
pub const SecureStorage: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(1u32);
pub const StoreKeys: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(2u32);
pub const ConfirmUserIntentToAuthenticate: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(4u32);
pub const SupportSecureUserPresenceCheck: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(8u32);
pub const TransmittedDataIsEncrypted: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(16u32);
pub const HMacSha256: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(32u32);
pub const CloseRangeDataTransmission: SecondaryAuthenticationFactorDeviceCapabilities = SecondaryAuthenticationFactorDeviceCapabilities(64u32);
}
impl ::core::convert::From<u32> for SecondaryAuthenticationFactorDeviceCapabilities {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorDeviceCapabilities {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorDeviceCapabilities {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorDeviceCapabilities;u4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorDeviceCapabilities {
type DefaultType = Self;
}
impl ::core::ops::BitOr for SecondaryAuthenticationFactorDeviceCapabilities {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for SecondaryAuthenticationFactorDeviceCapabilities {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for SecondaryAuthenticationFactorDeviceCapabilities {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for SecondaryAuthenticationFactorDeviceCapabilities {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for SecondaryAuthenticationFactorDeviceCapabilities {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorDeviceFindScope(pub i32);
impl SecondaryAuthenticationFactorDeviceFindScope {
pub const User: SecondaryAuthenticationFactorDeviceFindScope = SecondaryAuthenticationFactorDeviceFindScope(0i32);
pub const AllUsers: SecondaryAuthenticationFactorDeviceFindScope = SecondaryAuthenticationFactorDeviceFindScope(1i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorDeviceFindScope {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorDeviceFindScope {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorDeviceFindScope {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorDeviceFindScope;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorDeviceFindScope {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorDevicePresence(pub i32);
impl SecondaryAuthenticationFactorDevicePresence {
pub const Absent: SecondaryAuthenticationFactorDevicePresence = SecondaryAuthenticationFactorDevicePresence(0i32);
pub const Present: SecondaryAuthenticationFactorDevicePresence = SecondaryAuthenticationFactorDevicePresence(1i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorDevicePresence {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorDevicePresence {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorDevicePresence {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorDevicePresence;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorDevicePresence {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorDevicePresenceMonitoringMode(pub i32);
impl SecondaryAuthenticationFactorDevicePresenceMonitoringMode {
pub const Unsupported: SecondaryAuthenticationFactorDevicePresenceMonitoringMode = SecondaryAuthenticationFactorDevicePresenceMonitoringMode(0i32);
pub const AppManaged: SecondaryAuthenticationFactorDevicePresenceMonitoringMode = SecondaryAuthenticationFactorDevicePresenceMonitoringMode(1i32);
pub const SystemManaged: SecondaryAuthenticationFactorDevicePresenceMonitoringMode = SecondaryAuthenticationFactorDevicePresenceMonitoringMode(2i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorDevicePresenceMonitoringMode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorDevicePresenceMonitoringMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorDevicePresenceMonitoringMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorDevicePresenceMonitoringMode;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorDevicePresenceMonitoringMode {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus(pub i32);
impl SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus {
pub const Unsupported: SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus = SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus(0i32);
pub const Succeeded: SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus = SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus(1i32);
pub const DisabledByPolicy: SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus = SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus(2i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorFinishAuthenticationStatus(pub i32);
impl SecondaryAuthenticationFactorFinishAuthenticationStatus {
pub const Failed: SecondaryAuthenticationFactorFinishAuthenticationStatus = SecondaryAuthenticationFactorFinishAuthenticationStatus(0i32);
pub const Completed: SecondaryAuthenticationFactorFinishAuthenticationStatus = SecondaryAuthenticationFactorFinishAuthenticationStatus(1i32);
pub const NonceExpired: SecondaryAuthenticationFactorFinishAuthenticationStatus = SecondaryAuthenticationFactorFinishAuthenticationStatus(2i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorFinishAuthenticationStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorFinishAuthenticationStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorFinishAuthenticationStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorFinishAuthenticationStatus;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorFinishAuthenticationStatus {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryAuthenticationFactorInfo(pub ::windows::core::IInspectable);
impl SecondaryAuthenticationFactorInfo {
#[cfg(feature = "deprecated")]
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceFriendlyName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn DeviceModelNumber(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Storage_Streams")]
pub fn DeviceConfigurationData(&self) -> ::windows::core::Result<super::super::super::super::Storage::Streams::IBuffer> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::super::Storage::Streams::IBuffer>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn PresenceMonitoringMode(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorDevicePresenceMonitoringMode> {
let this = &::windows::core::Interface::cast::<ISecondaryAuthenticationFactorInfo2>(self)?;
unsafe {
let mut result__: SecondaryAuthenticationFactorDevicePresenceMonitoringMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorDevicePresenceMonitoringMode>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn UpdateDevicePresenceAsync(&self, presencestate: SecondaryAuthenticationFactorDevicePresence) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
let this = &::windows::core::Interface::cast::<ISecondaryAuthenticationFactorInfo2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), presencestate, &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn IsAuthenticationSupported(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ISecondaryAuthenticationFactorInfo2>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorInfo {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorInfo;{1e2ba861-8533-4fce-839b-ecb72410ac14})");
}
unsafe impl ::windows::core::Interface for SecondaryAuthenticationFactorInfo {
type Vtable = ISecondaryAuthenticationFactorInfo_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e2ba861_8533_4fce_839b_ecb72410ac14);
}
impl ::windows::core::RuntimeName for SecondaryAuthenticationFactorInfo {
const NAME: &'static str = "Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorInfo";
}
impl ::core::convert::From<SecondaryAuthenticationFactorInfo> for ::windows::core::IUnknown {
fn from(value: SecondaryAuthenticationFactorInfo) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorInfo> for ::windows::core::IUnknown {
fn from(value: &SecondaryAuthenticationFactorInfo) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryAuthenticationFactorInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecondaryAuthenticationFactorInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryAuthenticationFactorInfo> for ::windows::core::IInspectable {
fn from(value: SecondaryAuthenticationFactorInfo) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorInfo> for ::windows::core::IInspectable {
fn from(value: &SecondaryAuthenticationFactorInfo) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryAuthenticationFactorInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecondaryAuthenticationFactorInfo {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryAuthenticationFactorInfo {}
unsafe impl ::core::marker::Sync for SecondaryAuthenticationFactorInfo {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryAuthenticationFactorRegistration(pub ::windows::core::IInspectable);
impl SecondaryAuthenticationFactorRegistration {
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn FinishRegisteringDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>>(&self, deviceconfigurationdata: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), deviceconfigurationdata.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn AbortRegisteringDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, errorlogmessage: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), errorlogmessage.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn RequestStartRegisteringDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>, Param5: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>>(
deviceid: Param0,
capabilities: SecondaryAuthenticationFactorDeviceCapabilities,
devicefriendlyname: Param2,
devicemodelnumber: Param3,
devicekey: Param4,
mutualauthenticationkey: Param5,
) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorRegistrationResult>> {
Self::ISecondaryAuthenticationFactorRegistrationStatics(|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(), capabilities, devicefriendlyname.into_param().abi(), devicemodelnumber.into_param().abi(), devicekey.into_param().abi(), mutualauthenticationkey.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorRegistrationResult>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllRegisteredDeviceInfoAsync(querytype: SecondaryAuthenticationFactorDeviceFindScope) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<super::super::super::super::Foundation::Collections::IVectorView<SecondaryAuthenticationFactorInfo>>> {
Self::ISecondaryAuthenticationFactorRegistrationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), querytype, &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<super::super::super::super::Foundation::Collections::IVectorView<SecondaryAuthenticationFactorInfo>>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn UnregisterDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
Self::ISecondaryAuthenticationFactorRegistrationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn UpdateDeviceConfigurationDataAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>>(deviceid: Param0, deviceconfigurationdata: Param1) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
Self::ISecondaryAuthenticationFactorRegistrationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), deviceconfigurationdata.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn RegisterDevicePresenceMonitoringAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0, deviceinstancepath: Param1, monitoringmode: SecondaryAuthenticationFactorDevicePresenceMonitoringMode) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus>> {
Self::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics(|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(), deviceinstancepath.into_param().abi(), monitoringmode, &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn RegisterDevicePresenceMonitoringWithNewDeviceAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param4: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param5: ::windows::core::IntoParam<'a, super::super::super::super::Storage::Streams::IBuffer>>(
deviceid: Param0,
deviceinstancepath: Param1,
monitoringmode: SecondaryAuthenticationFactorDevicePresenceMonitoringMode,
devicefriendlyname: Param3,
devicemodelnumber: Param4,
deviceconfigurationdata: Param5,
) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus>> {
Self::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), deviceinstancepath.into_param().abi(), monitoringmode, devicefriendlyname.into_param().abi(), devicemodelnumber.into_param().abi(), deviceconfigurationdata.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncOperation<SecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatus>>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn UnregisterDevicePresenceMonitoringAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::super::super::Foundation::IAsyncAction> {
Self::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::super::super::Foundation::IAsyncAction>(result__)
})
}
#[cfg(feature = "deprecated")]
pub fn IsDevicePresenceMonitoringSupported() -> ::windows::core::Result<bool> {
Self::ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn ISecondaryAuthenticationFactorRegistrationStatics<R, F: FnOnce(&ISecondaryAuthenticationFactorRegistrationStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorRegistrationStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics<R, F: FnOnce(&ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SecondaryAuthenticationFactorRegistration, ISecondaryAuthenticationFactorDevicePresenceMonitoringRegistrationStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorRegistration {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorRegistration;{9f4cbbb4-8cba-48b0-840d-dbb22a54c678})");
}
unsafe impl ::windows::core::Interface for SecondaryAuthenticationFactorRegistration {
type Vtable = ISecondaryAuthenticationFactorRegistration_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9f4cbbb4_8cba_48b0_840d_dbb22a54c678);
}
impl ::windows::core::RuntimeName for SecondaryAuthenticationFactorRegistration {
const NAME: &'static str = "Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorRegistration";
}
impl ::core::convert::From<SecondaryAuthenticationFactorRegistration> for ::windows::core::IUnknown {
fn from(value: SecondaryAuthenticationFactorRegistration) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorRegistration> for ::windows::core::IUnknown {
fn from(value: &SecondaryAuthenticationFactorRegistration) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryAuthenticationFactorRegistration {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecondaryAuthenticationFactorRegistration {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryAuthenticationFactorRegistration> for ::windows::core::IInspectable {
fn from(value: SecondaryAuthenticationFactorRegistration) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorRegistration> for ::windows::core::IInspectable {
fn from(value: &SecondaryAuthenticationFactorRegistration) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryAuthenticationFactorRegistration {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecondaryAuthenticationFactorRegistration {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryAuthenticationFactorRegistration {}
unsafe impl ::core::marker::Sync for SecondaryAuthenticationFactorRegistration {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryAuthenticationFactorRegistrationResult(pub ::windows::core::IInspectable);
impl SecondaryAuthenticationFactorRegistrationResult {
#[cfg(feature = "deprecated")]
pub fn Status(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorRegistrationStatus> {
let this = self;
unsafe {
let mut result__: SecondaryAuthenticationFactorRegistrationStatus = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorRegistrationStatus>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn Registration(&self) -> ::windows::core::Result<SecondaryAuthenticationFactorRegistration> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SecondaryAuthenticationFactorRegistration>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorRegistrationResult {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorRegistrationResult;{a4fe35f0-ade3-4981-af6b-ec195921682a})");
}
unsafe impl ::windows::core::Interface for SecondaryAuthenticationFactorRegistrationResult {
type Vtable = ISecondaryAuthenticationFactorRegistrationResult_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa4fe35f0_ade3_4981_af6b_ec195921682a);
}
impl ::windows::core::RuntimeName for SecondaryAuthenticationFactorRegistrationResult {
const NAME: &'static str = "Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorRegistrationResult";
}
impl ::core::convert::From<SecondaryAuthenticationFactorRegistrationResult> for ::windows::core::IUnknown {
fn from(value: SecondaryAuthenticationFactorRegistrationResult) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorRegistrationResult> for ::windows::core::IUnknown {
fn from(value: &SecondaryAuthenticationFactorRegistrationResult) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryAuthenticationFactorRegistrationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a SecondaryAuthenticationFactorRegistrationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryAuthenticationFactorRegistrationResult> for ::windows::core::IInspectable {
fn from(value: SecondaryAuthenticationFactorRegistrationResult) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryAuthenticationFactorRegistrationResult> for ::windows::core::IInspectable {
fn from(value: &SecondaryAuthenticationFactorRegistrationResult) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryAuthenticationFactorRegistrationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a SecondaryAuthenticationFactorRegistrationResult {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryAuthenticationFactorRegistrationResult {}
unsafe impl ::core::marker::Sync for SecondaryAuthenticationFactorRegistrationResult {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SecondaryAuthenticationFactorRegistrationStatus(pub i32);
impl SecondaryAuthenticationFactorRegistrationStatus {
pub const Failed: SecondaryAuthenticationFactorRegistrationStatus = SecondaryAuthenticationFactorRegistrationStatus(0i32);
pub const Started: SecondaryAuthenticationFactorRegistrationStatus = SecondaryAuthenticationFactorRegistrationStatus(1i32);
pub const CanceledByUser: SecondaryAuthenticationFactorRegistrationStatus = SecondaryAuthenticationFactorRegistrationStatus(2i32);
pub const PinSetupRequired: SecondaryAuthenticationFactorRegistrationStatus = SecondaryAuthenticationFactorRegistrationStatus(3i32);
pub const DisabledByPolicy: SecondaryAuthenticationFactorRegistrationStatus = SecondaryAuthenticationFactorRegistrationStatus(4i32);
}
impl ::core::convert::From<i32> for SecondaryAuthenticationFactorRegistrationStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SecondaryAuthenticationFactorRegistrationStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SecondaryAuthenticationFactorRegistrationStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Security.Authentication.Identity.Provider.SecondaryAuthenticationFactorRegistrationStatus;i4)");
}
impl ::windows::core::DefaultType for SecondaryAuthenticationFactorRegistrationStatus {
type DefaultType = Self;
}
|
use super::{io, process, Runner, SubCommand};
use std::io::Write;
impl<'api, 'pin> Runner<'api, 'pin> {
pub fn upgrade(&self, cmd: &SubCommand) {
debug!("Starting in upgrade");
match *cmd {
SubCommand::SelfUpdate { check, download } => {
if check && download {
eprintln!("Cannont check & download at the same time!");
process::exit(1);
}
let json_format = self.config.as_ref().unwrap().can_use_json();
if check {
let none: Option<Vec<(&str, &str)>> = None;
match self.get_upgrade_item() {
Ok(item) => {
let upgrade_item = if let Some(item) = item {
debug!("Created item to show workflow upgrade is available.");
item
} else {
debug!("Created item to show NO upgrade is available.");
alfred::ItemBuilder::new("You have the latest version of workflow!")
.icon_path("auto_update.png")
.variable("workflow_update_ready", "0")
.arg("update")
.into_item()
};
crate::write_to_alfred(vec![upgrade_item], json_format, none);
}
Err(e) => {
debug!("Error in fetching update status {:?}", e);
let item = alfred::ItemBuilder::new("Error in getting upgrade info")
.into_item();
crate::write_to_alfred(vec![item], json_format, none);
}
}
} else if download {
let filename = self.updater.as_ref().unwrap().download_latest();
if let Ok(filename) = filename {
if let Some(p) = filename.to_str() {
io::stdout()
.write_all(["Download Successful: ", p].concat().as_bytes())
.expect("Couldn't write to output!");
} else {
io::stdout()
.write_all(b"Error: Download OK, issue with its file name!")
.expect("Couldn't write to output!");
}
} else {
let _r = io::stdout()
.write_all(b"Error: Couldn't download the latest workflow.");
debug!("Download error: {:?}", filename.unwrap_err());
process::exit(1);
}
}
}
_ => unreachable!(),
}
}
}
|
use core::ops::ControlFlow;
use firefly_diagnostics::{CodeMap, SourceSpan};
use firefly_intern::{symbols, Ident, Symbol};
use firefly_number::Integer;
use firefly_pass::Pass;
use crate::ast::*;
use crate::lexer::DelayedSubstitution;
use crate::visit::{self as visit, VisitMut};
/// This pass expands all delayed macro substitutions to their corresponding terms.
///
/// After this pass completes, the following is true of the AST:
///
/// * All `Expr::DelayedSubstitution` nodes have been replaced with `Expr::Literal` nodes
#[derive(Debug)]
pub struct ExpandSubstitutions<'cm> {
module: Ident,
codemap: &'cm CodeMap,
}
impl<'cm> ExpandSubstitutions<'cm> {
pub fn new(module: Ident, codemap: &'cm CodeMap) -> Self {
Self { module, codemap }
}
}
impl<'cm> Pass for ExpandSubstitutions<'cm> {
type Input<'a> = &'a mut Function;
type Output<'a> = &'a mut Function;
fn run<'a>(&mut self, f: Self::Input<'a>) -> anyhow::Result<Self::Output<'a>> {
let mut visitor = ExpandSubstitutionsVisitor::new(self.module, self.codemap, f);
match visitor.visit_mut_function(f) {
ControlFlow::Continue(_) => Ok(f),
ControlFlow::Break(err) => Err(err),
}
}
}
struct ExpandSubstitutionsVisitor<'cm> {
codemap: &'cm CodeMap,
module: Ident,
name: Ident,
arity: u8,
}
impl<'cm> ExpandSubstitutionsVisitor<'cm> {
fn new(module: Ident, codemap: &'cm CodeMap, f: &Function) -> Self {
Self {
codemap,
module,
name: f.name,
arity: f.arity,
}
}
fn fix(&mut self, span: &SourceSpan, sub: DelayedSubstitution) -> Expr {
// It shouldn't be possible for this expression to exist outside of a function context
match sub {
DelayedSubstitution::Module => Expr::Literal(Literal::Atom(self.module)),
DelayedSubstitution::ModuleString => Expr::Literal(Literal::String(self.module)),
DelayedSubstitution::FunctionName => Expr::Literal(Literal::Atom(self.name)),
DelayedSubstitution::FunctionArity => {
Expr::Literal(Literal::Integer(*span, self.arity.into()))
}
DelayedSubstitution::File => {
let span = *span;
if let Ok(filename) = self.codemap.name_for_span(span) {
let file = Ident::new(Symbol::intern(&filename.to_string()), span);
Expr::Literal(Literal::String(file))
} else {
Expr::Literal(Literal::String(Ident::new(symbols::Empty, span)))
}
}
DelayedSubstitution::Line => {
let span = *span;
if let Ok(loc) = self.codemap.location_for_span(span) {
let line = loc.line.number().to_usize() as i64;
Expr::Literal(Literal::Integer(span, Integer::Small(line)))
} else {
Expr::Literal(Literal::Integer(span, Integer::Small(0)))
}
}
}
}
}
impl<'cm> VisitMut<anyhow::Error> for ExpandSubstitutionsVisitor<'cm> {
fn visit_mut_expr(&mut self, expr: &mut Expr) -> ControlFlow<anyhow::Error> {
if let Expr::DelayedSubstitution(ref span, sub) = expr {
*expr = self.fix(span, *sub);
ControlFlow::Continue(())
} else {
visit::visit_mut_expr(self, expr)
}
}
fn visit_mut_pattern(&mut self, pattern: &mut Expr) -> ControlFlow<anyhow::Error> {
if let Expr::DelayedSubstitution(ref span, sub) = pattern {
*pattern = self.fix(span, *sub);
ControlFlow::Continue(())
} else {
visit::visit_mut_pattern(self, pattern)
}
}
}
|
#[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "tr";
#[test]
fn test_toupper() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["a-z", "A-Z"]).run_piped_stdin("!abcd!");
assert_eq!(result.stdout, "!ABCD!");
}
#[test]
fn test_small_set2() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["0-9", "X"]).run_piped_stdin("@0123456789");
assert_eq!(result.stdout, "@XXXXXXXXXX");
}
#[test]
fn test_unicode() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&[", ┬─┬", "╯︵┻━┻"])
.run_piped_stdin("(,°□°), ┬─┬".as_bytes());
assert_eq!(result.stdout, "(╯°□°)╯︵┻━┻");
}
#[test]
fn test_delete() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-d", "a-z"]).run_piped_stdin("aBcD");
assert_eq!(result.stdout, "BD");
}
#[test]
fn test_delete_complement() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-d", "-c", "a-z"]).run_piped_stdin("aBcD");
assert_eq!(result.stdout, "ac");
}
|
use std::time::{Duration, Instant};
use futures::{Async, Future, Stream};
use tower::Service;
use tower_grpc;
use tokio_core::reactor::Handle;
use super::codec::Protobuf;
use super::pb::proxy::telemetry::{ReportRequest, ReportResponse};
use super::pb::proxy::telemetry::client::Telemetry as TelemetrySvc;
use super::pb::proxy::telemetry::client::telemetry_methods::Report as ReportRpc;
use ::timeout::{Timeout, TimeoutFuture};
pub type ClientBody = tower_grpc::client::codec::EncodingBody<
Protobuf<ReportRequest, ReportResponse>,
tower_grpc::client::codec::Unary<ReportRequest>,
>;
type TelemetryStream<F> = tower_grpc::client::BodyFuture<
tower_grpc::client::Unary<
tower_grpc::client::ResponseFuture<Protobuf<ReportRequest, ReportResponse>, TimeoutFuture<F>>,
Protobuf<ReportRequest, ReportResponse>,
>,
>;
#[derive(Debug)]
pub struct Telemetry<T, F> {
reports: T,
in_flight: Option<(Instant, TelemetryStream<F>)>,
report_timeout: Duration,
handle: Handle,
}
impl<T, F> Telemetry<T, F>
where
T: Stream<Item = ReportRequest>,
T::Error: ::std::fmt::Debug,
F: Future<Item = ::http::Response<::tower_h2::RecvBody>>,
F::Error: ::std::fmt::Debug,
{
pub fn new(reports: T, report_timeout: Duration, handle: &Handle) -> Self {
Telemetry {
reports,
in_flight: None,
report_timeout,
handle: handle.clone(),
}
}
pub fn poll_rpc<S>(&mut self, client: &mut S)
where
S: Service<
Request = ::http::Request<ClientBody>,
Response = F::Item,
Error = F::Error,
Future = F,
>,
{
let client = Timeout::new(client, self.report_timeout, &self.handle);
let grpc = tower_grpc::Client::new(Protobuf::new(), client);
let mut rpc = ReportRpc::new(grpc);
//let _ctxt = ::logging::context("Telemetry.Report".into());
loop {
trace!("poll_rpc");
if let Some((t0, mut fut)) = self.in_flight.take() {
match fut.poll() {
Ok(Async::NotReady) => {
// TODO: can we just move this logging logic to `Timeout`?
trace!("report in flight to controller for {:?}", t0.elapsed());
self.in_flight = Some((t0, fut))
}
Ok(Async::Ready(_)) => {
trace!("report sent to controller in {:?}", t0.elapsed())
}
Err(err) => warn!("controller error: {:?}", err),
}
}
let controller_ready = self.in_flight.is_none() && match rpc.poll_ready() {
Ok(Async::Ready(_)) => true,
Ok(Async::NotReady) => {
trace!("controller unavailable");
false
}
Err(err) => {
warn!("controller error: {:?}", err);
false
}
};
match self.reports.poll() {
Ok(Async::NotReady) => {
return;
}
Ok(Async::Ready(None)) => {
error!("report stream complete");
return;
}
Err(err) => {
warn!("report stream error: {:?}", err);
}
Ok(Async::Ready(Some(report))) => {
// Attempt to send the report. Continue looping so that `reports` is
// polled until it's not ready.
if !controller_ready {
info!(
"report dropped; requests={} accepts={} connects={}",
report.requests.len(),
report.server_transports.len(),
report.client_transports.len(),
);
} else {
trace!(
"report sent; requests={} accepts={} connects={}",
report.requests.len(),
report.server_transports.len(),
report.client_transports.len(),
);
let rep = TelemetrySvc::new(&mut rpc).report(report);
self.in_flight = Some((Instant::now(), rep));
}
}
}
}
}
}
|
import std._vec;
import std._str;
import std.io;
import std.option;
import front.ast;
import front.lexer;
import util.common;
import pp.end; import pp.wrd; import pp.space; import pp.line;
const uint indent_unit = 4u;
const int as_prec = 5;
const uint default_columns = 78u;
type ps = @rec(pp.ps s,
option.t[vec[lexer.cmnt]] comments,
mutable uint cur_cmnt);
fn print_file(ast._mod _mod, str filename, io.writer out) {
auto cmnts = lexer.gather_comments(filename);
auto s = @rec(s=pp.mkstate(out, default_columns),
comments=option.some[vec[lexer.cmnt]](cmnts),
mutable cur_cmnt=0u);
print_mod(s, _mod);
}
fn ty_to_str(&@ast.ty ty) -> str {
auto writer = io.string_writer();
auto s = @rec(s=pp.mkstate(writer.get_writer(), 0u),
comments=option.none[vec[lexer.cmnt]],
mutable cur_cmnt=0u);
print_type(s, ty);
ret writer.get_str();
}
fn block_to_str(&ast.block blk) -> str {
auto writer = io.string_writer();
auto s = @rec(s=pp.mkstate(writer.get_writer(), 78u),
comments=option.none[vec[lexer.cmnt]],
mutable cur_cmnt=0u);
print_block(s, blk);
ret writer.get_str();
}
fn expr_to_str(&@ast.expr e) -> str {
auto writer = io.string_writer();
auto s = @rec(s=pp.mkstate(writer.get_writer(), 78u),
comments=option.none[vec[lexer.cmnt]],
mutable cur_cmnt=0u);
print_expr(s, e);
ret writer.get_str();
}
fn pat_to_str(&@ast.pat p) -> str {
auto writer = io.string_writer();
auto s = @rec(s=pp.mkstate(writer.get_writer(), 78u),
comments=option.none[vec[lexer.cmnt]],
mutable cur_cmnt=0u);
print_pat(s, p);
ret writer.get_str();
}
fn hbox(ps s) {
pp.hbox(s.s, indent_unit);
}
fn wrd1(ps s, str word) {
wrd(s.s, word);
space(s.s);
}
fn popen(ps s) {
wrd(s.s, "(");
pp.abox(s.s);
}
fn popen_h(ps s) {
wrd(s.s, "(");
pp.hbox(s.s, 0u);
}
fn pclose(ps s) {
end(s.s);
wrd(s.s, ")");
}
fn bopen(ps s) {
wrd(s.s, "{");
pp.vbox(s.s, indent_unit);
line(s.s);
}
fn bclose(ps s) {
end(s.s);
pp.cwrd(s.s, "}");
}
fn bclose_c(ps s, common.span span) {
maybe_print_comment(s, span.hi);
bclose(s);
}
fn commasep[IN](ps s, vec[IN] elts, fn(ps, &IN) op) {
auto first = true;
for (IN elt in elts) {
if (first) {first = false;}
else {wrd1(s, ",");}
op(s, elt);
}
}
fn commasep_cmnt[IN](ps s, vec[IN] elts, fn(ps, &IN) op,
fn(&IN) -> common.span get_span) {
auto len = _vec.len[IN](elts);
auto i = 0u;
for (IN elt in elts) {
op(s, elt);
i += 1u;
if (i < len) {
wrd(s.s, ",");
if (!maybe_print_line_comment(s, get_span(elt))) {space(s.s);}
}
}
}
fn commasep_exprs(ps s, vec[@ast.expr] exprs) {
fn expr_span(&@ast.expr expr) -> common.span {ret expr.span;}
auto f = print_expr;
auto gs = expr_span;
commasep_cmnt[@ast.expr](s, exprs, f, gs);
}
fn print_mod(ps s, ast._mod _mod) {
for (@ast.view_item vitem in _mod.view_items) {print_view_item(s, vitem);}
line(s.s);
for (@ast.item item in _mod.items) {print_item(s, item);}
print_remaining_comments(s);
}
fn print_type(ps s, &@ast.ty ty) {
maybe_print_comment(s, ty.span.lo);
hbox(s);
alt (ty.node) {
case (ast.ty_nil) {wrd(s.s, "()");}
case (ast.ty_bool) {wrd(s.s, "bool");}
case (ast.ty_int) {wrd(s.s, "int");}
case (ast.ty_uint) {wrd(s.s, "uint");}
case (ast.ty_float) {wrd(s.s, "float");}
case (ast.ty_machine(?tm)) {wrd(s.s, common.ty_mach_to_str(tm));}
case (ast.ty_char) {wrd(s.s, "char");}
case (ast.ty_str) {wrd(s.s, "str");}
case (ast.ty_box(?mt)) {wrd(s.s, "@"); print_mt(s, mt);}
case (ast.ty_vec(?mt)) {
wrd(s.s, "vec["); print_mt(s, mt); wrd(s.s, "]");
}
case (ast.ty_port(?t)) {
wrd(s.s, "port["); print_type(s, t); wrd(s.s, "]");
}
case (ast.ty_chan(?t)) {
wrd(s.s, "chan["); print_type(s, t); wrd(s.s, "]");
}
case (ast.ty_type) {wrd(s.s, "type");}
case (ast.ty_tup(?elts)) {
wrd(s.s, "tup");
popen(s);
auto f = print_mt;
commasep[ast.mt](s, elts, f);
pclose(s);
}
case (ast.ty_rec(?fields)) {
wrd(s.s, "rec");
popen(s);
fn print_field(ps s, &ast.ty_field f) {
hbox(s);
print_mt(s, f.mt);
space(s.s);
wrd(s.s, f.ident);
end(s.s);
}
fn get_span(&ast.ty_field f) -> common.span {
// Try to reconstruct the span for this field
auto sp = f.mt.ty.span;
auto hi = sp.hi + _str.char_len(f.ident) + 1u;
ret rec(hi=hi with sp);
}
auto f = print_field;
auto gs = get_span;
commasep_cmnt[ast.ty_field](s, fields, f, gs);
pclose(s);
}
case (ast.ty_obj(?methods)) {
wrd1(s, "obj");
bopen(s);
for (ast.ty_method m in methods) {
hbox(s);
print_ty_fn(s, m.proto, option.some[str](m.ident),
m.inputs, m.output);
wrd(s.s, ";");
end(s.s);
line(s.s);
}
bclose_c(s, ty.span);
}
case (ast.ty_fn(?proto,?inputs,?output)) {
print_ty_fn(s, proto, option.none[str], inputs, output);
}
case (ast.ty_path(?path,_)) {
print_path(s, path);
}
}
end(s.s);
}
fn print_item(ps s, @ast.item item) {
maybe_print_comment(s, item.span.lo);
hbox(s);
alt (item.node) {
case (ast.item_const(?id, ?ty, ?expr, _, _)) {
wrd1(s, "const");
print_type(s, ty);
space(s.s);
wrd1(s, id);
wrd1(s, "=");
print_expr(s, expr);
wrd(s.s, ";");
}
case (ast.item_fn(?name,?_fn,?typarams,_,_)) {
print_fn(s, _fn.decl, name, typarams);
space(s.s);
print_block(s, _fn.body);
}
case (ast.item_mod(?id,?_mod,_)) {
wrd1(s, "mod");
wrd1(s, id);
bopen(s);
for (@ast.item itm in _mod.items) {print_item(s, itm);}
bclose_c(s, item.span);
}
case (ast.item_native_mod(?id,?nmod,_)) {
wrd1(s, "native");
alt (nmod.abi) {
case (ast.native_abi_rust) {wrd1(s, "\"rust\"");}
case (ast.native_abi_cdecl) {wrd1(s, "\"cdecl\"");}
}
wrd1(s, "mod");
wrd1(s, id);
bopen(s);
for (@ast.native_item item in nmod.items) {
hbox(s);
maybe_print_comment(s, item.span.lo);
alt (item.node) {
case (ast.native_item_ty(?id,_)) {
wrd1(s, "type");
wrd(s.s, id);
}
case (ast.native_item_fn(?id,?lname,?decl,
?typarams,_,_)) {
print_fn(s, decl, id, typarams);
alt (lname) {
case (option.none[str]) {}
case (option.some[str](?ss)) {
print_string(s, ss);
}
}
}
}
wrd(s.s, ";");
end(s.s);
}
bclose_c(s, item.span);
}
case (ast.item_ty(?id,?ty,?params,_,_)) {
wrd1(s, "type");
wrd(s.s, id);
print_type_params(s, params);
space(s.s);
wrd1(s, "=");
print_type(s, ty);
wrd(s.s, ";");
}
case (ast.item_tag(?id,?variants,?params,_,_)) {
wrd1(s, "tag");
wrd(s.s, id);
print_type_params(s, params);
space(s.s);
bopen(s);
for (ast.variant v in variants) {
maybe_print_comment(s, v.span.lo);
wrd(s.s, v.node.name);
if (_vec.len[ast.variant_arg](v.node.args) > 0u) {
popen(s);
fn print_variant_arg(ps s, &ast.variant_arg arg) {
print_type(s, arg.ty);
}
auto f = print_variant_arg;
commasep[ast.variant_arg](s, v.node.args, f);
pclose(s);
}
wrd(s.s, ";");
if (!maybe_print_line_comment(s, v.span)) {line(s.s);}
}
bclose_c(s, item.span);
}
case (ast.item_obj(?id,?_obj,?params,_,_)) {
wrd1(s, "obj");
wrd(s.s, id);
print_type_params(s, params);
popen(s);
fn print_field(ps s, &ast.obj_field field) {
hbox(s);
print_type(s, field.ty);
space(s.s);
wrd(s.s, field.ident);
end(s.s);
}
fn get_span(&ast.obj_field f) -> common.span {ret f.ty.span;}
auto f = print_field;
auto gs = get_span;
commasep_cmnt[ast.obj_field](s, _obj.fields, f, gs);
pclose(s);
space(s.s);
bopen(s);
for (@ast.method meth in _obj.methods) {
hbox(s);
let vec[ast.ty_param] typarams = vec();
maybe_print_comment(s, meth.span.lo);
print_fn(s, meth.node.meth.decl, meth.node.ident, typarams);
space(s.s);
print_block(s, meth.node.meth.body);
end(s.s);
line(s.s);
}
alt (_obj.dtor) {
case (option.some[@ast.method](?dtor)) {
hbox(s);
wrd1(s, "close");
print_block(s, dtor.node.meth.body);
end(s.s);
line(s.s);
}
case (_) {}
}
bclose_c(s, item.span);
}
}
end(s.s);
line(s.s);
line(s.s);
}
fn print_block(ps s, ast.block blk) {
maybe_print_comment(s, blk.span.lo);
bopen(s);
for (@ast.stmt st in blk.node.stmts) {
maybe_print_comment(s, st.span.lo);
alt (st.node) {
case (ast.stmt_decl(?decl,_)) {print_decl(s, decl);}
case (ast.stmt_expr(?expr,_)) {print_expr(s, expr);}
}
if (front.parser.stmt_ends_with_semi(st)) {wrd(s.s, ";");}
if (!maybe_print_line_comment(s, st.span)) {line(s.s);}
}
alt (blk.node.expr) {
case (option.some[@ast.expr](?expr)) {
print_expr(s, expr);
if (!maybe_print_line_comment(s, expr.span)) {line(s.s);}
}
case (_) {}
}
bclose_c(s, blk.span);
}
fn print_literal(ps s, @ast.lit lit) {
maybe_print_comment(s, lit.span.lo);
alt (lit.node) {
case (ast.lit_str(?st)) {print_string(s, st);}
case (ast.lit_char(?ch)) {
wrd(s.s, "'" + escape_str(_str.from_bytes(vec(ch as u8)), '\'')
+ "'");
}
case (ast.lit_int(?val)) {
wrd(s.s, common.istr(val));
}
case (ast.lit_uint(?val)) { // FIXME clipping? uistr?
wrd(s.s, common.istr(val as int) + "u");
}
case (ast.lit_float(?fstr)) {
wrd(s.s, fstr);
}
case (ast.lit_mach_int(?mach,?val)) {
wrd(s.s, common.istr(val as int));
wrd(s.s, common.ty_mach_to_str(mach));
}
case (ast.lit_mach_float(?mach,?val)) {
// val is already a str
wrd(s.s, val);
wrd(s.s, common.ty_mach_to_str(mach));
}
case (ast.lit_nil) {wrd(s.s, "()");}
case (ast.lit_bool(?val)) {
if (val) {wrd(s.s, "true");} else {wrd(s.s, "false");}
}
}
}
fn print_expr(ps s, &@ast.expr expr) {
maybe_print_comment(s, expr.span.lo);
hbox(s);
alt (expr.node) {
case (ast.expr_vec(?exprs,?mut,_)) {
if (mut == ast.mut) {
wrd1(s, "mutable");
}
wrd(s.s, "vec");
popen(s);
commasep_exprs(s, exprs);
pclose(s);
}
case (ast.expr_tup(?exprs,_)) {
fn printElt(ps s, &ast.elt elt) {
hbox(s);
if (elt.mut == ast.mut) {wrd1(s, "mutable");}
print_expr(s, elt.expr);
end(s.s);
}
fn get_span(&ast.elt elt) -> common.span {ret elt.expr.span;}
wrd(s.s, "tup");
popen(s);
auto f = printElt;
auto gs = get_span;
commasep_cmnt[ast.elt](s, exprs, f, gs);
pclose(s);
}
case (ast.expr_rec(?fields,?wth,_)) {
fn print_field(ps s, &ast.field field) {
hbox(s);
if (field.mut == ast.mut) {wrd1(s, "mutable");}
wrd(s.s, field.ident);
wrd(s.s, "=");
print_expr(s, field.expr);
end(s.s);
}
fn get_span(&ast.field field) -> common.span {
ret field.expr.span;
}
wrd(s.s, "rec");
popen(s);
auto f = print_field;
auto gs = get_span;
commasep_cmnt[ast.field](s, fields, f, gs);
alt (wth) {
case (option.some[@ast.expr](?expr)) {
if (_vec.len[ast.field](fields) > 0u) {space(s.s);}
hbox(s);
wrd1(s, "with");
print_expr(s, expr);
end(s.s);
}
case (_) {}
}
pclose(s);
}
case (ast.expr_call(?func,?args,_)) {
print_expr(s, func);
popen(s);
commasep_exprs(s, args);
pclose(s);
}
case (ast.expr_self_method(?ident,_)) {
wrd(s.s, "self.");
print_ident(s, ident);
}
case (ast.expr_bind(?func,?args,_)) {
fn print_opt(ps s, &option.t[@ast.expr] expr) {
alt (expr) {
case (option.some[@ast.expr](?expr)) {
print_expr(s, expr);
}
case (_) {wrd(s.s, "_");}
}
}
wrd1(s, "bind");
print_expr(s, func);
popen(s);
auto f = print_opt;
commasep[option.t[@ast.expr]](s, args, f);
pclose(s);
}
case (ast.expr_spawn(_,_,?e,?es,_)) {
wrd1(s, "spawn");
print_expr(s, e);
popen(s);
commasep_exprs(s, es);
pclose(s);
}
case (ast.expr_binary(?op,?lhs,?rhs,_)) {
auto prec = operator_prec(op);
print_maybe_parens(s, lhs, prec);
space(s.s);
wrd1(s, ast.binop_to_str(op));
print_maybe_parens(s, rhs, prec + 1);
}
case (ast.expr_unary(?op,?expr,_)) {
wrd(s.s, ast.unop_to_str(op));
print_expr(s, expr);
}
case (ast.expr_lit(?lit,_)) {
print_literal(s, lit);
}
case (ast.expr_cast(?expr,?ty,_)) {
print_maybe_parens(s, expr, as_prec);
space(s.s);
wrd1(s, "as");
print_type(s, ty);
}
case (ast.expr_if(?test,?block,?elseopt,_)) {
wrd1(s, "if");
popen_h(s);
print_expr(s, test);
pclose(s);
space(s.s);
print_block(s, block);
alt (elseopt) {
case (option.some[@ast.expr](?_else)) {
space(s.s);
wrd1(s, "else");
print_expr(s, _else);
}
case (_) { /* fall through */ }
}
}
case (ast.expr_while(?test,?block,_)) {
wrd1(s, "while");
popen_h(s);
print_expr(s, test);
pclose(s);
space(s.s);
print_block(s, block);
}
case (ast.expr_for(?decl,?expr,?block,_)) {
wrd1(s, "for");
popen_h(s);
print_for_decl(s, decl);
space(s.s);
wrd1(s, "in");
print_expr(s, expr);
pclose(s);
space(s.s);
print_block(s, block);
}
case (ast.expr_for_each(?decl,?expr,?block,_)) {
wrd1(s, "for each");
popen_h(s);
print_for_decl(s, decl);
space(s.s);
wrd1(s, "in");
print_expr(s, expr);
pclose(s);
space(s.s);
print_block(s, block);
}
case (ast.expr_do_while(?block,?expr,_)) {
wrd1(s, "do");
space(s.s);
print_block(s, block);
space(s.s);
wrd1(s, "while");
popen_h(s);
print_expr(s, expr);
pclose(s);
}
case (ast.expr_alt(?expr,?arms,_)) {
wrd1(s, "alt");
popen_h(s);
print_expr(s, expr);
pclose(s);
space(s.s);
bopen(s);
for (ast.arm arm in arms) {
hbox(s);
wrd1(s, "case");
popen_h(s);
print_pat(s, arm.pat);
pclose(s);
space(s.s);
print_block(s, arm.block);
end(s.s);
line(s.s);
}
bclose_c(s, expr.span);
}
case (ast.expr_block(?block,_)) {
print_block(s, block);
}
case (ast.expr_assign(?lhs,?rhs,_)) {
print_expr(s, lhs);
space(s.s);
wrd1(s, "=");
print_expr(s, rhs);
}
case (ast.expr_assign_op(?op,?lhs,?rhs,_)) {
print_expr(s, lhs);
space(s.s);
wrd(s.s, ast.binop_to_str(op));
wrd1(s, "=");
print_expr(s, rhs);
}
case (ast.expr_send(?lhs, ?rhs, _)) {
print_expr(s, lhs);
space(s.s);
wrd1(s, "<|");
print_expr(s, rhs);
}
case (ast.expr_recv(?lhs, ?rhs, _)) {
print_expr(s, lhs);
space(s.s);
wrd1(s, "<-");
print_expr(s, rhs);
}
case (ast.expr_field(?expr,?id,_)) {
print_expr(s, expr);
wrd(s.s, ".");
wrd(s.s, id);
}
case (ast.expr_index(?expr,?index,_)) {
print_expr(s, expr);
wrd(s.s, ".");
popen_h(s);
print_expr(s, index);
pclose(s);
}
case (ast.expr_path(?path,_,_)) {
print_path(s, path);
}
case (ast.expr_fail(_)) {
wrd(s.s, "fail");
}
case (ast.expr_break(_)) {
wrd(s.s, "break");
}
case (ast.expr_cont(_)) {
wrd(s.s, "cont");
}
case (ast.expr_ret(?result,_)) {
wrd(s.s, "ret");
alt (result) {
case (option.some[@ast.expr](?expr)) {
space(s.s);
print_expr(s, expr);
}
case (_) {}
}
}
case (ast.expr_put(?result,_)) {
wrd(s.s, "put");
alt (result) {
case (option.some[@ast.expr](?expr)) {
space(s.s);
print_expr(s, expr);
}
case (_) {}
}
}
case (ast.expr_be(?result,_)) {
wrd1(s, "be");
print_expr(s, result);
}
case (ast.expr_log(?lvl,?expr,_)) {
alt (lvl) {
case (1) {wrd1(s, "log");}
case (0) {wrd1(s, "log_err");}
}
print_expr(s, expr);
}
case (ast.expr_check_expr(?expr,_)) {
wrd1(s, "check");
popen_h(s);
print_expr(s, expr);
pclose(s);
}
case (ast.expr_ext(?path, ?args, ?body, _, _)) {
wrd(s.s, "#");
print_path(s, path);
if (_vec.len[@ast.expr](args) > 0u) {
popen(s);
commasep_exprs(s, args);
pclose(s);
}
// FIXME: extension 'body'
}
case (ast.expr_port(_)) {
wrd(s.s, "port");
popen_h(s);
pclose(s);
}
case (ast.expr_chan(?expr, _)) {
wrd(s.s, "chan");
popen_h(s);
print_expr(s, expr);
pclose(s);
}
}
end(s.s);
}
fn print_decl(ps s, @ast.decl decl) {
maybe_print_comment(s, decl.span.lo);
hbox(s);
alt (decl.node) {
case (ast.decl_local(?loc)) {
alt (loc.ty) {
case (option.some[@ast.ty](?ty)) {
wrd1(s, "let");
print_type(s, ty);
space(s.s);
}
case (_) {
wrd1(s, "auto");
}
}
wrd(s.s, loc.ident);
alt (loc.init) {
case (option.some[ast.initializer](?init)) {
space(s.s);
alt (init.op) {
case (ast.init_assign) {
wrd1(s, "=");
}
case (ast.init_recv) {
wrd1(s, "<-");
}
}
print_expr(s, init.expr);
}
case (_) {}
}
}
case (ast.decl_item(?item)) {
print_item(s, item);
}
}
end(s.s);
}
fn print_ident(ps s, ast.ident ident) {
wrd(s.s, ident);
}
fn print_for_decl(ps s, @ast.decl decl) {
alt (decl.node) {
case (ast.decl_local(?loc)) {
print_type(s, option.get[@ast.ty](loc.ty));
space(s.s);
wrd(s.s, loc.ident);
}
}
}
fn print_path(ps s, ast.path path) {
maybe_print_comment(s, path.span.lo);
auto first = true;
for (str id in path.node.idents) {
if (first) {first = false;}
else {wrd(s.s, ".");}
wrd(s.s, id);
}
if (_vec.len[@ast.ty](path.node.types) > 0u) {
wrd(s.s, "[");
auto f = print_type;
commasep[@ast.ty](s, path.node.types, f);
wrd(s.s, "]");
}
}
fn print_pat(ps s, &@ast.pat pat) {
maybe_print_comment(s, pat.span.lo);
alt (pat.node) {
case (ast.pat_wild(_)) {wrd(s.s, "_");}
case (ast.pat_bind(?id,_,_)) {wrd(s.s, "?" + id);}
case (ast.pat_lit(?lit,_)) {print_literal(s, lit);}
case (ast.pat_tag(?path,?args,_,_)) {
print_path(s, path);
if (_vec.len[@ast.pat](args) > 0u) {
popen_h(s);
auto f = print_pat;
commasep[@ast.pat](s, args, f);
pclose(s);
}
}
}
}
fn print_fn(ps s, ast.fn_decl decl, str name,
vec[ast.ty_param] typarams) {
wrd1(s, "fn");
wrd(s.s, name);
print_type_params(s, typarams);
popen(s);
fn print_arg(ps s, &ast.arg x) {
hbox(s);
if (x.mode == ast.alias) {wrd(s.s, "&");}
print_type(s, x.ty);
space(s.s);
wrd(s.s, x.ident);
end(s.s);
}
auto f = print_arg;
commasep[ast.arg](s, decl.inputs, f);
pclose(s);
maybe_print_comment(s, decl.output.span.lo);
if (decl.output.node != ast.ty_nil) {
space(s.s);
hbox(s);
wrd1(s, "->");
print_type(s, decl.output);
end(s.s);
}
}
fn print_type_params(ps s, vec[ast.ty_param] params) {
if (_vec.len[ast.ty_param](params) > 0u) {
wrd(s.s, "[");
fn printParam(ps s, &ast.ty_param param) {
wrd(s.s, param);
}
auto f = printParam;
commasep[ast.ty_param](s, params, f);
wrd(s.s, "]");
}
}
fn print_view_item(ps s, @ast.view_item item) {
maybe_print_comment(s, item.span.lo);
hbox(s);
alt (item.node) {
case (ast.view_item_use(?id,?mta,_,_)) {
wrd1(s, "use");
wrd(s.s, id);
if (_vec.len[@ast.meta_item](mta) > 0u) {
popen(s);
fn print_meta(ps s, &@ast.meta_item item) {
hbox(s);
wrd1(s, item.node.name);
wrd1(s, "=");
print_string(s, item.node.value);
end(s.s);
}
auto f = print_meta;
commasep[@ast.meta_item](s, mta, f);
pclose(s);
}
}
case (ast.view_item_import(?id,?ids,_,_)) {
wrd1(s, "import");
if (!_str.eq(id, ids.(_vec.len[str](ids)-1u))) {
wrd1(s, id);
wrd1(s, "=");
}
auto first = true;
for (str elt in ids) {
if (first) {first = false;}
else {wrd(s.s, ".");}
wrd(s.s, elt);
}
}
case (ast.view_item_export(?id)) {
wrd1(s, "export");
wrd(s.s, id);
}
}
end(s.s);
wrd(s.s, ";");
line(s.s);
}
// FIXME: The fact that this builds up the table anew for every call is
// not good. Eventually, table should be a const.
fn operator_prec(ast.binop op) -> int {
for (front.parser.op_spec spec in front.parser.prec_table()) {
if (spec.op == op) {ret spec.prec;}
}
fail;
}
fn print_maybe_parens(ps s, @ast.expr expr, int outer_prec) {
auto add_them;
alt (expr.node) {
case (ast.expr_binary(?op,_,_,_)) {
add_them = operator_prec(op) < outer_prec;
}
case (ast.expr_cast(_,_,_)) {
add_them = as_prec < outer_prec;
}
case (_) {
add_them = false;
}
}
if (add_them) {popen(s);}
print_expr(s, expr);
if (add_them) {pclose(s);}
}
fn escape_str(str st, char to_escape) -> str {
let str out = "";
auto len = _str.byte_len(st);
auto i = 0u;
while (i < len) {
alt (st.(i) as char) {
case ('\n') {out += "\\n";}
case ('\t') {out += "\\t";}
case ('\r') {out += "\\r";}
case ('\\') {out += "\\\\";}
case (?cur) {
if (cur == to_escape) {out += "\\";}
_str.push_byte(out, cur as u8);
}
}
i += 1u;
}
ret out;
}
fn print_mt(ps s, &ast.mt mt) {
alt (mt.mut) {
case (ast.mut) { wrd1(s, "mutable"); }
case (ast.maybe_mut) { wrd1(s, "mutable?"); }
case (ast.imm) { /* nothing */ }
}
print_type(s, mt.ty);
}
fn print_string(ps s, str st) {
wrd(s.s, "\""); wrd(s.s, escape_str(st, '"')); wrd(s.s, "\"");
}
fn print_ty_fn(ps s, ast.proto proto, option.t[str] id,
vec[ast.ty_arg] inputs, @ast.ty output) {
if (proto == ast.proto_fn) {wrd(s.s, "fn");}
else {wrd(s.s, "iter");}
alt (id) {
case (option.some[str](?id)) {space(s.s); wrd(s.s, id);}
case (_) {}
}
popen_h(s);
fn print_arg(ps s, &ast.ty_arg input) {
if (middle.ty.mode_is_alias(input.mode)) {wrd(s.s, "&");}
print_type(s, input.ty);
}
auto f = print_arg;
commasep[ast.ty_arg](s, inputs, f);
pclose(s);
maybe_print_comment(s, output.span.lo);
if (output.node != ast.ty_nil) {
space(s.s);
hbox(s);
wrd1(s, "->");
print_type(s, output);
end(s.s);
}
}
fn next_comment(ps s) -> option.t[lexer.cmnt] {
alt (s.comments) {
case (option.some[vec[lexer.cmnt]](?cmnts)) {
if (s.cur_cmnt < _vec.len[lexer.cmnt](cmnts)) {
ret option.some[lexer.cmnt](cmnts.(s.cur_cmnt));
} else {ret option.none[lexer.cmnt];}
}
case (_) {ret option.none[lexer.cmnt];}
}
}
fn maybe_print_comment(ps s, uint pos) {
while (true) {
alt (next_comment(s)) {
case (option.some[lexer.cmnt](?cmnt)) {
if (cmnt.pos < pos) {
print_comment(s, cmnt.val);
if (cmnt.space_after) {line(s.s);}
s.cur_cmnt += 1u;
} else { break; }
}
case (_) {break;}
}
}
}
fn maybe_print_line_comment(ps s, common.span span) -> bool {
alt (next_comment(s)) {
case (option.some[lexer.cmnt](?cmnt)) {
if (span.hi + 4u >= cmnt.pos) {
wrd(s.s, " ");
print_comment(s, cmnt.val);
s.cur_cmnt += 1u;
ret true;
}
}
case (_) {}
}
ret false;
}
fn print_remaining_comments(ps s) {
while (true) {
alt (next_comment(s)) {
case (option.some[lexer.cmnt](?cmnt)) {
print_comment(s, cmnt.val);
if (cmnt.space_after) {line(s.s);}
s.cur_cmnt += 1u;
}
case (_) {break;}
}
}
}
fn print_comment(ps s, lexer.cmnt_ cmnt) {
alt (cmnt) {
case (lexer.cmnt_line(?val)) {
wrd(s.s, "// " + val);
pp.hardbreak(s.s);
}
case (lexer.cmnt_block(?lines)) {
pp.abox(s.s);
wrd(s.s, "/* ");
pp.abox(s.s);
auto first = true;
for (str ln in lines) {
if (first) {first = false;}
else {pp.hardbreak(s.s);}
wrd(s.s, ln);
}
end(s.s);
wrd(s.s, "*/");
end(s.s);
line(s.s);
}
}
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
|
//pub mod protocol_parser;
//pub mod protocol;
//pub mod errors;
//pub use protocol::{OwnerType, TypeData, Step, Protocol};
//pub use protocol_parser::{Parser};
|
use super::prelude::*;
#[get("/posts")]
pub fn index(db: DbConnection) -> content::Html<String> {
use crate::schema::posts::dsl::*;
let psts = posts.load::<Post>(&db as &PgConnection).expect("Should load posts");
content::Html (
(html! {
(header(Some("Posts")));
(navigation(Some("/posts")));
div.container {
h1 { "Posts" }
(PreEscaped(psts.iter()
.map( post_entry ).collect::<String>()));
};
(footer());
}).into_string()
)
}
fn post_entry(post: &Post) -> String {
(html! {
div.panel.panel-default {
div.panel-heading { (post.title) }
div.panel-body { (post.body) }
div.panel-footer { "Published: " strong { (post.published) } }
}
}).into_string()
}
#[get("/posts/new")]
pub fn new() -> content::Html<String> {
content::Html((html! {
(header(Some("New Post")));
(navigation(Some("/posts/new")));
div.container {
h1 { "Create a new Post!" }
form action="/posts/create" method="post" {
label.control-label for="title" { "Post Title" };
input.form-control type="text" name="title" placeholder="Post Title" {};
label.control-label for="body" { "Post Content" };
textarea.form-control name="body" placeholder="Post Content" {};
input.control-label type="checkbox" name="published" {};
label.control-label for="published" { "Publish post" };
br;
input.btn.btn-primary type="submit" value="Create Post!" { };
}
}
}).into_string())
}
#[post("/posts/create", data = "<post_data>")]
pub fn create(db: DbConnection, post_data: Form<PostData>) -> Redirect {
use crate::schema::posts;
let new_post = NewPost::from(post_data);
diesel::insert_into(posts::table)
.values(&new_post)
.execute(&db as &PgConnection)
.expect("Error saving new post");
Redirect::to("/posts")
}
|
use crate::projection::Projection;
use numpy::{IntoPyArray, PyArray1, PyArray2};
use pyo3::prelude::{pyfunction, pymodule, Py, PyModule, PyResult, Python};
use pyo3::wrap_pyfunction;
use ndarray::{Ix1, Ix2, Array};
#[pyfunction]
fn project_vec(py: Python<'_>, x: &PyArray1<f64>) -> Py<PyArray1<f64>> {
Projection::<Ix1, f64>::project(&x.as_array())
.into_pyarray(py)
.to_owned()
}
#[pyfunction]
fn project_vecs(py: Python<'_>, xs: &PyArray2<f64>) -> Py<PyArray2<f64>> {
Projection::<Ix2, &Array<f64, Ix1>>::project(&xs.as_array())
.into_pyarray(py)
.to_owned()
}
#[pyfunction]
fn inv_project_vec(
py: Python<'_>,
x: &PyArray1<f64>,
depth: f64
) -> Py<PyArray1<f64>> {
Projection::inv_project(&x.as_array(), depth)
.into_pyarray(py)
.to_owned()
}
#[pyfunction]
fn inv_project_vecs(
py: Python<'_>,
xs: &PyArray2<f64>,
depths: &PyArray1<f64>,
) -> Py<PyArray2<f64>> {
Projection::inv_project(&xs.as_array(), &depths.as_array())
.into_pyarray(py)
.to_owned()
}
#[pymodule(projection)]
fn projection_module(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(project_vec))?;
m.add_wrapped(wrap_pyfunction!(project_vecs))?;
m.add_wrapped(wrap_pyfunction!(inv_project_vec))?;
m.add_wrapped(wrap_pyfunction!(inv_project_vecs))?;
Ok(())
}
|
use crate::prelude::*;
use crate::config;
use crate::models;
use sqlx::postgres::PgPoolOptions;
#[derive(Clone)]
pub struct Repo {
pool: sqlx::Pool<sqlx::Postgres>,
}
impl Repo {
pub async fn new(conf: &config::Settings) -> Result<Repo> {
let pool = PgPoolOptions::new()
.max_connections(4)
.connect(&conf.database_url)
.await?;
let repo = Repo { pool };
repo.migrate().await.context("Failed to migrate db")?;
Ok(repo)
}
async fn migrate(&self) -> Result<()> {
log::info!("Trying to migrate db");
let mut delay = std::time::Duration::from_millis(100);
loop {
let res = sqlx::migrate!("src/migrations")
.run(&self.pool)
.await;
match res {
Ok(_) => {
log::info!("Successfully applied migrations");
break;
},
Err(e) => {
delay *= 2;
log::error!("Failed to apply migrations: {:?}, sleeping {} seconds", e, delay.as_secs_f32());
}
}
tokio::time::delay_for(delay).await;
}
Ok(())
}
pub async fn list_statuses(&self) -> Result<Vec<models::NodeStatus>> {
let res: Vec<models::NodeStatus> = sqlx::query_as("SELECT * FROM statuses")
.fetch_all(&self.pool)
.await?;
Ok(res)
}
pub async fn update_status(&self, status: models::NodeStatus) -> Result<()> {
sqlx::query("INSERT INTO statuses(ip, status, timestamp) VALUES ($1, $2, $3) ON CONFLICT (ip) DO UPDATE SET timestamp = $3")
.bind(status.ip)
.bind(status.status)
.bind(status.timestamp)
.execute(&self.pool)
.await?;
Ok(())
}
}
|
//xfail-stage1
//xfail-stage2
//xfail-stage3
use std;
fn main() {
obj inner() {
fn a() -> int { ret 2; }
fn m() -> uint { ret 3u; }
fn z() -> uint { ret self.m(); }
}
let my_inner = inner();
let my_outer =
obj () {
fn b() -> uint { ret 5u; }
fn n() -> str { ret "world!"; }
with
my_inner
};
log_err my_inner.z();
assert (my_inner.z() == 3u);
log_err my_outer.z();
assert (my_outer.z() == 3u);
}
/*
Here, when we make the self-call to self.m() in inner, we're going
back through the outer "self". That outer "self" has 5 methods in
its vtable: a, b, m, n, z. But the method z has already been
compiled, and at the time it was compiled, it expected "self" to
only have three methods in its vtable: a, m, and z. So, the method
z thinks that "self.m()" means "look up method #1 (indexing from 0)
in my vtable and call it". That means that it'll call method #1 on
the larger vtable that it thinks is "self", and method #1 at that
point is b.
So, when we call my_inner.z(), we get 3, which is what we'd
expect. When we call my_outer.z(), we should also get 3, because
at no point is z being overridden.
To fix this bug, we need to make the vtable slots on the inner
object match whatever the object being passed in at runtime has.
My first instinct was to change the vtable to match the runtime
object, but vtables are already baked into RO memory. So, instead,
we're going to tweak the object being passed in at runtime to match
the vtable that inner already has. That is, it needs to only have
a, m, and z slots in its vtable, and each one of those slots will
forward to the *outer* object's a, m, and z slots, respectively.
From there they will either head right back to inner, or they'll be
overridden.
Adding support for this is issue #702.
*/
|
use crate::record::cell::Cell;
#[derive(Debug, PartialOrd, PartialEq, Clone)]
pub enum Record {
Header,
Info(u32, u32),
CellContent(Cell),
CellFormat,
Format,
Options,
Substitution,
ExtLink,
NameDefinitions,
WindowDefinitions,
ChartExtLink,
EOF,
}
impl Record {
pub fn from(record_type: Result<RecordType, String>, fields: &Vec<String>) -> Result<Record, String>{
// println!("{:?}",record_type);
match record_type{
Ok(RecordType::EOF) => {
Ok(Record::EOF)
},
Ok(RecordType::Header) => {
Ok(Record::Header)
},
Ok(RecordType::Info) => {
let mut columns = 0u32;
let mut rows = 0u32;
for field in fields.iter(){
let field_id = &field[0..1];
let field_content = &field[1..];
match field_id{
"Y" => rows = field_content.parse::<u32>().unwrap(),
"X" => columns = field_content.parse::<u32>().unwrap(),
_ => ()
}
}
Ok(Record::Info(rows,columns))
},
Ok(RecordType::CellContent) => {
Ok(Record::CellContent(Cell::parse(fields, None)))
},
Ok(RecordType::Format) => Ok(Record::Format),
Ok(RecordType::ChartExtLink) => Ok(Record::ChartExtLink),
Ok(RecordType::CellFormat) => Ok(Record::CellFormat),
Ok(RecordType::Options) => Ok(Record::Options),
Ok(RecordType::Substitution) => Ok(Record::Substitution),
Ok(RecordType::ExtLink) => Ok(Record::ExtLink),
Ok(RecordType::NameDefinitions) => Ok(Record::NameDefinitions),
Ok(RecordType::WindowDefinitions) => Ok(Record::WindowDefinitions),
Err(msg) => Err(msg),
}
}
}
#[derive(Debug, PartialOrd, PartialEq, Clone)]
pub enum RecordType {
Header,
Info,
CellContent,
CellFormat,
Format,
Options,
Substitution,
ExtLink,
NameDefinitions,
WindowDefinitions,
ChartExtLink,
EOF,
}
impl RecordType {
pub fn is_eof(&self) -> bool{
*self == RecordType::EOF
}
pub fn from_id(id: &str) -> Result<Self, String>{
match id {
"ID" => Ok(RecordType::Header),
"B" => Ok(RecordType::Info),
"C" => Ok(RecordType::CellContent),
"P" => Ok(RecordType::CellFormat),
"F" => Ok(RecordType::Format),
"O" => Ok(RecordType::Options),
"NU" => Ok(RecordType::Substitution),
"NE" => Ok(RecordType::ExtLink),
"NN" => Ok(RecordType::NameDefinitions),
"W" => Ok(RecordType::WindowDefinitions),
"NL" => Ok(RecordType::ChartExtLink),
"E" => Ok(RecordType::EOF),
_ => Err(format!("Unknown record {}", id))
}
}
} |
use crate::fd::OwnedFd;
use crate::{backend, io, path};
pub use backend::fs::types::MemfdFlags;
/// `memfd_create(path, flags)`
///
/// # References
/// - [Linux]
/// - [glibc]
/// - [FreeBSD]
///
/// [Linux]: https://man7.org/linux/man-pages/man2/memfd_create.2.html
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Memory_002dmapped-I_002fO.html#index-memfd_005fcreate
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?memfd_create
#[inline]
pub fn memfd_create<P: path::Arg>(path: P, flags: MemfdFlags) -> io::Result<OwnedFd> {
path.into_with_c_str(|path| backend::fs::syscalls::memfd_create(path, flags))
}
|
fn parse_config(args: &[String]) -> (&str, &str) {
let query = &args[1];
let filename = &args[2];
(query, filename)
} |
enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32)
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
struct Point {
x: i32,
y: i32,
}
struct Point3d {
x: i32,
y: i32,
z: i32
}
/// mix and match: `if let` with `if` and `else if`
fn if_let_examples() {
let favorite_color: Option<&str> = None;
let is_tuesday = false;
let age: Result<u8, _> = "34".parse();
if let Some(color) = favorite_color {
println!("Using your favorite color, {}, as the background", color);
} else if is_tuesday {
println!("Tuesday is green day!");
} else if let Ok(age) = age {
if age > 30 {
println!("Using purple as the background color");
} else {
println!("Using orange as the background color");
}
} else {
println!("Using blue as the background color");
}
}
/// while let loop using pattern matching
fn while_let_examples() {
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
println!("{}", top);
}
}
fn multiple_patterns() {
let x = 1;
match x {
1 | 2 | 5 | 8 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
}
fn range_patterns() {
let x = 5;
match x {
1 ... 5 => println!("one through five"),
_ => println!("something else"),
}
}
fn char_range_patterns() {
let x = 'c';
match x {
'a' ... 'j' => println!("early ASCII letter"),
'k' ... 'z' => println!("late ASCII letter"),
_ => println!("something else"),
}
}
fn matching_structs() {
let p = Point { x: 0, y: 7 };
match p {
Point { x, y: 0 } => println!("On the x axis at {}", x),
Point { x: 0, y } => println!("On the y axis at {}", y),
Point { x, y } => println!("On neither axis: ({}, {})", x, y),
}
}
fn nested_structs_and_enums() {
let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));
match msg {
Message::ChangeColor(Color::Rgb(r, g, b)) => {
println!(
"Change the color to red {}, green {}, and blue {}",
r,
g,
b
)
},
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!(
"Change the color to hue {}, saturation {}, and value {}",
h,
s,
v
)
}
_ => ()
}
}
fn match_guard_examples() {
let num = Some(4);
let y = 10;
match num {
Some(x) if x == 4 && y <= 11 => println!("x is {} and y is{}", x,y),
Some(x) if x < 5 => println!("less than five: {}", x),
Some(x) => println!("{}", x),
None => (),
}
}
// The at operator (@) lets us create a variable that holds a value at the same time we’re
// testing that value to see whether it matches a pattern
fn bindings_example() {
enum Message {
Hello { id: i32 },
}
let msg = Message::Hello { id: 5 };
match msg {
Message::Hello { id: id_variable @ 3...7 } => {
println!("Found an id in range: {}", id_variable)
},
Message::Hello { id: 10...12 } => {
println!("Found an id in another range")
},
Message::Hello { id } => {
println!("Found some other id: {}", id)
},
}
}
/// matching on parts of slice, The .. is called a "rest pattern," because it matches the rest of the slice
fn subslice_patterns() {
let words = ["zHello","World","!","Run","Forrest"];
match &words {
["Hello", "World", "!", ..] => println!("Hello World!"),
["Foo", "Bar", ..] => println!("Baz"),
rest => println!("{:?}", rest),
}
}
fn subslice_patterns2() {
let words = ["hello","all","z"];
match &words {
// Ignore everything but the last element, which must be "!".
[.., "!"] => println!("!!!"),
// `start` is a slice of everything except the last element, which must be "z".
[start @ .., "z"] => println!("starts with: {:?}", start),
// `end` is a slice of everything but the first element, which must be "a".
["a", end @ ..] => println!("ends with: {:?}", end),
rest => println!("{:?}", rest),
}
}
/// This macro accepts an expression and a pattern, and returns true if the pattern matches the expression
fn matches_macro() {
// Using the `matches!` macro:
//matches!(self.partial_cmp(other), Some(Less));
// You can also use features like | patterns and if guards:
let foo = 'f';
assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
let bar = Some(4);
assert!(matches!(bar, Some(x) if x > 2));
}
fn main() {
subslice_patterns();
subslice_patterns2();
// if_let_examples();
// while_let_examples();
// char_range_patterns();
// matching_structs();
// bindings_example();
// We can use patterns to destructure structs, enums, tuples, and references
// destructuring structs
let p = Point { x: 0, y: 7 };
//let Point { x: a, y: b } = p;
let Point { x, y } = p;
assert_eq!(0, x);
assert_eq!(7, y);
// complex destructuring
let ((feet, inches), Point {x, y}) = ((3, 10), Point { x: 3, y: -10 });
// ignoring parts of a value with ..
let origin = Point3d {x:0, y:0, z:0};
match origin {
Point3d {x, ..} => println!("x is {}", x)
}
// ignoring parts of a tuple with ..
let numbers = (2,4,8,12,32);
match numbers {
(first, .., last) => println!("first:{} last:{}", first, last)
// using .. must be ambiguous, the following pattern will not compile
// (.., second, ..)
}
// to match vectors, need to use experimental rust with #![feature(slice_patterns)]
// let v1 = vec![1,3,5,7,9];
// match &v1[..] {
// [first, ..] => println!("first of v1:{}", first)
// }
} |
pub(crate) use _sysconfigdata::make_module;
#[pymodule]
pub(crate) mod _sysconfigdata {
use crate::{builtins::PyDictRef, convert::ToPyObject, stdlib::sys::MULTIARCH, VirtualMachine};
#[pyattr]
fn build_time_vars(vm: &VirtualMachine) -> PyDictRef {
let vars = vm.ctx.new_dict();
macro_rules! sysvars {
($($key:literal => $value:expr),*$(,)?) => {{
$(vars.set_item($key, $value.to_pyobject(vm), vm).unwrap();)*
}};
}
sysvars! {
// fake shared module extension
"EXT_SUFFIX" => format!(".rustpython-{MULTIARCH}"),
"MULTIARCH" => MULTIARCH,
// enough for tests to stop expecting urandom() to fail after restricting file resources
"HAVE_GETRANDOM" => 1,
}
include!(concat!(env!("OUT_DIR"), "/env_vars.rs"));
vars
}
}
|
mod num;
mod util;
use std::env;
use std::path::PathBuf;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
fn main() {
let v: Vec<String> = env::args().collect();
let args: Vec<&str> = v.iter().map(AsRef::as_ref).collect();
let (i, o, f, d, v) = util::parse_input(args);
if f == None {
println!("{}", util::convert(i, o, v, d));
}
else {
let mut path = PathBuf::new();
path.push(env::current_dir().unwrap().as_path());
path.push(f.unwrap());
for line in BufReader::new(File::open(path).unwrap()).lines() {
line.unwrap().as_bytes().iter().for_each(|b| print!("{}",o.format_as(b)));
println!();
}
}
}
//-----------------------------------------------------------------------------------------------------------------//
//--------------------------Tests----------------------------------------------------------------------------------//
//-----------------------------------------------------------------------------------------------------------------//
#[cfg(test)]
mod full_send {
use super::*;
#[test]
fn test1() {
}
}
|
use crossterm::input::{InputEvent, KeyEvent, MouseButton, MouseEvent};
/// a valid user event
#[derive(Debug, Clone)]
pub enum Event {
Key(KeyEvent),
Click(u16, u16),
DoubleClick(u16, u16),
Wheel(i32),
}
impl Event {
pub fn from_crossterm_event(crossterm_event: Option<InputEvent>) -> Option<Event> {
match crossterm_event {
Some(InputEvent::Keyboard(key)) => Some(Event::Key(key)),
Some(InputEvent::Mouse(MouseEvent::Release(x, y))) => Some(Event::Click(x, y)),
Some(InputEvent::Mouse(MouseEvent::Press(MouseButton::WheelUp, _, _))) => {
Some(Event::Wheel(-1))
}
Some(InputEvent::Mouse(MouseEvent::Press(MouseButton::WheelDown, _, _))) => {
Some(Event::Wheel(1))
}
_ => None,
}
}
}
|
use algebra::UniformRand;
use rand::Rng;
use std::{fmt::Debug, hash::Hash};
use algebra::bytes::ToBytes;
pub mod blake2s;
pub mod injective_map;
pub mod pedersen;
use crate::Error;
pub trait CommitmentScheme {
type Output: ToBytes + Clone + Default + Eq + Hash + Debug;
type Parameters: Clone;
type Randomness: Clone + ToBytes + Default + Eq + UniformRand + Debug;
fn setup<R: Rng>(r: &mut R) -> Result<Self::Parameters, Error>;
fn commit(
parameters: &Self::Parameters,
input: &[u8],
r: &Self::Randomness,
) -> Result<Self::Output, Error>;
}
|
use jni::JNIEnv;
use jni::objects::JClass;
use jni::sys::jstring;
pub extern "system" fn Java_com_github_xxx_yyy_MainActivity_init() {
// TODO
}
pub extern "system" fn Java_com_github_xxx_yyy_MainActivity_stringFromJNI(env: JNIEnv,
_class: JClass)
-> jstring {
let hello = env.new_string("Hello from Rust")
.expect("Couldn't create java string!");
hello.into_inner()
} |
use reset_router::{Response, Router};
use std::{
env,
net::{IpAddr, Ipv4Addr, SocketAddr},
};
mod handlers;
use handlers::{auth, devices, exchange};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Get the port number to listen on.
let port = env::var("PORT")
.unwrap_or_else(|_| "3000".to_string())
.parse()
.expect("PORT must be a number");
let router = Router::build()
.add(http::Method::POST, r"^/access_code/([^/]+)$", auth)
.add(http::Method::POST, r"^/exchange", exchange)
.add(http::Method::GET, r"^/devices", devices)
.add_not_found(|_| async {
Ok::<_, Response>(
http::Response::builder()
.status(404)
.body("404".into())
.unwrap(),
)
})
.finish()?;
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port);
let server = hyper::Server::bind(&addr).serve(router);
server.await?;
Ok(())
}
|
//! Mock example
//!
//! Mocking an actor and setting it on the `SystemRegistry`. This can be
//! done so you can test an actor that depends on a `SystemService` in isolation.
#[cfg(test)]
use actix::actors::mocker::Mocker;
use actix::prelude::*;
#[cfg(test)]
use actix::SystemRegistry;
#[derive(Default)]
struct MyActor {}
impl Actor for MyActor {
type Context = Context<Self>;
}
impl Handler<Question> for MyActor {
type Result = ResponseFuture<usize>;
fn handle(&mut self, _msg: Question, _ctx: &mut Context<Self>) -> Self::Result {
let act_addr = AnswerActor::from_registry();
let request = act_addr.send(Question {});
Box::pin(async move { request.await.unwrap() })
}
}
#[derive(Default)]
struct AnsActor {}
#[derive(Message)]
#[rtype(result = "usize")]
struct Question {}
#[cfg(not(test))]
type AnswerActor = AnsActor;
#[cfg(test)]
type AnswerActor = Mocker<AnsActor>;
impl Actor for AnsActor {
type Context = Context<Self>;
}
impl Supervised for AnsActor {}
impl SystemService for AnsActor {}
impl Handler<Question> for AnsActor {
type Result = usize;
fn handle(&mut self, _: Question, _: &mut Context<Self>) -> Self::Result {
42
}
}
#[actix::main]
async fn main() {
let addr = MyActor::default().start();
let result = addr.send(Question {}).await.unwrap_or_default();
assert_eq!(42, result);
}
#[cfg(test)]
mod tests {
use super::*;
#[actix::test]
async fn mocked_behavior() {
let mocker_addr = AnswerActor::mock(Box::new(move |_msg, _ctx| {
let result: usize = 2;
Box::new(Some(result))
}))
.start();
SystemRegistry::set(mocker_addr);
let result = MyActor::default().start().send(Question {}).await.unwrap();
assert_eq!(result, 2);
}
}
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from ../gir-files
// DO NOT EDIT
mod address;
pub use self::address::{Address, NONE_ADDRESS};
mod auth;
pub use self::auth::{Auth, NONE_AUTH};
mod auth_basic;
pub use self::auth_basic::{AuthBasic};
mod auth_digest;
pub use self::auth_digest::{AuthDigest};
mod auth_domain;
pub use self::auth_domain::{AuthDomain, NONE_AUTH_DOMAIN};
mod auth_domain_basic;
pub use self::auth_domain_basic::{AuthDomainBasic, NONE_AUTH_DOMAIN_BASIC};
mod auth_domain_digest;
pub use self::auth_domain_digest::{AuthDomainDigest, NONE_AUTH_DOMAIN_DIGEST};
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
mod auth_manager;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::auth_manager::{AuthManager, NONE_AUTH_MANAGER};
mod auth_ntlm;
pub use self::auth_ntlm::{AuthNTLM};
#[cfg(any(feature = "v2_54", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_54")))]
mod auth_negotiate;
#[cfg(any(feature = "v2_54", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_54")))]
pub use self::auth_negotiate::{AuthNegotiate};
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
mod cache;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use self::cache::{Cache, NONE_CACHE};
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
mod content_decoder;
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
pub use self::content_decoder::{ContentDecoder, NONE_CONTENT_DECODER};
#[cfg(any(feature = "v2_28", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_28")))]
mod content_sniffer;
#[cfg(any(feature = "v2_28", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_28")))]
pub use self::content_sniffer::{ContentSniffer, NONE_CONTENT_SNIFFER};
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
mod cookie_jar;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use self::cookie_jar::{CookieJar, NONE_COOKIE_JAR};
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
mod cookie_jar_db;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::cookie_jar_db::{CookieJarDB, NONE_COOKIE_JAR_DB};
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
mod cookie_jar_text;
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
pub use self::cookie_jar_text::{CookieJarText, NONE_COOKIE_JAR_TEXT};
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
mod hsts_enforcer;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::hsts_enforcer::{HSTSEnforcer, NONE_HSTS_ENFORCER};
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
mod hsts_enforcer_db;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::hsts_enforcer_db::{HSTSEnforcerDB, NONE_HSTS_ENFORCER_DB};
mod logger;
pub use self::logger::{Logger, NONE_LOGGER};
mod message;
pub use self::message::{Message, NONE_MESSAGE};
#[cfg(any(feature = "v2_40", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_40")))]
mod multipart_input_stream;
#[cfg(any(feature = "v2_40", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_40")))]
pub use self::multipart_input_stream::{MultipartInputStream, NONE_MULTIPART_INPUT_STREAM};
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
mod proxy_resolver_default;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use self::proxy_resolver_default::{ProxyResolverDefault, NONE_PROXY_RESOLVER_DEFAULT};
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
mod request;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::request::{Request, NONE_REQUEST};
#[cfg(any(feature = "v0", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v0")))]
mod request_data;
#[cfg(any(feature = "v0", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v0")))]
pub use self::request_data::{RequestData, NONE_REQUEST_DATA};
#[cfg(any(feature = "v0", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v0")))]
mod request_file;
#[cfg(any(feature = "v0", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v0")))]
pub use self::request_file::{RequestFile, NONE_REQUEST_FILE};
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
mod request_http;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::request_http::{RequestHTTP, NONE_REQUEST_HTTP};
mod requester;
pub use self::requester::{Requester, NONE_REQUESTER};
mod server;
pub use self::server::{Server, NONE_SERVER};
mod session;
pub use self::session::{Session, NONE_SESSION};
#[cfg_attr(feature = "v2_42", deprecated = "Since 2.42")]
mod session_async;
#[cfg_attr(feature = "v2_42", deprecated = "Since 2.42")]
pub use self::session_async::{SessionAsync, NONE_SESSION_ASYNC};
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
mod session_feature;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use self::session_feature::{SessionFeature, NONE_SESSION_FEATURE};
#[cfg_attr(feature = "v2_42", deprecated = "Since 2.42")]
mod session_sync;
#[cfg_attr(feature = "v2_42", deprecated = "Since 2.42")]
pub use self::session_sync::{SessionSync, NONE_SESSION_SYNC};
mod socket;
pub use self::socket::{Socket, NONE_SOCKET};
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
mod websocket_connection;
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
pub use self::websocket_connection::{WebsocketConnection, NONE_WEBSOCKET_CONNECTION};
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
mod websocket_extension;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::websocket_extension::{WebsocketExtension, NONE_WEBSOCKET_EXTENSION};
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
mod websocket_extension_deflate;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::websocket_extension_deflate::{WebsocketExtensionDeflate, NONE_WEBSOCKET_EXTENSION_DEFLATE};
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
mod websocket_extension_manager;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::websocket_extension_manager::{WebsocketExtensionManager, NONE_WEBSOCKET_EXTENSION_MANAGER};
mod buffer;
pub use self::buffer::Buffer;
mod client_context;
pub use self::client_context::ClientContext;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
mod cookie;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use self::cookie::Cookie;
mod date;
pub use self::date::Date;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
mod hsts_policy;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::hsts_policy::HSTSPolicy;
mod message_body;
pub use self::message_body::MessageBody;
mod message_headers;
pub use self::message_headers::MessageHeaders;
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
mod multipart;
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
pub use self::multipart::Multipart;
mod uri;
pub use self::uri::URI;
mod enums;
pub use self::enums::AddressFamily;
pub use self::enums::CacheResponse;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use self::enums::CacheType;
pub use self::enums::ConnectionState;
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
pub use self::enums::CookieJarAcceptPolicy;
pub use self::enums::DateFormat;
pub use self::enums::Encoding;
pub use self::enums::HTTPVersion;
pub use self::enums::KnownStatusCode;
pub use self::enums::LoggerLogLevel;
pub use self::enums::MemoryUse;
pub use self::enums::MessageHeadersType;
pub use self::enums::MessagePriority;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::enums::RequestError;
pub use self::enums::RequesterError;
#[cfg(any(feature = "v2_70", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_70")))]
pub use self::enums::SameSitePolicy;
pub use self::enums::SocketIOStatus;
pub use self::enums::Status;
#[cfg(any(feature = "v2_40", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_40")))]
pub use self::enums::TLDError;
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
pub use self::enums::WebsocketCloseCode;
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
pub use self::enums::WebsocketConnectionType;
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
pub use self::enums::WebsocketDataType;
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
pub use self::enums::WebsocketError;
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
pub use self::enums::WebsocketState;
pub use self::enums::XMLRPCError;
pub use self::enums::XMLRPCFault;
mod flags;
pub use self::flags::Cacheability;
pub use self::flags::Expectation;
pub use self::flags::MessageFlags;
#[cfg(any(feature = "v2_48", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))]
pub use self::flags::ServerListenOptions;
pub mod functions;
mod constants;
pub use self::constants::ADDRESS_FAMILY;
pub use self::constants::ADDRESS_NAME;
pub use self::constants::ADDRESS_PHYSICAL;
pub use self::constants::ADDRESS_PORT;
pub use self::constants::ADDRESS_PROTOCOL;
pub use self::constants::ADDRESS_SOCKADDR;
pub use self::constants::AUTH_DOMAIN_ADD_PATH;
pub use self::constants::AUTH_DOMAIN_BASIC_AUTH_CALLBACK;
pub use self::constants::AUTH_DOMAIN_BASIC_AUTH_DATA;
pub use self::constants::AUTH_DOMAIN_DIGEST_AUTH_CALLBACK;
pub use self::constants::AUTH_DOMAIN_DIGEST_AUTH_DATA;
pub use self::constants::AUTH_DOMAIN_FILTER;
pub use self::constants::AUTH_DOMAIN_FILTER_DATA;
pub use self::constants::AUTH_DOMAIN_GENERIC_AUTH_CALLBACK;
pub use self::constants::AUTH_DOMAIN_GENERIC_AUTH_DATA;
pub use self::constants::AUTH_DOMAIN_PROXY;
pub use self::constants::AUTH_DOMAIN_REALM;
pub use self::constants::AUTH_DOMAIN_REMOVE_PATH;
pub use self::constants::AUTH_HOST;
pub use self::constants::AUTH_IS_AUTHENTICATED;
pub use self::constants::AUTH_IS_FOR_PROXY;
pub use self::constants::AUTH_REALM;
pub use self::constants::AUTH_SCHEME_NAME;
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
pub use self::constants::COOKIE_JAR_ACCEPT_POLICY;
pub use self::constants::COOKIE_JAR_DB_FILENAME;
pub use self::constants::COOKIE_JAR_READ_ONLY;
pub use self::constants::COOKIE_JAR_TEXT_FILENAME;
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
pub use self::constants::FORM_MIME_TYPE_MULTIPART;
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
pub use self::constants::FORM_MIME_TYPE_URLENCODED;
pub use self::constants::HSTS_ENFORCER_DB_FILENAME;
#[cfg(any(feature = "v2_56", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_56")))]
pub use self::constants::LOGGER_LEVEL;
#[cfg(any(feature = "v2_56", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_56")))]
pub use self::constants::LOGGER_MAX_BODY_SIZE;
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
pub use self::constants::MESSAGE_FIRST_PARTY;
pub use self::constants::MESSAGE_FLAGS;
pub use self::constants::MESSAGE_HTTP_VERSION;
pub use self::constants::MESSAGE_IS_TOP_LEVEL_NAVIGATION;
pub use self::constants::MESSAGE_METHOD;
#[cfg(any(feature = "v2_44", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))]
pub use self::constants::MESSAGE_PRIORITY;
pub use self::constants::MESSAGE_REASON_PHRASE;
pub use self::constants::MESSAGE_REQUEST_BODY;
#[cfg(any(feature = "v2_46", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_46")))]
pub use self::constants::MESSAGE_REQUEST_BODY_DATA;
pub use self::constants::MESSAGE_REQUEST_HEADERS;
pub use self::constants::MESSAGE_RESPONSE_BODY;
#[cfg(any(feature = "v2_46", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_46")))]
pub use self::constants::MESSAGE_RESPONSE_BODY_DATA;
pub use self::constants::MESSAGE_RESPONSE_HEADERS;
pub use self::constants::MESSAGE_SERVER_SIDE;
pub use self::constants::MESSAGE_SITE_FOR_COOKIES;
pub use self::constants::MESSAGE_STATUS_CODE;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use self::constants::MESSAGE_TLS_CERTIFICATE;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use self::constants::MESSAGE_TLS_ERRORS;
pub use self::constants::MESSAGE_URI;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::constants::REQUEST_SESSION;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::constants::REQUEST_URI;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::constants::SERVER_ADD_WEBSOCKET_EXTENSION;
pub use self::constants::SERVER_ASYNC_CONTEXT;
#[cfg(any(feature = "v2_44", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))]
pub use self::constants::SERVER_HTTPS_ALIASES;
#[cfg(any(feature = "v2_44", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))]
pub use self::constants::SERVER_HTTP_ALIASES;
pub use self::constants::SERVER_INTERFACE;
pub use self::constants::SERVER_PORT;
pub use self::constants::SERVER_RAW_PATHS;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use self::constants::SERVER_REMOVE_WEBSOCKET_EXTENSION;
pub use self::constants::SERVER_SERVER_HEADER;
pub use self::constants::SERVER_SSL_CERT_FILE;
pub use self::constants::SERVER_SSL_KEY_FILE;
#[cfg(any(feature = "v2_38", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))]
pub use self::constants::SERVER_TLS_CERTIFICATE;
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
pub use self::constants::SESSION_ACCEPT_LANGUAGE;
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
pub use self::constants::SESSION_ACCEPT_LANGUAGE_AUTO;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use self::constants::SESSION_ADD_FEATURE;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use self::constants::SESSION_ADD_FEATURE_BY_TYPE;
pub use self::constants::SESSION_ASYNC_CONTEXT;
#[cfg(any(feature = "v2_38", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))]
pub use self::constants::SESSION_HTTPS_ALIASES;
#[cfg(any(feature = "v2_38", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))]
pub use self::constants::SESSION_HTTP_ALIASES;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use self::constants::SESSION_IDLE_TIMEOUT;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use self::constants::SESSION_LOCAL_ADDRESS;
pub use self::constants::SESSION_MAX_CONNS;
pub use self::constants::SESSION_MAX_CONNS_PER_HOST;
pub use self::constants::SESSION_PROXY_RESOLVER;
pub use self::constants::SESSION_PROXY_URI;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use self::constants::SESSION_REMOVE_FEATURE_BY_TYPE;
pub use self::constants::SESSION_SSL_CA_FILE;
#[cfg(any(feature = "v2_30", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))]
pub use self::constants::SESSION_SSL_STRICT;
#[cfg(any(feature = "v2_38", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))]
pub use self::constants::SESSION_SSL_USE_SYSTEM_CA_FILE;
pub use self::constants::SESSION_TIMEOUT;
#[cfg(any(feature = "v2_38", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))]
pub use self::constants::SESSION_TLS_DATABASE;
#[cfg(any(feature = "v2_48", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))]
pub use self::constants::SESSION_TLS_INTERACTION;
pub use self::constants::SESSION_USER_AGENT;
pub use self::constants::SESSION_USE_NTLM;
#[cfg(any(feature = "v2_38", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))]
pub use self::constants::SESSION_USE_THREAD_CONTEXT;
pub use self::constants::SOCKET_ASYNC_CONTEXT;
pub use self::constants::SOCKET_FLAG_NONBLOCKING;
pub use self::constants::SOCKET_IS_SERVER;
pub use self::constants::SOCKET_LOCAL_ADDRESS;
pub use self::constants::SOCKET_REMOTE_ADDRESS;
pub use self::constants::SOCKET_SSL_CREDENTIALS;
pub use self::constants::SOCKET_SSL_FALLBACK;
pub use self::constants::SOCKET_SSL_STRICT;
pub use self::constants::SOCKET_TIMEOUT;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use self::constants::SOCKET_TLS_CERTIFICATE;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use self::constants::SOCKET_TLS_ERRORS;
pub use self::constants::SOCKET_TRUSTED_CERTIFICATE;
#[cfg(any(feature = "v2_38", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))]
pub use self::constants::SOCKET_USE_THREAD_CONTEXT;
#[doc(hidden)]
pub mod traits {
pub use super::address::AddressExt;
pub use super::auth::AuthExt;
pub use super::auth_domain::AuthDomainExt;
pub use super::auth_domain_basic::AuthDomainBasicExt;
pub use super::auth_domain_digest::AuthDomainDigestExt;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use super::auth_manager::AuthManagerExt;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use super::cache::CacheExt;
#[cfg(any(feature = "v2_28", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_28")))]
pub use super::content_sniffer::ContentSnifferExt;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use super::cookie_jar::CookieJarExt;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use super::cookie_jar_db::CookieJarDBExt;
#[cfg(any(feature = "v2_26", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))]
pub use super::cookie_jar_text::CookieJarTextExt;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use super::hsts_enforcer::HSTSEnforcerExt;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use super::hsts_enforcer_db::HSTSEnforcerDBExt;
pub use super::logger::LoggerExt;
pub use super::message::MessageExt;
#[cfg(any(feature = "v2_40", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_40")))]
pub use super::multipart_input_stream::MultipartInputStreamExt;
#[cfg(any(feature = "v2_34", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))]
pub use super::proxy_resolver_default::ProxyResolverDefaultExt;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use super::request::RequestExt;
#[cfg(any(feature = "v0", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v0")))]
pub use super::request_file::RequestFileExt;
#[cfg(any(feature = "v2_42", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))]
pub use super::request_http::RequestHTTPExt;
pub use super::requester::RequesterExt;
pub use super::server::ServerExt;
pub use super::session::SessionExt;
#[cfg(any(feature = "v2_24", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))]
pub use super::session_feature::SessionFeatureExt;
pub use super::socket::SocketExt;
#[cfg(any(feature = "v2_50", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
pub use super::websocket_connection::WebsocketConnectionExt;
#[cfg(any(feature = "v2_68", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))]
pub use super::websocket_extension::WebsocketExtensionExt;
}
|
mod profiler;
use self::profiler::Profiler;
use std::fs::File;
use std::ops::DerefMut;
use std::rc::Rc;
use std::str::FromStr;
use bigint::{Address, Gas, H256, M256, U256};
use hexutil::read_hex;
use evm::{
AccountCommitment, Context, HeaderParams, RequireError, SeqContextVM, SeqTransactionVM, TransactionAction,
VMStatus, ValidTransaction, VM,
};
use evm_network_classic::{
MainnetByzantiumPatch, MainnetConstantinoplePatch, MainnetEIP150Patch, MainnetEIP160Patch, MainnetFrontierPatch,
MainnetHomesteadPatch,
};
use gethrpc::{GethRPCClient, NormalGethRPCClient, RPCBlock};
fn from_rpc_block(block: &RPCBlock) -> HeaderParams {
HeaderParams {
beneficiary: Address::from_str(&block.miner).unwrap(),
timestamp: U256::from_str(&block.timestamp).unwrap().as_u64(),
number: U256::from_str(block.number.as_ref().unwrap()).unwrap(),
difficulty: U256::from_str(&block.difficulty).unwrap(),
gas_limit: Gas::from_str(&block.gas_limit).unwrap(),
}
}
fn handle_step_without_rpc(vm: &mut VM) {
match vm.step() {
Ok(()) => {}
Err(RequireError::Account(address)) => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
Err(RequireError::AccountStorage(address, index)) => {
vm.commit_account(AccountCommitment::Storage {
address,
index,
value: M256::zero(),
})
.unwrap();
}
Err(RequireError::AccountCode(address)) => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
Err(RequireError::Blockhash(number)) => {
vm.commit_blockhash(number, H256::default()).unwrap();
}
}
}
fn profile_fire_without_rpc(vm: &mut VM) {
loop {
match vm.status() {
VMStatus::Running => {
let opcode = vm.peek_opcode();
flame::span_of(format!("{:?}", opcode), || handle_step_without_rpc(vm));
}
VMStatus::ExitedOk | VMStatus::ExitedErr(_) | VMStatus::ExitedNotSupported(_) => return,
}
}
}
fn handle_fire_without_rpc(vm: &mut VM) {
loop {
match vm.fire() {
Ok(()) => break,
Err(RequireError::Account(address)) => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
Err(RequireError::AccountStorage(address, index)) => {
vm.commit_account(AccountCommitment::Storage {
address,
index,
value: M256::zero(),
})
.unwrap();
}
Err(RequireError::AccountCode(address)) => {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
}
Err(RequireError::Blockhash(number)) => {
vm.commit_blockhash(number, H256::default()).unwrap();
}
}
}
}
fn handle_fire_with_rpc<T: GethRPCClient>(client: &mut T, vm: &mut VM, block_number: &str) {
loop {
match vm.fire() {
Ok(()) => break,
Err(RequireError::Account(address)) => {
let nonce =
U256::from_str(&client.get_transaction_count(&format!("0x{:x}", address), &block_number)).unwrap();
let balance = U256::from_str(&client.get_balance(&format!("0x{:x}", address), &block_number)).unwrap();
let code = read_hex(&client.get_code(&format!("0x{:x}", address), &block_number)).unwrap();
if !client.account_exist(
&format!("0x{:x}", address),
U256::from_str(&block_number).unwrap().as_usize(),
) {
vm.commit_account(AccountCommitment::Nonexist(address)).unwrap();
} else {
vm.commit_account(AccountCommitment::Full {
nonce,
address,
balance,
code: Rc::new(code),
})
.unwrap();
}
}
Err(RequireError::AccountStorage(address, index)) => {
let value = M256::from_str(&client.get_storage_at(
&format!("0x{:x}", address),
&format!("0x{:x}", index),
&block_number,
))
.unwrap();
vm.commit_account(AccountCommitment::Storage { address, index, value })
.unwrap();
}
Err(RequireError::AccountCode(address)) => {
let code = read_hex(&client.get_code(&format!("0x{:x}", address), &block_number)).unwrap();
vm.commit_account(AccountCommitment::Code {
address,
code: Rc::new(code),
})
.unwrap();
}
Err(RequireError::Blockhash(number)) => {
let hash = H256::from_str(
&client
.get_block_by_number(&format!("0x{:x}", number))
.expect("block not found")
.hash
.expect("block has no hash"),
)
.unwrap();
vm.commit_blockhash(number, hash).unwrap();
}
}
}
}
use clap::clap_app;
fn main() {
let matches = clap_app!(evm =>
(version: "0.1")
(author: "Ethereum Classic Contributors")
(about: "CLI tool for SputnikVM.")
(@arg CREATE: --create "Execute a CreateContract transaction instead of message call.")
(@arg PROFILE: --profile "Whether to output a profiling result for the execution.")
(@arg PROFILE_DUMP: --profile_dump +takes_value "Dump profiler result as HTML.")
(@arg CODE: --code +takes_value +required "Code to be executed.")
(@arg RPC: --rpc +takes_value "Indicate this EVM should be run on an actual blockchain.")
(@arg DATA: --data +takes_value "Data associated with this transaction.")
(@arg BLOCK: --block +takes_value "Block number associated.")
(@arg PATCH: --patch +takes_value +required "Patch to be used.")
(@arg GAS_LIMIT: --gas_limit +takes_value "Gas limit.")
(@arg GAS_PRICE: --gas_price +takes_value "Gas price.")
(@arg CALLER: --caller +takes_value "Caller of the transaction.")
(@arg ADDRESS: --address +takes_value "Address of the transaction.")
(@arg VALUE: --value +takes_value "Value of the transaction.")
)
.get_matches();
let code = read_hex(matches.value_of("CODE").unwrap()).unwrap();
let data = read_hex(matches.value_of("DATA").unwrap_or("")).unwrap();
let caller = Address::from_str(
matches
.value_of("CALLER")
.unwrap_or("0x0000000000000000000000000000000000000000"),
)
.unwrap();
let address = Address::from_str(
matches
.value_of("ADDRESS")
.unwrap_or("0x0000000000000000000000000000000000000000"),
)
.unwrap();
let value = U256::from_str(matches.value_of("VALUE").unwrap_or("0x0")).unwrap();
let gas_limit = Gas::from_str(matches.value_of("GAS_LIMIT").unwrap_or("0x2540be400")).unwrap();
let gas_price = Gas::from_str(matches.value_of("GAS_PRICE").unwrap_or("0x0")).unwrap();
let is_create = matches.is_present("CREATE");
let block_number = matches.value_of("BLOCK").unwrap_or("0x0");
let block = if matches.is_present("RPC") {
let mut client = NormalGethRPCClient::new(matches.value_of("RPC").unwrap());
from_rpc_block(&client.get_block_by_number(block_number).expect("block not found"))
} else {
HeaderParams {
beneficiary: Address::default(),
timestamp: 0,
number: U256::from_str(block_number).unwrap(),
difficulty: U256::zero(),
gas_limit: Gas::zero(),
}
};
let mut client = if matches.is_present("RPC") {
Some(NormalGethRPCClient::new(matches.value_of("RPC").unwrap()))
} else {
None
};
// Bind pathes so they would outlive VM execution
let frontier = MainnetFrontierPatch::default();
let homestead = MainnetHomesteadPatch::default();
let eip150 = MainnetEIP150Patch::default();
let eip160 = MainnetEIP160Patch::default();
let byzantium = MainnetByzantiumPatch::default();
let constantinople = MainnetConstantinoplePatch::default();
let mut vm: Box<VM> = if matches.is_present("CODE") {
let context = Context {
address,
caller,
callee: address,
gas_limit,
gas_price,
value,
code: Rc::new(code),
data: Rc::new(data),
origin: caller,
apprent_value: value,
is_system: false,
is_static: false,
};
match matches.value_of("PATCH") {
Some("frontier") => Box::new(SeqContextVM::new(&frontier, context, block)),
Some("homestead") => Box::new(SeqContextVM::new(&homestead, context, block)),
Some("eip150") => Box::new(SeqContextVM::new(&eip150, context, block)),
Some("eip160") => Box::new(SeqContextVM::new(&eip160, context, block)),
Some("byzantium") => Box::new(SeqContextVM::new(&byzantium, context, block)),
Some("constantinople") => Box::new(SeqContextVM::new(&constantinople, context, block)),
_ => panic!("Unsupported patch."),
}
} else {
let transaction = ValidTransaction {
caller: Some(caller),
value,
gas_limit,
gas_price,
input: Rc::new(data),
nonce: match client {
Some(ref mut client) => {
U256::from_str(&client.get_transaction_count(&format!("0x{:x}", caller), &block_number)).unwrap()
}
None => U256::zero(),
},
action: if is_create {
TransactionAction::Create
} else {
TransactionAction::Call(address)
},
};
match matches.value_of("PATCH") {
Some("frontier") => Box::new(SeqTransactionVM::new(&frontier, transaction, block)),
Some("homestead") => Box::new(SeqTransactionVM::new(&homestead, transaction, block)),
Some("eip150") => Box::new(SeqTransactionVM::new(&eip150, transaction, block)),
Some("eip160") => Box::new(SeqTransactionVM::new(&eip160, transaction, block)),
Some("byzantium") => Box::new(SeqTransactionVM::new(&byzantium, transaction, block)),
_ => panic!("Unsupported patch."),
}
};
match client {
Some(ref mut client) => {
handle_fire_with_rpc(client, vm.deref_mut(), block_number);
}
None => {
if matches.is_present("PROFILE") {
profile_fire_without_rpc(vm.deref_mut());
if matches.is_present("PROFILE_DUMP") {
flame::dump_html(&mut File::create(matches.value_of("PROFILE_DUMP").unwrap()).unwrap()).unwrap();
}
let mut profiler = Profiler::default();
for span in flame::spans() {
profiler.record(&span);
}
profiler.print_stats();
} else {
handle_fire_without_rpc(vm.deref_mut());
}
}
}
println!("VM returned: {:?}", vm.status());
println!("VM out: {:?}", vm.out());
for account in vm.accounts() {
println!("{:?}", account);
}
}
|
//! Audio Filters example.
//!
//! This example showcases basic audio functionality using [`Ndsp`].
#![feature(allocator_api)]
use std::f32::consts::PI;
use ctru::linear::LinearAllocator;
use ctru::prelude::*;
use ctru::services::ndsp::{
wave::{Status, Wave},
AudioFormat, AudioMix, InterpolationType, Ndsp, OutputMode,
};
// Configuration for the NDSP process and channels.
const SAMPLE_RATE: usize = 22050;
const SAMPLES_PER_BUF: usize = SAMPLE_RATE / 10; // 2205
const BYTES_PER_SAMPLE: usize = AudioFormat::PCM16Stereo.size();
const AUDIO_WAVE_LENGTH: usize = SAMPLES_PER_BUF * BYTES_PER_SAMPLE;
// Note frequencies.
const NOTEFREQ: [f32; 7] = [220., 440., 880., 1760., 3520., 7040., 14080.];
fn fill_buffer(audio_data: &mut [u8], frequency: f32) {
// The audio format is Stereo PCM16.
// As such, a sample is made up of 2 "Mono" samples (2 * i16), one for each channel (left and right).
let formatted_data = bytemuck::cast_slice_mut::<_, [i16; 2]>(audio_data);
for (i, chunk) in formatted_data.iter_mut().enumerate() {
// This is a simple sine wave, with a frequency of `frequency` Hz, and an amplitude 30% of maximum.
let sample: f32 = (frequency * (i as f32 / SAMPLE_RATE as f32) * 2. * PI).sin();
let amplitude = 0.3 * i16::MAX as f32;
let result = (sample * amplitude) as i16;
// Stereo samples are interleaved: left and right channels.
*chunk = [result, result];
}
}
fn main() {
ctru::use_panic_handler();
let gfx = Gfx::new().expect("Couldn't obtain GFX controller");
let mut hid = Hid::new().expect("Couldn't obtain HID controller");
let apt = Apt::new().expect("Couldn't obtain APT controller");
let _console = Console::new(gfx.top_screen.borrow_mut());
let mut note: usize = 4;
// Filter names to display.
let filter_names = [
"None",
"Low-Pass",
"High-Pass",
"Band-Pass",
"Notch",
"Peaking",
];
let mut filter: i32 = 0;
// We set up two wave buffers and alternate between the two,
// effectively streaming an infinitely long sine wave.
// We create a buffer on the LINEAR memory that will hold our audio data.
// It's necessary for the buffer to live on the LINEAR memory sector since it needs to be accessed by the DSP processor.
let mut audio_data1 = Box::new_in([0u8; AUDIO_WAVE_LENGTH], LinearAllocator);
// Fill the buffer with the first set of data. This simply writes a sine wave into the buffer.
fill_buffer(audio_data1.as_mut_slice(), NOTEFREQ[4]);
// Clone the original buffer to obtain an equal buffer on the LINEAR memory used for double buffering.
let audio_data2 = audio_data1.clone();
// Setup two wave info objects with the correct configuration and ownership of the audio data.
let mut wave_info1 = Wave::new(audio_data1, AudioFormat::PCM16Stereo, false);
let mut wave_info2 = Wave::new(audio_data2, AudioFormat::PCM16Stereo, false);
// Setup the NDSP service and its configuration.
let mut ndsp = Ndsp::new().expect("Couldn't obtain NDSP controller");
ndsp.set_output_mode(OutputMode::Stereo);
// Channel configuration. We use channel zero but any channel would do just fine.
let mut channel_zero = ndsp.channel(0).unwrap();
channel_zero.set_interpolation(InterpolationType::Linear);
channel_zero.set_sample_rate(SAMPLE_RATE as f32);
channel_zero.set_format(AudioFormat::PCM16Stereo);
// Output at 100% on the first pair of left and right channels.
let mix = AudioMix::default();
channel_zero.set_mix(&mix);
// First set of queueing for the two buffers. The second one will only play after the first one has ended.
channel_zero.queue_wave(&mut wave_info1).unwrap();
channel_zero.queue_wave(&mut wave_info2).unwrap();
println!("\x1b[1;1HPress up/down to change tone frequency");
println!("\x1b[2;1HPress left/right to change filter");
println!("\x1b[4;1Hnote = {} Hz ", NOTEFREQ[note]);
println!(
"\x1b[5;1Hfilter = {} ",
filter_names[filter as usize]
);
println!("\x1b[29;16HPress Start to exit");
let mut altern = true; // true is wave_info1, false is wave_info2
while apt.main_loop() {
hid.scan_input();
let keys_down = hid.keys_down();
if keys_down.contains(KeyPad::START) {
break;
}
// Note frequency controller using the buttons.
if keys_down.intersects(KeyPad::DOWN) {
note = note.saturating_sub(1);
} else if keys_down.intersects(KeyPad::UP) {
note = std::cmp::min(note + 1, NOTEFREQ.len() - 1);
}
// Filter controller using the buttons.
let mut update_params = false;
if keys_down.intersects(KeyPad::LEFT) {
filter -= 1;
filter = filter.rem_euclid(filter_names.len() as _);
update_params = true;
} else if keys_down.intersects(KeyPad::RIGHT) {
filter += 1;
filter = filter.rem_euclid(filter_names.len() as _);
update_params = true;
}
println!("\x1b[4;1Hnote = {} Hz ", NOTEFREQ[note]);
println!(
"\x1b[5;1Hfilter = {} ",
filter_names[filter as usize]
);
if update_params {
match filter {
1 => channel_zero.iir_biquad_set_params_low_pass_filter(1760., 0.707),
2 => channel_zero.iir_biquad_set_params_high_pass_filter(1760., 0.707),
3 => channel_zero.iir_biquad_set_params_band_pass_filter(1760., 0.707),
4 => channel_zero.iir_biquad_set_params_notch_filter(1760., 0.707),
5 => channel_zero.iir_biquad_set_params_peaking_equalizer(1760., 0.707, 3.),
_ => channel_zero.iir_biquad_set_enabled(false),
}
}
// Double buffer alternation depending on the one used.
let current: &mut Wave = if altern {
&mut wave_info1
} else {
&mut wave_info2
};
// If the current buffer has finished playing, we can refill it with new data and re-queue it.
let status = current.status();
if let Status::Done = status {
fill_buffer(current.get_buffer_mut().unwrap(), NOTEFREQ[note]);
channel_zero.queue_wave(current).unwrap();
altern = !altern;
}
gfx.wait_for_vblank();
}
}
|
use crate::position::Position;
use crate::value::{Object, Value};
#[derive(Clone, Debug)]
pub enum Error {
Runtime(Value),
Lexer(LexerError),
Parser(ParserError),
}
impl Error {
pub fn redeclaration_of_variable(pos: Position) -> Value {
Error::runtime(pos, "redeclaration of variable".into())
}
pub fn undeclared_variable(pos: Position) -> Value {
Error::runtime(pos, "undeclared variable".into())
}
pub fn not_a_function(pos: Position) -> Value {
Error::runtime(pos, "not a function".into())
}
pub fn bad_break(pos: Position) -> Value {
Error::runtime(pos, "`break` used outside a loop".into())
}
pub fn bad_continue(pos: Position) -> Value {
Error::runtime(pos, "`continue` used outside a loop".into())
}
pub fn bad_return(pos: Position) -> Value {
Error::runtime(pos, "`return` used outside a function".into())
}
pub fn bad_iter(pos: Position) -> Value {
Error::runtime(pos, "expected an iterator object with a `next` function".into())
}
pub fn bad_iter_next(pos: Position) -> Value {
Error::runtime(pos, "expected iterator's `next` to return an object".into())
}
pub fn invalid_operands(pos: Position) -> Value {
Error::runtime(pos, "invalid operands for operation".into())
}
pub fn invalid_operand(pos: Position) -> Value {
Error::runtime(pos, "invalid operand for operation".into())
}
pub fn invalid_assign_lhs(pos: Position) -> Value {
Error::runtime(pos, "invalid assignment left-hand side".into())
}
pub fn non_string_object_key(pos: Position) -> Value {
Error::runtime(pos, "object key must be a string".into())
}
pub fn non_numeric_array_index(pos: Position) -> Value {
Error::runtime(pos, "array index must be a number".into())
}
pub fn negative_array_index(pos: Position) -> Value {
Error::runtime(pos, "array index cannot be negative".into())
}
pub fn invalid_indexee(pos: Position) -> Value {
Error::runtime(pos, "only arrays and objects can be indexed".into())
}
pub fn invalid_dot(pos: Position) -> Value {
Error::runtime(pos, "dot operator can only be used on objects".into())
}
pub fn runtime(pos: Position, message: String) -> Value {
let object = Object::new();
object.set("message", Value::string(message));
object.set("line", Value::Number(pos.line as f64));
object.set("column", Value::Number(pos.column as f64));
Value::Object(object)
}
}
#[derive(Clone, Debug)]
pub struct LexerError {
pub kind: LexerErrorKind,
pub position: Position,
}
#[derive(Clone, Debug)]
pub enum LexerErrorKind {
UnexpectedChar,
MalformedNumber,
MalformedEscapeSequence,
MalformedChar,
}
#[derive(Clone, Debug)]
pub struct ParserError {
pub kind: ParserErrorKind,
pub position: Position,
}
#[derive(Clone, Debug)]
pub enum ParserErrorKind {
ExpectedLCurly,
ExpectedRParen,
ExpectedSemicolon,
UnexpectedToken,
UnexpectedEOF,
}
impl From<Value> for Error {
fn from(value: Value) -> Error {
Error::Runtime(value)
}
}
|
use amethyst::{
core::transform::Transform,
input::{get_key, is_close_requested, is_key_down, VirtualKeyCode},
prelude::*,
renderer::{Camera},
window::ScreenDimensions,
assets::{AssetStorage, Loader, Handle},
renderer::{ImageFormat, SpriteSheet, SpriteSheetFormat, Texture},
};
use crate::components;
use crate::resources::SpawnCounter;
use log::info;
/// A dummy game state that shows 3 sprites.
pub struct LifeSim;
impl SimpleState for LifeSim {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let world = data.world;
// Get the screen dimensions so we can initialize the camera and
// place our sprites correctly later. We'll clone this since we'll
// pass the world mutably to the following functions.
let dimensions = (*world.read_resource::<ScreenDimensions>()).clone();
let sprite_sheet_handle = load_sprite_sheet(world);
let spawn_counter = SpawnCounter {
cells: 100,
food: 10,
};
world.insert(spawn_counter);
world.register::<components::CreatureTag>();
components::initialise_creatures(world, sprite_sheet_handle);
// Place the camera
init_camera(world, &dimensions);
}
/// The following events are handled:
/// - The game state is quit when either the close button is clicked or when the escape key is pressed.
/// - Any other keypress is simply logged to the console.
fn handle_event(
&mut self,
mut _data: StateData<'_, GameData<'_, '_>>,
event: StateEvent,
) -> SimpleTrans {
if let StateEvent::Window(event) = &event {
// Check if the window should be closed
if is_close_requested(&event) || is_key_down(&event, VirtualKeyCode::Escape) {
return Trans::Quit;
}
// Listen to any key events
if let Some(event) = get_key(&event) {
info!("handling key event: {:?}", event);
}
}
// Keep going
Trans::None
}
}
/// Creates a camera entity in the `world`.
///
/// The `dimensions` are used to center the camera in the middle
/// of the screen, as well as make it cover the entire screen.
fn init_camera(world: &mut World, dimensions: &ScreenDimensions) {
let mut transform = Transform::default();
transform.set_translation_xyz(dimensions.width() * 0.5, dimensions.height() * 0.5, 1.);
world
.create_entity()
.with(Camera::standard_2d(dimensions.width(), dimensions.height()))
.with(transform)
.build();
}
pub fn load_sprite_sheet(world: &mut World) -> Handle<SpriteSheet> {
let texture_handle = {
let loader = world.read_resource::<Loader>();
let texture_storage = world.read_resource::<AssetStorage<Texture>>();
loader.load(
"sprites/sheet.png",
ImageFormat::default(),
(),
&texture_storage,
)
};
let loader = world.read_resource::<Loader>();
let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>();
loader.load(
"sprites/sheet.ron", // Here we load the associated ron file
SpriteSheetFormat(texture_handle),
(),
&sprite_sheet_store,
)
}
|
extern crate chrono;
#[macro_use]
extern crate diesel;
extern crate dotenv;
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
extern crate reqwest;
extern crate serde_json;
mod db;
mod discord;
mod error;
mod schema;
mod z3r;
use std::{collections::HashMap, env};
use dotenv::dotenv;
use serenity::{framework::standard::StandardFramework, model::id::ChannelId, prelude::*};
use crate::error::BotError;
use discord::{ActiveGames, ChannelsContainer, DBConnectionContainer, Handler, GENERAL_GROUP};
fn main() -> Result<(), BotError> {
dotenv().ok();
env_logger::init();
let token = env::var("DISCORD_TOKEN").expect("Expected a token in the environment.");
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let mut client = Client::new(&token, Handler).expect("Error creating client");
{
let mut data = client.data.write();
let db_pool = db::establish_pool(&database_url)?;
let active_game: bool = db::check_for_active_game(&db_pool)?;
let channels: HashMap<&'static str, ChannelId> = discord::get_channels_from_env()?;
data.insert::<DBConnectionContainer>(db_pool);
data.insert::<ActiveGames>(active_game);
data.insert::<ChannelsContainer>(channels);
}
client.with_framework(
StandardFramework::new()
.configure(|c| c.prefix("!"))
.group(&GENERAL_GROUP),
);
if let Err(why) = client.start() {
error!("Client error: {:?}", why);
}
Ok(())
}
|
use std::collections::VecDeque;
use proconio::{input, marker::Usize1};
fn solve(n: usize, _: usize, c: Vec<u8>, edges: Vec<(usize, usize)>) {
let mut g = vec![vec![]; n];
for (u, v) in edges {
g[u].push(v);
g[v].push(u);
}
const INF: u32 = std::u32::MAX;
let mut dp = vec![vec![INF; n]; n];
dp[0][n - 1] = 0;
let mut que = VecDeque::new();
que.push_back((0, n - 1));
while let Some((x, y)) = que.pop_front() {
for &nx in &g[x] {
for &ny in &g[y] {
if c[nx] != c[ny] && dp[nx][ny] == INF {
dp[nx][ny] = dp[x][y] + 1;
que.push_back((nx, ny));
}
}
}
}
if dp[n - 1][0] == INF {
println!("-1");
} else {
println!("{}", dp[n - 1][0]);
}
}
fn main() {
input! {
t: usize,
};
for _ in 0..t {
input! {
n: usize,
m: usize,
c: [u8; n],
edges: [(Usize1, Usize1); m],
};
solve(n, m, c, edges);
}
}
|
use console::style;
use emoji;
use error::Error;
use std::process::Command;
use PBAR;
pub fn rustup_add_wasm_target() -> Result<(), Error> {
let step = format!(
"{} {}Adding WASM target...",
style("[1/7]").bold().dim(),
emoji::TARGET
);
let pb = PBAR.message(&step);
let output = Command::new("rustup")
.arg("target")
.arg("add")
.arg("wasm32-unknown-unknown")
.output()?;
pb.finish();
if !output.status.success() {
let s = String::from_utf8_lossy(&output.stderr);
Error::cli("Adding the wasm32-unknown-unknown target failed", s)
} else {
Ok(())
}
}
pub fn cargo_build_wasm(path: &str) -> Result<(), Error> {
let step = format!(
"{} {}Compiling to WASM...",
style("[2/7]").bold().dim(),
emoji::CYCLONE
);
let pb = PBAR.message(&step);
let output = Command::new("cargo")
.current_dir(path)
.arg("build")
.arg("--release")
.arg("--target")
.arg("wasm32-unknown-unknown")
.output()?;
pb.finish();
if !output.status.success() {
let s = String::from_utf8_lossy(&output.stderr);
Error::cli("Compilation of your program failed", s)
} else {
Ok(())
}
}
|
use opentelemetry::metrics::MetricsError;
use opentelemetry_prometheus::PrometheusExporter;
use prometheus::{proto::MetricFamily, Encoder as _, TextEncoder};
use std::time::Duration;
pub(crate) struct PrometheusPushOnDropExporter {
exporter: PrometheusExporter,
endpoint: String,
}
impl Drop for PrometheusPushOnDropExporter {
fn drop(&mut self) {
let metric_families = self.exporter.registry().gather();
if let Err(err) = push_metrics(metric_families, &self.endpoint) {
opentelemetry::global::handle_error(err);
}
}
}
pub(crate) fn new_prometheus_push_on_drop_exporter(
) -> Result<PrometheusPushOnDropExporter, MetricsError> {
let host = std::env::var("OTEL_EXPORTER_PROMETHEUS_HOST").unwrap_or_else(|_| "0.0.0.0".into());
let port = std::env::var("OTEL_EXPORTER_PROMETHEUS_PORT").unwrap_or_else(|_| "9464".into());
let endpoint = format!("{}:{}", host, port);
let exporter = opentelemetry_prometheus::exporter()
.with_default_histogram_boundaries(vec![
1., // 1 sec
10., // 10 secs
30., // 30 secs
60., // 1 min
300., // 5 mins
600., // 10 mins
900., // 15 mins
1200., // 20 mins
1500., // 25 mins
1800., // 30 mins
2100., // 35 mins
2400., // 40 mins
2700., // 45 mins
])
.try_init()?;
Ok(PrometheusPushOnDropExporter { exporter, endpoint })
}
fn push_metrics(metric_families: Vec<MetricFamily>, endpoint: &str) -> Result<(), MetricsError> {
let mut buffer = vec![];
let encoder = TextEncoder::new();
encoder.encode(&metric_families, &mut buffer).unwrap();
let agent = ureq::AgentBuilder::new()
.timeout(Duration::from_secs(5))
.build();
let _response = agent
.post(&format!("http://{}/metrics/job/tracebuild", endpoint))
.set("content-type", encoder.format_type())
.send_bytes(&buffer)
.map_err(|err| {
MetricsError::Other(format!(
"Failed to send metrics to Prometheus push gateway: {}",
err
))
})?;
Ok(())
}
|
#[derive(Clone)]
pub struct Group<P: Peer> {
id: GroupID,
rate: f32,
peers: HashMap<P::PublicKey, PeerAddr>,
living_peers: Vec<P::PublicKey>,
waiting_peers: HashMap<P::PublicKey, Vec<(P::PublicKey, P::Signature)>>,
storage: Addr<DiskStorageActor>,
}
impl<P: 'static + Peer> Group<P> {
pub fn load(id: GroupID, pk: P::PublicKey, peer_addr: PeerAddr, rate: f32) -> Self {
let mut path = get_default_storage_path();
path.push("group");
path.push(format!("{}", id));
let db = DiskDatabase::new(Some(path.clone()));
let mut peers = if let Ok(group) = db.read_entity::<GroupStore<P>>(id.to_string()) {
group.1
} else {
HashMap::new()
};
drop(db);
peers.entry(pk).or_insert(peer_addr); // set self to peers
let storage = DiskStorageActor::run(Some(path));
Self {
id: id,
rate: rate,
peers: peers,
living_peers: Vec::new(),
waiting_peers: HashMap::new(),
storage: storage,
}
}
pub fn has_peer(&self, pk: &P::PublicKey) -> bool {
self.peers.contains_key(pk)
}
pub fn get_peer_addr(&self, pk: &P::PublicKey) -> Option<PeerAddr> {
self.peers.get(pk).cloned()
}
pub fn get_by_peer_addr(&self, peer_addr: &PeerAddr) -> Option<&P::PublicKey> {
self.peers
.iter()
.filter_map(|(pk, addr)| if addr == peer_addr { Some(pk) } else { None })
.next()
}
pub fn all_peer_keys(&self) -> Vec<P::PublicKey> {
self.peers.keys().map(|e| e).cloned().collect()
}
pub fn living_peers(&self) -> &Vec<P::PublicKey> {
&self.living_peers
}
pub fn heart_beat(&mut self, pk: &P::PublicKey) {
if self.has_peer(pk) {
if !self.living_peers.contains(pk) {
self.living_peers.push(pk.clone());
}
}
}
pub fn bootstrap(&mut self, peers: Vec<(P::PublicKey, PeerAddr)>) {
for pk in peers {
self.add_sync_peers(&pk.0, pk.1);
}
}
pub fn iter(&self) -> Iter<P::PublicKey, PeerAddr> {
self.peers.iter()
}
}
impl<P: 'static + Peer> GroupTrait<P> for Group<P> {
type JoinType = Certificate<P>;
fn id(&self) -> &GroupID {
&self.id
}
fn join(&mut self, data: Self::JoinType, peer_addr: PeerAddr) -> bool {
if self.has_peer(&data.pk) {
return true;
}
if Certificate::verify(&data) && self.has_peer(&data.ca) {
let pk = &data.pk;
self.waiting_peers
.entry(pk.clone())
.and_modify(|peers| peers.push((data.ca.clone(), data.pkc.clone())))
.or_insert(vec![(data.ca.clone(), data.pkc.clone())]);
if (self.waiting_peers.get(pk).unwrap().len() as f32 / self.peers.len() as f32)
>= self.rate
{
self.waiting_peers.remove(pk);
self.peers.insert(pk.clone(), peer_addr);
self.storage.do_send(EntityWrite(GroupStore::<P>(
self.id.clone(),
self.peers.clone(),
)));
}
true
} else {
false
}
}
fn leave(&mut self, peer_addr: &PeerAddr) -> bool {
let mut pks: Vec<&P::PublicKey> = self
.peers
.iter()
.filter_map(|(pk, addr)| if addr == peer_addr { Some(pk) } else { None })
.collect();
loop {
if let Some(pk) = pks.pop() {
self.living_peers.remove_item(pk);
} else {
break;
}
}
true
}
fn verify(&self, pk: &P::PublicKey) -> bool {
self.peers.contains_key(pk)
}
fn help_sync_peers(&self, _pk: &P::PublicKey) -> Vec<PeerAddr> {
self.living_peers
.iter()
.filter_map(|pk| {
if let Some(addr) = self.peers.get(pk) {
Some(addr.clone())
} else {
None
}
})
.collect()
}
fn add_sync_peers(&mut self, pk: &P::PublicKey, peer_addr: PeerAddr) {
self.peers.entry(pk.clone()).or_insert(peer_addr);
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct GroupStore<P: Peer>(GroupID, HashMap<P::PublicKey, PeerAddr>);
impl<P: Peer> Entity for GroupStore<P> {
type Key = String;
fn key(&self) -> Self::Key {
self.0.to_string()
}
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct Certificate<P: Peer> {
pub pk: P::PublicKey,
pub ca: P::PublicKey,
pub pkc: P::Signature,
}
/// use string to format is better for copy and move
#[derive(Serialize, Deserialize)]
struct CertificateString {
pk: String,
ca: String,
pkc: String,
}
impl<P: Peer> Certificate<P> {
pub fn new(pk: P::PublicKey, ca: P::PublicKey, pkc: P::Signature) -> Self {
Self { pk, ca, pkc }
}
pub fn certificate(ca_psk: &P::PrivateKey, ca: P::PublicKey, pk: P::PublicKey) -> Self {
let pkc = P::sign(ca_psk, &(bincode::serialize(&pk).unwrap()));
Self::new(pk, ca, pkc)
}
pub fn certificate_self(psk: &P::PrivateKey, pk: P::PublicKey) -> Self {
Self::certificate(psk, pk.clone(), pk)
}
pub fn verify(ca: &Self) -> bool {
let pk_vec = {
let v = bincode::serialize(&ca.pk);
if v.is_err() {
return false;
}
v.unwrap()
};
P::verify(&ca.ca, &pk_vec, &ca.pkc)
}
pub fn to_json_string(&self) -> String {
let ca_string = CertificateString {
pk: format!("{}", self.pk),
ca: format!("{}", self.ca),
pkc: format!("{}", self.pkc),
};
serde_json::to_string(&ca_string).unwrap()
}
pub fn to_jsonrpc(&self) -> RPCParams {
json! ({
"pk": format!("{}", self.pk),
"ca": format!("{}", self.ca),
"pkc": format!("{}", self.pkc),
})
}
pub fn from_json_string(s: String) -> Result<Self, ()> {
let join_type: Result<CertificateString, _> = serde_json::from_str(&s);
if join_type.is_err() {
return Err(());
}
let ca_str = join_type.unwrap();
Self::from_string(ca_str.pk, ca_str.ca, ca_str.pkc)
}
pub fn from_string(pk: String, ca: String, pkc: String) -> Result<Self, ()> {
Ok(Self::new(pk.into(), ca.into(), pkc.into()))
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(clippy::uninlined_format_args)]
#![deny(unused_crate_dependencies)]
mod converters;
mod hive_block_filter;
mod hive_blocks;
mod hive_catalog;
mod hive_database;
mod hive_file_splitter;
mod hive_meta_data_reader;
mod hive_parquet_block_reader;
mod hive_partition;
mod hive_partition_filler;
mod hive_partition_pruner;
mod hive_table;
mod hive_table_options;
mod hive_table_source;
mod utils;
pub use hive_block_filter::HiveBlockFilter;
pub use hive_blocks::HiveBlocks;
pub use hive_catalog::HiveCatalog;
pub use hive_file_splitter::HiveFileSplitter;
pub use hive_meta_data_reader::MetaDataReader;
pub use hive_parquet_block_reader::filter_hive_partition_from_partition_keys;
pub use hive_partition::HivePartInfo;
pub use hive_partition_filler::HivePartitionFiller;
pub use hive_table::HiveFileInfo;
pub use hive_table::HiveTable;
|
#[allow(unused_imports)]
use proconio::{marker::*, *};
#[allow(unused_imports)]
use std::{cmp::Ordering, convert::TryInto};
#[allow(unused_imports)]
use lib::*;
#[fastout]
fn main() {
input! {
n: i32,
s: Chars,
}
let mut t = 0;
let mut a = 0;
for c in &s {
match c {
'T' => { t += 1; },
'A' => { a += 1; },
_ => panic!(),
}
}
let ret = match t.cmp(&a) {
Ordering::Greater => String::from("T"),
Ordering::Less => String::from("A"),
Ordering::Equal => String::from(if s.last().unwrap().to_string() == String::from("T") { "A" } else { "T" }),
};
println!("{}", ret);
}
mod lib {
pub trait CumlativeSum {
// 累積和
fn cumlative_sum(&self) -> Self;
}
impl CumlativeSum for Vec<Vec<i32>> {
fn cumlative_sum(&self) -> Self {
let h = self.len() as usize;
let w = self.get(0).unwrap().len() as usize;
let mut s = vec![vec![0; w + 1]; h + 1];
// 横方向合計
for (r, xs) in self.iter().enumerate() {
let r = r as usize + 1;
for (c, x) in xs.iter().enumerate() {
let c = c as usize + 1;
s[r][c] = s[r][c - 1] + x;
}
}
// 縦方向合計
for c in 1..=w {
for r in 1..=h {
s[r][c] += s[r - 1][c];
}
}
s
}
}
}
|
use std::fmt;
use super::{ffi, PowerDevice, PowerIterator};
use crate::platform::traits::BatteryManager;
use crate::Result;
#[derive(Default)]
pub struct PowerManager;
impl BatteryManager for PowerManager {
type Iterator = PowerIterator;
fn new() -> Result<Self> {
Ok(PowerManager {})
}
fn refresh(&self, device: &mut PowerDevice) -> Result<()> {
let battery_tag = device.tag().clone();
let di = ffi::DeviceIterator::new()?;
let handle = di.prepare_handle()?;
let device_handle = ffi::DeviceHandle {
handle,
tag: battery_tag,
};
device.refresh(device_handle)?;
Ok(())
}
}
impl fmt::Debug for PowerManager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("WindowsManager").finish()
}
}
|
//! Code generation for prefix-types.
use abi_stable_shared::const_utils::low_bit_mask_u64;
use core_extensions::{matches, SelfOps};
use syn::{punctuated::Punctuated, Ident, TypeParamBound, Visibility, WherePredicate};
use quote::{quote_spanned, ToTokens, TokenStreamExt};
use proc_macro2::Span;
use as_derive_utils::{
datastructure::{DataStructure, Field, FieldIndex, FieldMap},
return_spanned_err,
to_token_fn::ToTokenFnMut,
};
use crate::*;
use crate::{literals_constructors::rstr_tokenizer, parse_utils::parse_str_as_ident};
use super::{
attribute_parsing::{StabilityKind, StableAbiOptions},
reflection::FieldAccessor,
CommonTokens,
};
/// Configuration for code generation related to prefix-types.
pub(crate) struct PrefixKind<'a> {
pub(crate) first_suffix_field: FirstSuffixField,
pub(crate) prefix_ref: &'a Ident,
pub(crate) prefix_fields_struct: &'a Ident,
pub(crate) replacing_prefix_ref_docs: &'a [syn::Expr],
pub(crate) prefix_bounds: Vec<WherePredicate>,
pub(crate) fields: FieldMap<AccessorOrMaybe<'a>>,
pub(crate) accessor_bounds: FieldMap<Vec<TypeParamBound>>,
pub(crate) cond_field_indices: Vec<usize>,
pub(crate) enable_field_if: Vec<&'a syn::Expr>,
pub(crate) unconditional_bit_mask: u64,
pub(crate) prefix_field_conditionality_mask: u64,
}
pub(crate) struct PrefixKindCtor<'a> {
pub(crate) arenas: &'a Arenas,
#[allow(dead_code)]
pub(crate) struct_name: &'a Ident,
pub(crate) first_suffix_field: FirstSuffixField,
pub(crate) prefix_ref: Option<&'a Ident>,
pub(crate) prefix_fields: Option<&'a Ident>,
pub(crate) replacing_prefix_ref_docs: &'a [syn::Expr],
pub(crate) prefix_bounds: Vec<WherePredicate>,
pub(crate) fields: FieldMap<AccessorOrMaybe<'a>>,
pub(crate) accessor_bounds: FieldMap<Vec<TypeParamBound>>,
}
impl<'a> PrefixKindCtor<'a> {
pub fn make(self) -> PrefixKind<'a> {
let ctor = self;
let mut cond_field_indices = Vec::<usize>::new();
let mut enable_field_if = Vec::<&syn::Expr>::new();
let mut unconditional_bit_mask = 0u64;
let mut conditional_bit_mask = 0u64;
for (index, field) in ctor.fields.iter() {
let field_i = index.pos;
match (|| field.to_maybe_accessor()?.accessible_if)() {
Some(cond) => {
cond_field_indices.push(field_i);
enable_field_if.push(cond);
conditional_bit_mask |= 1u64 << field_i;
}
None => {
unconditional_bit_mask |= 1u64 << field_i;
}
}
}
let prefix_field_conditionality_mask =
conditional_bit_mask & low_bit_mask_u64(ctor.first_suffix_field.field_pos as u32);
PrefixKind {
first_suffix_field: ctor.first_suffix_field,
prefix_ref: ctor.prefix_ref.unwrap_or_else(|| {
let ident = format!("{}_Ref", ctor.struct_name);
ctor.arenas.alloc(parse_str_as_ident(&ident))
}),
prefix_fields_struct: ctor.prefix_fields.unwrap_or_else(|| {
let ident = format!("{}_Prefix", ctor.struct_name);
ctor.arenas.alloc(parse_str_as_ident(&ident))
}),
replacing_prefix_ref_docs: ctor.replacing_prefix_ref_docs,
prefix_bounds: ctor.prefix_bounds,
fields: ctor.fields,
accessor_bounds: ctor.accessor_bounds,
cond_field_indices,
enable_field_if,
unconditional_bit_mask,
prefix_field_conditionality_mask,
}
}
}
/// Used while parsing the prefix-type-related attributes on fields.
#[derive(Copy, Default, Clone)]
pub(crate) struct PrefixKindField<'a> {
pub(crate) accessible_if: Option<&'a syn::Expr>,
pub(crate) on_missing: Option<OnMissingField<'a>>,
}
/// The different types of prefix-type accessors.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum AccessorOrMaybe<'a> {
/// Unconditionally returns the field.
Accessor,
/// Either optionally returns the field,or it does some action when it's missing.
Maybe(MaybeAccessor<'a>),
}
/// Describes a field accessor which is either optional or
/// does some action when the field is missing.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
pub struct MaybeAccessor<'a> {
/// If Some,it uses a bool constant to determine whether a field is accessible.
accessible_if: Option<&'a syn::Expr>,
/// What the accessor method does when the field is missing.
on_missing: OnMissingField<'a>,
}
#[derive(Copy, Clone, Default, PartialEq, Eq)]
pub(crate) struct FirstSuffixField {
pub(crate) field_pos: usize,
}
/// What happens in a Prefix-type field getter if the field does not exist.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) enum OnMissingField<'a> {
/// Returns an `Option<FieldType>`,where it returns None if the field is absent.
ReturnOption,
/// Panics with a default message.
Panic,
/// Evaluates `function()`,and returns the return value of the function.
With { function: &'a syn::Path },
/// Returns `some_expression`.
Value { value: &'a syn::Expr },
/// Returns Default::default
Default_,
}
impl<'a> Default for OnMissingField<'a> {
fn default() -> Self {
OnMissingField::ReturnOption
}
}
impl<'a> AccessorOrMaybe<'a> {
pub(crate) fn new(
field_i: FieldIndex,
first_suffix_field: FirstSuffixField,
pkf: PrefixKindField<'a>,
default_omf: OnMissingField<'a>,
) -> Self {
if field_i.pos < first_suffix_field.field_pos
&& pkf.accessible_if.is_none()
&& pkf.on_missing != Some(OnMissingField::ReturnOption)
{
AccessorOrMaybe::Accessor
} else {
AccessorOrMaybe::Maybe(MaybeAccessor {
accessible_if: pkf.accessible_if,
on_missing: pkf.on_missing.unwrap_or(default_omf),
})
}
}
#[allow(dead_code)]
pub(crate) fn is_conditional(&self) -> bool {
self.to_maybe_accessor()
.map_or(false, |x| x.accessible_if.is_some())
}
/// Converts this to a MaybeAccessor,returning None if it is not the `Maybe` variant.
pub(crate) fn to_maybe_accessor(self) -> Option<MaybeAccessor<'a>> {
match self {
AccessorOrMaybe::Maybe(x) => Some(x),
_ => None,
}
}
#[allow(dead_code)]
pub(crate) fn is_maybe_accessor(&self) -> bool {
matches!(self, AccessorOrMaybe::Maybe { .. })
}
}
impl<'a> PrefixKind<'a> {
/// Gets the accessibility for a field,used for (very basic) runtime reflection.
pub(crate) fn field_accessor(&self, field: &Field<'a>) -> FieldAccessor<'a> {
use self::OnMissingField as OMF;
match self.fields[field] {
AccessorOrMaybe::Accessor => FieldAccessor::Method { name: None },
AccessorOrMaybe::Maybe(MaybeAccessor { on_missing, .. }) => match on_missing {
OMF::ReturnOption => FieldAccessor::MethodOption,
OMF::Panic { .. } | OMF::With { .. } | OMF::Value { .. } | OMF::Default_ => {
FieldAccessor::Method { name: None }
}
},
}
}
}
////////////////////////////////////////////////////////////////////////////////
///// Code generation
////////////////////////////////////////////////////////////////////////////////
pub struct PrefixTypeTokens {
pub prefixref_types: TokenStream2,
pub prefixref_impls: TokenStream2,
}
/// Returns a value which for a prefix-type .
pub(crate) fn prefix_type_tokenizer<'a>(
mono_type_layout: &'a Ident,
ds: &'a DataStructure<'a>,
config: &'a StableAbiOptions<'a>,
_ctokens: &'a CommonTokens<'a>,
) -> Result<PrefixTypeTokens, syn::Error> {
if matches!(config.kind, StabilityKind::Prefix { .. }) {
if ds
.variants
.get(0)
.map_or(false, |struct_| struct_.fields.len() > 64)
{
return_spanned_err!(
ds.name,
"`#[sabi(kind(Prefix(..)))]` structs cannot have more than 64 fields."
);
}
if config.repr.is_packed.is_some() {
return_spanned_err!(
ds.name,
"`#[sabi(kind(Prefix(..)))]` structs cannot be `#[repr(C, packed)]`"
);
}
}
Ok({
fn default_prefixtype_tokens() -> PrefixTypeTokens {
PrefixTypeTokens {
prefixref_types: TokenStream2::new(),
prefixref_impls: TokenStream2::new(),
}
}
let struct_ = match ds.variants.get(0) {
Some(x) => x,
None => return Ok(default_prefixtype_tokens()),
};
let prefix = match &config.kind {
StabilityKind::Prefix(prefix) => prefix,
_ => return Ok(default_prefixtype_tokens()),
};
let first_suffix_field = prefix.first_suffix_field.field_pos;
let prefix_fields_struct = &prefix.prefix_fields_struct;
let doc_hidden_attr = config.doc_hidden_attr;
let deriving_name = ds.name;
let (ref impl_generics, ref ty_generics, ref where_clause) = ds.generics.split_for_impl();
let empty_preds = Punctuated::new();
let where_preds = where_clause
.as_ref()
.map_or(&empty_preds, |x| &x.predicates)
.into_iter();
let where_preds_a = where_preds.clone();
let where_preds_b = where_preds.clone();
let where_preds_c = where_preds.clone();
// let where_preds_d0=where_preds.clone();
// let where_preds_d1=where_preds.clone();
let where_preds_e = where_preds.clone();
let where_preds_f = where_preds.clone();
let where_preds_rl = where_preds.clone();
let where_preds_r2 = where_preds.clone();
let prefix_bounds = &prefix.prefix_bounds;
let stringified_deriving_name = deriving_name.to_string();
let stringified_generics = (&ty_generics).into_token_stream().to_string();
let stringified_generics_tokenizer = rstr_tokenizer(&stringified_generics);
let is_ds_pub = matches!(ds.vis, Visibility::Public { .. }) && doc_hidden_attr.is_none();
let has_replaced_docs = !prefix.replacing_prefix_ref_docs.is_empty();
let prefix_ref_docs = ToTokenFnMut::new(|ts| {
if !is_ds_pub {
return;
}
if has_replaced_docs {
let iter = prefix.replacing_prefix_ref_docs.iter();
ts.append_all(quote!(#(#[doc = #iter])*));
} else {
let single_docs = format!(
"\
This is the pointer to the prefix of \n\
[`{deriving_name}{generics}`](struct@{deriving_name}).\n\
\n\
**This is automatically generated documentation,\
by the StableAbi derive macro**.\n\
\n\
### Creating a compiletime-constant\n\
\n\
You can look at the docs in [`::abi_stable::docs::prefix_types`] \
to see how you\n\
can construct and use this and similar types.<br>\n\
More specifically in the \n\
[\"constructing a module\" example\n\
](::abi_stable::docs::prefix_types#module_construction) or the\n\
[\"Constructing a vtable\" example\n\
](::abi_stable::docs::prefix_types#vtable_construction)\n\
",
deriving_name = stringified_deriving_name,
generics = stringified_generics,
);
ts.append_all(quote!(#[doc = #single_docs]));
}
});
let prefix_fields_docs = if is_ds_pub {
format!(
"\
This is the prefix fields of
[`{deriving_name}{generics}`](struct@{deriving_name}),
accessible through [`{prefix_name}`](struct@{prefix_name}), with `.0.prefix()`.
**This is automatically generated documentation,by the StableAbi derive macro**.
",
prefix_name = prefix.prefix_ref,
deriving_name = stringified_deriving_name,
generics = stringified_generics,
)
} else {
String::new()
};
let prefix_ref = prefix.prefix_ref;
// Generating the `<prefix_ref>` struct
let generated_types = {
let vis = ds.vis;
let generics = ds.generics;
let alignemnt = if let Some(alignemnt) = config.repr.is_aligned {
let alignemnt = as_derive_utils::utils::uint_lit(alignemnt.into());
quote!(, align(#alignemnt))
} else {
quote!()
};
let prefix_field_iter = struct_.fields[..first_suffix_field].iter();
// This uses `field_<NUMBER>` for tuple fields
let prefix_field_vis = prefix_field_iter.clone().map(|f| {
ToTokenFnMut::new(move |ts| {
let vis = f.vis;
if AccessorOrMaybe::Accessor == prefix.fields[f] {
vis.to_tokens(ts);
}
})
});
let prefix_field = prefix_field_iter.clone().map(|f| f.pat_ident());
let prefix_field_ty = prefix_field_iter.clone().map(|f| f.ty);
let (_, ty_generics, where_clause) = generics.split_for_impl();
quote!(
#doc_hidden_attr
#prefix_ref_docs
#[repr(transparent)]
#vis struct #prefix_ref #generics (
#vis ::abi_stable::pmr::PrefixRef<
#prefix_fields_struct #ty_generics,
>
)#where_clause;
#doc_hidden_attr
#[doc=#prefix_fields_docs]
// A struct with all the prefix fields in the deriving type
//
// A field being in the prefix doesn't mean that it's
// unconditionally accessible, it just means that it won't cause a SEGFAULT.
#[repr(C #alignemnt)]
#vis struct #prefix_fields_struct #generics
#where_clause
{
#(
///
#prefix_field_vis #prefix_field: #prefix_field_ty,
)*
// Using this to ensure:
// - That all the generic arguments are used
// - That the struct has the same alignemnt as the deriving struct.
__sabi_pt_prefix_alignment: [#deriving_name #ty_generics ;0],
// Using this to ensure that the struct has at least the alignment of usize,
// so that adding pointer fields is not an ABI breaking change.
__sabi_usize_alignment: [usize; 0],
__sabi_pt_unbounds: ::abi_stable::pmr::NotCopyNotClone,
}
)
};
let mut accessor_buffer = String::new();
let mut uncond_acc_docs = Vec::<String>::new();
let mut cond_acc_docs = Vec::<String>::new();
let mut field_index_for = Vec::new();
let offset_consts: &[syn::Ident] = &struct_
.fields
.iter()
.map(|f| parse_str_as_ident(&format!("__sabi_offset_for_{}", f.pat_ident())))
.collect::<Vec<Ident>>();
// Creates the docs for the accessor functions.
// Creates the identifiers for constants associated with each field.
for field in struct_.fields.iter() {
use self::AccessorOrMaybe as AOM;
use std::fmt::Write;
let mut acc_doc_buffer = String::new();
let acc_on_missing = prefix.fields[field];
if is_ds_pub {
let _ = write!(
acc_doc_buffer,
"Accessor method for the `{deriving_name}::{field_name}` field.",
deriving_name = deriving_name,
field_name = field.pat_ident(),
);
match acc_on_missing {
AOM::Accessor => {
acc_doc_buffer.push_str("This is for a field which always exists.")
}
AOM::Maybe(MaybeAccessor {
on_missing: OnMissingField::ReturnOption,
..
}) => acc_doc_buffer.push_str(
"Returns `Some(field_value)` if the field exists,\
`None` if it does not.\
",
),
AOM::Maybe(MaybeAccessor {
on_missing: OnMissingField::Panic,
..
}) => acc_doc_buffer
.push_str("\n\n# Panic\n\nPanics if the field does not exist."),
AOM::Maybe(MaybeAccessor {
on_missing: OnMissingField::With { function },
..
}) => write!(
acc_doc_buffer,
"Returns `{function}()` if the field does not exist.",
function = (&function).into_token_stream()
)
.drop_(),
AOM::Maybe(MaybeAccessor {
on_missing: OnMissingField::Value { .. },
..
}) => acc_doc_buffer.push_str(
"\
Returns a default value (not Default::default()) \
if the field does not exist.\
",
),
AOM::Maybe(MaybeAccessor {
on_missing: OnMissingField::Default_,
..
}) => acc_doc_buffer
.push_str("Returns `Default::default()` if the field does not exist."),
};
}
if config.with_field_indices {
let field_name = field.pat_ident();
let mut new_ident = parse_str_as_ident(&format!("field_index_for_{}", field_name));
new_ident.set_span(field_name.span());
field_index_for.push(new_ident);
}
match acc_on_missing {
AOM::Accessor => {
uncond_acc_docs.push(acc_doc_buffer);
}
AOM::Maybe { .. } => {
cond_acc_docs.push(acc_doc_buffer);
}
}
}
let mut unconditional_accessors = Vec::new();
let mut conditional_accessors = Vec::new();
// Creates TokenStreams for each accessor function.
for (field_i, field) in struct_.fields.iter().enumerate() {
use std::fmt::Write;
accessor_buffer.clear();
write!(accessor_buffer, "{}", field.pat_ident()).drop_();
let vis = field.vis;
let mut getter_name = syn::parse_str::<Ident>(&accessor_buffer).expect("BUG");
getter_name.set_span(field.pat_ident().span());
let field_name = field.pat_ident();
let field_span = field_name.span();
let ty = field.ty;
let accessor_bounds = &prefix.accessor_bounds[field];
let field_where_clause = if accessor_bounds.is_empty() {
None
} else {
Some(quote!(where #ty:))
};
match prefix.fields[field] {
AccessorOrMaybe::Accessor => {
unconditional_accessors.push(quote_spanned! {field_span=>
#[allow(clippy::missing_const_for_fn)]
#vis fn #getter_name(&self)->#ty
#field_where_clause #( #accessor_bounds+ )*
{
self.0.prefix().#field_name
}
})
}
AccessorOrMaybe::Maybe(maybe_accessor) => {
let field_offset = &offset_consts[field_i];
let on_missing_field = maybe_accessor.on_missing;
let is_optional = on_missing_field == OnMissingField::ReturnOption;
let return_ty = if is_optional {
quote!( Option< #ty > )
} else {
quote!( #ty)
};
let else_ = match on_missing_field {
OnMissingField::ReturnOption => quote_spanned! {field_span=>
return None
},
OnMissingField::Panic => quote_spanned!(field_span=>
__sabi_re::panic_on_missing_field_ty::<
#deriving_name #ty_generics
>(
#field_i,
self._prefix_type_layout(),
)
),
OnMissingField::With { function } => quote_spanned! {field_span=>
#function()
},
OnMissingField::Value { value } => quote_spanned! {field_span=>
(#value)
},
OnMissingField::Default_ => quote_spanned! {field_span=>
Default::default()
},
};
let val_var = syn::Ident::new("val", Span::mixed_site());
let with_val = if is_optional {
quote_spanned!(field_span=> Some(#val_var) )
} else {
val_var.to_token_stream()
};
conditional_accessors.push(quote_spanned! {field_span=>
#[allow(clippy::missing_const_for_fn)]
#vis fn #getter_name(&self)->#return_ty
#field_where_clause #( #accessor_bounds+ )*
{
let acc_bits=self.0.field_accessibility().bits();
let #val_var=if (1u64<<#field_i & Self::__SABI_PTT_FAM & acc_bits)==0 {
#else_
}else{
unsafe{
*((self.0.to_raw_ptr() as *const u8)
.offset(Self::#field_offset as isize)
as *const #ty)
}
};
#with_val
}
});
}
}
}
let cond_field_indices = &prefix.cond_field_indices;
let enable_field_if = &prefix.enable_field_if;
let unconditional_bit_mask = &prefix.unconditional_bit_mask;
let cond_field_indices = cond_field_indices.iter();
let enable_field_if = enable_field_if.iter();
let field_i_a = 0u8..;
let mut pt_layout_ident = parse_str_as_ident(&format!("__sabi_PT_LAYOUT{}", deriving_name));
pt_layout_ident.set_span(deriving_name.span());
let mut generated_impls = quote!(
#[allow(non_upper_case_globals)]
const #pt_layout_ident:&'static __sabi_re::PTStructLayout ={
&__sabi_re::PTStructLayout::new(
#stringified_generics_tokenizer,
#mono_type_layout,
)
};
unsafe impl #impl_generics
__sabi_re::PrefixTypeTrait
for #deriving_name #ty_generics
where
#(#where_preds_a,)*
#(#prefix_bounds,)*
{
// Describes the accessibility of all the fields,
// used to initialize the `WithMetadata<Self>::_prefix_type_field_acc` field.
const PT_FIELD_ACCESSIBILITY:__sabi_re::FieldAccessibility={
__sabi_re::FieldAccessibility::from_u64(
#unconditional_bit_mask
#(
|(((#enable_field_if)as u64) << #cond_field_indices)
)*
)
};
// A description of the struct used for error messages.
const PT_LAYOUT:&'static __sabi_re::PTStructLayout =#pt_layout_ident;
type PrefixFields = #prefix_fields_struct #ty_generics;
type PrefixRef = #prefix_ref #ty_generics;
}
#[allow(non_upper_case_globals, clippy::needless_lifetimes, clippy::new_ret_no_self)]
impl #impl_generics #prefix_ref #ty_generics
where
#(#where_preds_b,)*
{
#(
#[doc=#uncond_acc_docs]
#unconditional_accessors
)*
#(
// This is the field index,starting with 0,from the top field.
const #field_index_for:u8=
#field_i_a;
)*
}
);
let first_offset = if let Some(constant) = offset_consts.first() {
quote!(
const #constant: usize = {
__sabi_re::WithMetadata_::<
#prefix_fields_struct #ty_generics,
#prefix_fields_struct #ty_generics,
>::__VALUE_OFFSET
};
)
} else {
quote!()
};
let prev_offsets = offset_consts.iter();
let curr_offsets = prev_offsets.clone().skip(1);
let prev_tys = struct_.fields.iter().map(|f| f.ty);
let curr_tys = prev_tys.clone().skip(1);
generated_impls.append_all(quote!(
#[allow(
clippy::ptr_offset_with_cast,
clippy::needless_lifetimes,
clippy::new_ret_no_self,
non_upper_case_globals,
)]
impl #impl_generics #prefix_ref #ty_generics
where
#(#where_preds_c,)*
#(#prefix_bounds,)*
{
#first_offset
#(
const #curr_offsets: usize =
__sabi_re::next_field_offset::<
#deriving_name #ty_generics,
#prev_tys,
#curr_tys,
>(Self::#prev_offsets);
)*
// The accessibility of all fields,
// used below to initialize the mask for each individual field.
//
// If the nth bit is:
// 0:the field is inaccessible.
// 1:the field is accessible.
const __SABI_PTT_FAM:u64=
<#deriving_name #ty_generics as
__sabi_re::PrefixTypeTrait
>::PT_FIELD_ACCESSIBILITY.bits();
/// Accessor to get the layout of the type,used for error messages.
#[inline(always)]
pub fn _prefix_type_layout(self)-> &'static __sabi_re::PTStructLayout {
self.0.type_layout()
}
#(
#[doc=#cond_acc_docs]
#conditional_accessors
)*
}
unsafe impl #impl_generics __sabi_re::GetPointerKind for #prefix_ref #ty_generics
where
#(#where_preds_rl,)*
{
type PtrTarget = __sabi_re::WithMetadata_<
#prefix_fields_struct #ty_generics,
#prefix_fields_struct #ty_generics,
>;
type Kind = __sabi_re::PK_Reference;
}
unsafe impl #impl_generics __sabi_re::PrefixRefTrait for #prefix_ref #ty_generics
where
#(#where_preds_r2,)*
{
type PrefixFields = #prefix_fields_struct #ty_generics;
}
impl #impl_generics Copy for #prefix_ref #ty_generics
where
#(#where_preds_e,)*
{}
impl #impl_generics Clone for #prefix_ref #ty_generics
where
#(#where_preds_f,)*
{
fn clone(&self) -> Self {
*self
}
}
));
PrefixTypeTokens {
prefixref_types: generated_types,
prefixref_impls: generated_impls,
}
})
}
|
pub mod lz78;
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::DPDCTRL {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `WAKEUPHYS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WAKEUPHYSR {
#[doc = "Disabled. Hysteresis for WAKUP pin disabled."]
DISABLED_HYSTERESIS,
#[doc = "Enabled. Hysteresis for WAKEUP pin enabled."]
ENABLED_HYSTERESIS_,
}
impl WAKEUPHYSR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
WAKEUPHYSR::DISABLED_HYSTERESIS => false,
WAKEUPHYSR::ENABLED_HYSTERESIS_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> WAKEUPHYSR {
match value {
false => WAKEUPHYSR::DISABLED_HYSTERESIS,
true => WAKEUPHYSR::ENABLED_HYSTERESIS_,
}
}
#[doc = "Checks if the value of the field is `DISABLED_HYSTERESIS`"]
#[inline]
pub fn is_disabled_hysteresis(&self) -> bool {
*self == WAKEUPHYSR::DISABLED_HYSTERESIS
}
#[doc = "Checks if the value of the field is `ENABLED_HYSTERESIS_`"]
#[inline]
pub fn is_enabled_hysteresis_(&self) -> bool {
*self == WAKEUPHYSR::ENABLED_HYSTERESIS_
}
}
#[doc = "Possible values of the field `WAKEPAD_DISABLE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WAKEPAD_DISABLER {
#[doc = "Enabled. The wake-up function is enabled on pin PIO0_4."]
ENABLED_THE_WAKE_UP,
#[doc = "Disabled. Setting this bit disables the wake-up function on pin PIO0_4."]
DISABLED_SETTING_TH,
}
impl WAKEPAD_DISABLER {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
WAKEPAD_DISABLER::ENABLED_THE_WAKE_UP => false,
WAKEPAD_DISABLER::DISABLED_SETTING_TH => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> WAKEPAD_DISABLER {
match value {
false => WAKEPAD_DISABLER::ENABLED_THE_WAKE_UP,
true => WAKEPAD_DISABLER::DISABLED_SETTING_TH,
}
}
#[doc = "Checks if the value of the field is `ENABLED_THE_WAKE_UP`"]
#[inline]
pub fn is_enabled_the_wake_up(&self) -> bool {
*self == WAKEPAD_DISABLER::ENABLED_THE_WAKE_UP
}
#[doc = "Checks if the value of the field is `DISABLED_SETTING_TH`"]
#[inline]
pub fn is_disabled_setting_th(&self) -> bool {
*self == WAKEPAD_DISABLER::DISABLED_SETTING_TH
}
}
#[doc = "Possible values of the field `LPOSCEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPOSCENR {
#[doc = "Disabled."]
DISABLED_,
#[doc = "Enabled."]
ENABLED_,
}
impl LPOSCENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
LPOSCENR::DISABLED_ => false,
LPOSCENR::ENABLED_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> LPOSCENR {
match value {
false => LPOSCENR::DISABLED_,
true => LPOSCENR::ENABLED_,
}
}
#[doc = "Checks if the value of the field is `DISABLED_`"]
#[inline]
pub fn is_disabled_(&self) -> bool {
*self == LPOSCENR::DISABLED_
}
#[doc = "Checks if the value of the field is `ENABLED_`"]
#[inline]
pub fn is_enabled_(&self) -> bool {
*self == LPOSCENR::ENABLED_
}
}
#[doc = "Possible values of the field `LPOSCDPDEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPOSCDPDENR {
#[doc = "Disabled."]
DISABLED_,
#[doc = "Enabled."]
ENABLED_,
}
impl LPOSCDPDENR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
LPOSCDPDENR::DISABLED_ => false,
LPOSCDPDENR::ENABLED_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> LPOSCDPDENR {
match value {
false => LPOSCDPDENR::DISABLED_,
true => LPOSCDPDENR::ENABLED_,
}
}
#[doc = "Checks if the value of the field is `DISABLED_`"]
#[inline]
pub fn is_disabled_(&self) -> bool {
*self == LPOSCDPDENR::DISABLED_
}
#[doc = "Checks if the value of the field is `ENABLED_`"]
#[inline]
pub fn is_enabled_(&self) -> bool {
*self == LPOSCDPDENR::ENABLED_
}
}
#[doc = "Values that can be written to the field `WAKEUPHYS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WAKEUPHYSW {
#[doc = "Disabled. Hysteresis for WAKUP pin disabled."]
DISABLED_HYSTERESIS,
#[doc = "Enabled. Hysteresis for WAKEUP pin enabled."]
ENABLED_HYSTERESIS_,
}
impl WAKEUPHYSW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
WAKEUPHYSW::DISABLED_HYSTERESIS => false,
WAKEUPHYSW::ENABLED_HYSTERESIS_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _WAKEUPHYSW<'a> {
w: &'a mut W,
}
impl<'a> _WAKEUPHYSW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: WAKEUPHYSW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disabled. Hysteresis for WAKUP pin disabled."]
#[inline]
pub fn disabled_hysteresis(self) -> &'a mut W {
self.variant(WAKEUPHYSW::DISABLED_HYSTERESIS)
}
#[doc = "Enabled. Hysteresis for WAKEUP pin enabled."]
#[inline]
pub fn enabled_hysteresis_(self) -> &'a mut W {
self.variant(WAKEUPHYSW::ENABLED_HYSTERESIS_)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `WAKEPAD_DISABLE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WAKEPAD_DISABLEW {
#[doc = "Enabled. The wake-up function is enabled on pin PIO0_4."]
ENABLED_THE_WAKE_UP,
#[doc = "Disabled. Setting this bit disables the wake-up function on pin PIO0_4."]
DISABLED_SETTING_TH,
}
impl WAKEPAD_DISABLEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
WAKEPAD_DISABLEW::ENABLED_THE_WAKE_UP => false,
WAKEPAD_DISABLEW::DISABLED_SETTING_TH => true,
}
}
}
#[doc = r" Proxy"]
pub struct _WAKEPAD_DISABLEW<'a> {
w: &'a mut W,
}
impl<'a> _WAKEPAD_DISABLEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: WAKEPAD_DISABLEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Enabled. The wake-up function is enabled on pin PIO0_4."]
#[inline]
pub fn enabled_the_wake_up(self) -> &'a mut W {
self.variant(WAKEPAD_DISABLEW::ENABLED_THE_WAKE_UP)
}
#[doc = "Disabled. Setting this bit disables the wake-up function on pin PIO0_4."]
#[inline]
pub fn disabled_setting_th(self) -> &'a mut W {
self.variant(WAKEPAD_DISABLEW::DISABLED_SETTING_TH)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `LPOSCEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPOSCENW {
#[doc = "Disabled."]
DISABLED_,
#[doc = "Enabled."]
ENABLED_,
}
impl LPOSCENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
LPOSCENW::DISABLED_ => false,
LPOSCENW::ENABLED_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _LPOSCENW<'a> {
w: &'a mut W,
}
impl<'a> _LPOSCENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: LPOSCENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disabled."]
#[inline]
pub fn disabled_(self) -> &'a mut W {
self.variant(LPOSCENW::DISABLED_)
}
#[doc = "Enabled."]
#[inline]
pub fn enabled_(self) -> &'a mut W {
self.variant(LPOSCENW::ENABLED_)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `LPOSCDPDEN`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum LPOSCDPDENW {
#[doc = "Disabled."]
DISABLED_,
#[doc = "Enabled."]
ENABLED_,
}
impl LPOSCDPDENW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
LPOSCDPDENW::DISABLED_ => false,
LPOSCDPDENW::ENABLED_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _LPOSCDPDENW<'a> {
w: &'a mut W,
}
impl<'a> _LPOSCDPDENW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: LPOSCDPDENW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disabled."]
#[inline]
pub fn disabled_(self) -> &'a mut W {
self.variant(LPOSCDPDENW::DISABLED_)
}
#[doc = "Enabled."]
#[inline]
pub fn enabled_(self) -> &'a mut W {
self.variant(LPOSCDPDENW::ENABLED_)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - WAKEUP pin hysteresis enable"]
#[inline]
pub fn wakeuphys(&self) -> WAKEUPHYSR {
WAKEUPHYSR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 1 - WAKEUP pin disable. Setting this bit disables the wake-up pin, so it can be used for other purposes. Never set this bit if you intend to use a pin to wake up the part from Deep power-down mode. You can only disable the wake-up pin if the self wake-up timer is enabled and configured. Setting this bit is not necessary if Deep power-down mode is not used."]
#[inline]
pub fn wakepad_disable(&self) -> WAKEPAD_DISABLER {
WAKEPAD_DISABLER::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - Enable the low-power oscillator for use with the 10 kHz self wake-up timer clock. You must set this bit if the CLKSEL bit in the self wake-up timer CTRL bit is set. Do not enable the low-power oscillator if the self wake-up timer is clocked by the divided IRC."]
#[inline]
pub fn lposcen(&self) -> LPOSCENR {
LPOSCENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 3 - Enable the low-power oscillator in Deep power-down mode. Setting this bit causes the low-power oscillator to remain running during Deep power-down mode provided that bit 12 in this register is set as well. You must set this bit for the self wake-up timer to be able to wake up the part from Deep power-down mode. Do not set this bit unless you must use the self wake-up timer to wake up from Deep power-down mode."]
#[inline]
pub fn lposcdpden(&self) -> LPOSCDPDENR {
LPOSCDPDENR::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - WAKEUP pin hysteresis enable"]
#[inline]
pub fn wakeuphys(&mut self) -> _WAKEUPHYSW {
_WAKEUPHYSW { w: self }
}
#[doc = "Bit 1 - WAKEUP pin disable. Setting this bit disables the wake-up pin, so it can be used for other purposes. Never set this bit if you intend to use a pin to wake up the part from Deep power-down mode. You can only disable the wake-up pin if the self wake-up timer is enabled and configured. Setting this bit is not necessary if Deep power-down mode is not used."]
#[inline]
pub fn wakepad_disable(&mut self) -> _WAKEPAD_DISABLEW {
_WAKEPAD_DISABLEW { w: self }
}
#[doc = "Bit 2 - Enable the low-power oscillator for use with the 10 kHz self wake-up timer clock. You must set this bit if the CLKSEL bit in the self wake-up timer CTRL bit is set. Do not enable the low-power oscillator if the self wake-up timer is clocked by the divided IRC."]
#[inline]
pub fn lposcen(&mut self) -> _LPOSCENW {
_LPOSCENW { w: self }
}
#[doc = "Bit 3 - Enable the low-power oscillator in Deep power-down mode. Setting this bit causes the low-power oscillator to remain running during Deep power-down mode provided that bit 12 in this register is set as well. You must set this bit for the self wake-up timer to be able to wake up the part from Deep power-down mode. Do not set this bit unless you must use the self wake-up timer to wake up from Deep power-down mode."]
#[inline]
pub fn lposcdpden(&mut self) -> _LPOSCDPDENW {
_LPOSCDPDENW { w: self }
}
}
|
use std::f64;
use crate::simulation::colony::Colony;
use crate::simulation::environment::Environment;
use crate::neural_network::mlp::MLP;
pub struct Simulation {
pub environment: Environment,
pub colony: Colony,
}
pub struct SimulationResult {
pub num_iters: usize,
pub food_returned_to_nest: f64,
pub food_remaining: f64,
pub proportion_explored: f64
}
impl Simulation {
pub fn new(arena_size: usize, diffusion_rate: f64, num_ants: usize, decision_network: MLP) -> Simulation {
let environment = Environment::new(arena_size, diffusion_rate);
let colony = Colony::new(num_ants, decision_network);
Simulation {
environment,
colony,
}
}
pub fn run(&mut self, num_steps: usize) -> SimulationResult {
let mut i = 0;
while i < num_steps {
self.environment.update();
self.colony.update(&mut self.environment);
i += 1;
};
SimulationResult::new(
i,
self.environment.food_returned_to_nest,
self.environment.total_food_remaining(),
self.environment.num_cells_visited() as f64/ self.environment.size.pow(2) as f64
)
}
}
impl SimulationResult {
pub fn new(num_iters: usize, food_returned_to_nest: f64, food_remaining: f64, proportion_explored: f64) -> SimulationResult {
SimulationResult {
num_iters,
food_returned_to_nest,
food_remaining,
proportion_explored
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simulation_new() {
let decision_network: MLP = MLP::new(37, vec![16, 1]);
let simulation = Simulation::new(50, 0.99, 100, decision_network);
assert_eq!(simulation.environment.size, 50);
}
#[test]
fn test_simulation_run() {
let decision_network: MLP = MLP::new(38, vec![16, 1]);
let mut simulation = Simulation::new(50, 0.99, 100, decision_network);
let _sim_result = simulation.run(10);
// let fake_sim_result = SimulationResult::new(10, 0., 25.);
// assert_eq!(sim_result.num_iters, fake_sim_result.num_iters);
}
} |
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let d = scan!(f64);
println!("{:.10}", d / 100.0);
}
|
pub mod capture_policy;
|
use crate::objects::{game_data::GameData, node::Node};
/// distributes starting ressources to players
pub fn setup_players(mut gd: GameData) -> GameData {
for i in 0..gd.players.len() {
let player_id = gd.players[i].id.clone();
let exec_ids = find_start_execs(&gd);
for id in exec_ids {
gd.add_exec_to_player(&id, &player_id);
}
let node_id = find_start_node(&gd).expect("{}");
gd.add_node_to_player(&node_id, &player_id);
}
gd
}
pub fn find_start_node<'a>(gd: &'a mut GameData) -> Result<&'a mut Node, String> {
let mut node_id: &str = "";
let rows = gd.map.iter();
for row in rows {
let nodes = row.iter_mut();
for node in nodes {
if node_allowed(&gd, node) {
return Ok(node);
}
}
if node_id.len() > 0 {
break;
}
}
return Err(String::from("Fuck"));
}
pub fn find_start_execs(gd: &GameData) -> Vec<super::objects::exec::Exec> {
// Make this loop variable? -> config would be part of GameData
let mut execs: Vec<super::objects::exec::Exec> = Vec::with_capacity(gd.config.starting_execs as usize);
while execs.len() < gd.config.starting_execs as usize {
let _execs = gd.execs.iter();
for exec in _execs {
let fuck = execs.iter().find( |e| e.id == exec.id);
if exec.employer == "" && fuck.is_none() {
execs.push(*exec);
break;
}
}
}
execs
}
fn node_allowed(gd: &GameData, node: &Node) -> bool {
// Ownerless
if node.owner != "" {
return false;
}
// Away from map-boarders
if node.y < 2 || node.y > gd.map.len() as u32 -3 {
return false;
}
if node.x < 2 || node.x > gd.map[0].len() as u32 -3 {
return false;
}
// Node away from other owned nodes
let check_blocker = |old_node: &Node| {
let inside_radius = |val, old_val| val >= old_val-2 && val <= old_val+2;
old_node.owner != "" && inside_radius(node.x, old_node.x) && inside_radius(node.y, old_node.y)
};
for row in gd.map.iter() {
if row.iter().filter( |n| check_blocker(n) ).count() > 0 {
return false;
}
}
true
}
#[cfg(test)]
mod tests {
#[allow(unused_imports)]
use super::*;
#[allow(unused_imports)]
use std::collections::HashMap;
use crate::objects::{config::Config, player::Player};
#[test]
fn test_node_allowed() {
let config = Config {
map_size: vec![11,11],
player_number: 4,
starting_money: 0,
starting_nodes: 1,
starting_distance: 2,
starting_boarder_distance: 2,
starting_execs: 1
};
let mut gd = GameData::new(config);
// Owned
let mut owned = Node::new(&vec![2,2]);
owned.owner = String::from("Jackshit");
assert!( !node_allowed(&gd, &owned));
// Outside allowed area
let out_of_boarder = vec![Node::new(&vec![2,1]), Node::new(&vec![9,2]), Node::new(&vec![2,9]), Node::new(&vec![1,2])];
for node in out_of_boarder.iter() {
assert!( !node_allowed(&gd, &node) );
}
// Inside allowed area
let inside_boarder = vec![Node::new(&vec![2,2]), Node::new(&vec![8,2]), Node::new(&vec![8,8]), Node::new(&vec![2,8])];
for node in inside_boarder.iter() {
assert!(node_allowed(&gd, &node));
}
// Not colliding with other node
let evil_player = Player::new(String::from("Fuck"), String::from("You"), 0);
let pid = evil_player.id.clone();
let evil_node = Node::new(&vec![5,5]);
gd.players.push(evil_player);
gd.add_node_to_player(&mut evil_node, &pid);
let inside_player_area = vec![Node::new(&vec![3,3]), Node::new(&vec![3,7]), Node::new(&vec![7,3]), Node::new(&vec![7,7])];
for node in inside_player_area.iter() {
assert!( !node_allowed(&gd, &node), "failed for {}/{}, Map.len(): {}", &node.x, &node.y, gd.map.len());
}
let outside_player_area = vec![Node::new(&vec![2,2]), Node::new(&vec![2,8]), Node::new(&vec![8,2]), Node::new(&vec![8,8])];
for node in outside_player_area.iter() {
assert!( node_allowed(&gd, &node), "failed for {}/{}", &node.x, &node.y );
}
}
#[test]
fn test_find_start_node() {
// Config
let nodes_per_length = |length: f32, space_to_boarder: f32, space_between: f32| { return ((length - 2_f32*space_to_boarder) / (space_between+1_f32)).ceil() };
let (map_len, map_hei, space_to_boarder, space_between) = (8, 8, 2, 2); // To be moved to config-struct
let nodes_per_row = nodes_per_length(map_len as f32, space_to_boarder as f32, space_between as f32) as usize;
let nodes_per_col = nodes_per_length(map_hei as f32, space_to_boarder as f32, space_between as f32) as usize;
let nr_nodes = nodes_per_row * nodes_per_col;
let config = Config::new(vec![map_len,map_hei], 4, 0, 1, space_between, space_to_boarder, 1);
let mut game_data = GameData::new(config);
let player_id = game_data.players[0].id.to_owned();
let mut node_coord: Vec<HashMap<&str, u32>> = Vec::with_capacity(nr_nodes);
// Test starts here
while node_coord.len() < node_coord.capacity() {
let node = find_start_node(&mut game_data).expect("{}");
// Ensure real node without owner
assert_eq!(node.owner, "", "Node nr {}", node_coord.len()+1);
let hm: HashMap<&str, u32> = [
("x", node.x),
("y", node.y)
].iter().cloned().collect();
node_coord.push(hm);
game_data.add_node_to_player(&mut node, &player_id);
}
for node in node_coord.iter() {
let x = node.get("x").unwrap();
let y = node.get("y").unwrap();
// Node 2 rows and cols from map-boarders away
assert!( x > &(1), "X should be > {} -> x: {} | {:?}", space_to_boarder-1, x, node_coord );
assert!( x < &( map_len - 1), "X should be < {} -> x: {} | {:?}", map_len - 1, x, node_coord);
assert!( y > &(1), "Y should be > {} -> y: {}, | {:?}", space_to_boarder-1, y, node_coord );
assert!( y < &(map_hei - 1), "Y should be < {} -> y: {} | {:?}",(map_hei - 1), y, node_coord );
// Node at least 2 rows and cols from next player-owned node
let check = |n: &HashMap<&str, u32>, arg: &str| {
let coordinate = node.get(arg).unwrap();
let old_coordinate = n.get(arg).unwrap();
if old_coordinate < &(space_to_boarder+1) {
return coordinate > &(space_to_boarder+space_between+1);
} else {
return coordinate > &(old_coordinate+space_between+1) && coordinate < &(old_coordinate-space_between-1);
}
};
let close_nodes_x = node_coord.iter().filter( |n| check(n, "x") ).count();
let close_nodes_y = node_coord.iter().filter( |n| check(n, "y") ).count();
assert_eq!( close_nodes_x, 0, "Owned starting nodes to close to each other (x-row) -> {} nodes too close, {} Nodes required; {:?}", close_nodes_x, nr_nodes, node_coord );
assert_eq!( close_nodes_y, 0, "Owned starting nodes to close to each other (y-row) -> {} nodes too close, {} Nodes required; {:?}", close_nodes_y, nr_nodes, node_coord );
}
}
#[test]
fn test_find_start_execs() {
let mut game_data = crate::objects::game_data::GameData::new(Config::read_config());
let exec_ids = find_start_execs(&game_data);
let execs_ids_iter = exec_ids.iter();
for exec_id in execs_ids_iter {
assert_eq!(exec_ids.iter().filter( |&e| e == exec_id ).count(), 1);
assert_eq!(game_data.get_exec(exec_id).employer, "");
}
}
} |
use yew::prelude::*;
use yew_router::components::RouterAnchor;
use crate::app::AppRoute;
pub struct EnterpriseGoogle {
// link: ComponentLink<Self>
}
pub enum Msg {}
impl Component for EnterpriseGoogle {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, _link: ComponentLink<Self>) -> Self {
EnterpriseGoogle {
// link
}
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
true
}
fn change(&mut self, _: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
type Anchor = RouterAnchor<AppRoute>;
html! {
<div
class="py-5 px-4 m-auto"
style="max-width: 1048px; font-size:14px;"
>
<Anchor
route=AppRoute::EnterpriseHome
classes="text-decoration-none domain-link-dark"
>
<i class="bi bi-arrow-left me-2"></i>
{"Back to Enterprise Connections"}
</Anchor>
<div
class="d-flex mb-4 mt-3"
>
<div
class="d-flex flex-column"
>
<h2>{"Google Workspace"}</h2>
</div>
</div>
<div style="
display: flex;
text-align: center;
align-items: center;
flex-direction: column;
padding: 40px;
border-radius: 6px;
border: 1px solid #e3e4e6;
"
>
<i class="bi bi-briefcase text-color-secondary" style="font-size:150px; opacity:.5;"></i>
<div>
{"No items have been added to this section."}
</div>
<button
class="btn btn-primary"
style=" color: #fff;
background-color: #635dff;
box-shadow: none;
border-radius: 4px;
padding: 8px 16px;
margin: 20px"
>
<Anchor
route=AppRoute::EnterpriseGoogleCreate
classes="text-decoration-none text-light px-2 link-primary pe-auto"
>
{"+ Create Connection"}
</Anchor>
</button>
<a
href="https://auth0.com/docs/sso/single-sign-on"
target="_blank"
style="text-decoration: none;"
>{"Learn More"}</a>
</div>
</div>
}
}
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::chain_service::BlockChainCollection;
use actix::prelude::*;
use anyhow::{format_err, Error, Result};
use config::NodeConfig;
use crypto::HashValue;
use executor::block_executor::BlockExecutor;
use executor::executor::mock_create_account_txn;
use logger::prelude::*;
use network::get_unix_ts;
use once_cell::sync::Lazy;
use starcoin_accumulator::node::ACCUMULATOR_PLACEHOLDER_HASH;
use starcoin_accumulator::{Accumulator, MerkleAccumulator};
use starcoin_state_api::{ChainState, ChainStateReader};
use starcoin_statedb::ChainStateDB;
use starcoin_txpool_api::TxPoolAsyncService;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::sync::{Arc, Weak};
use std::time::{SystemTime, UNIX_EPOCH};
use storage::Store;
use traits::Consensus;
use traits::{ChainReader, ChainWriter};
use types::{
account_address::AccountAddress,
block::{Block, BlockHeader, BlockInfo, BlockNumber, BlockTemplate, BLOCK_INFO_DEFAULT_ID},
block_metadata::BlockMetadata,
startup_info::ChainInfo,
transaction::{SignedUserTransaction, Transaction, TransactionInfo},
U512,
};
pub static DEFAULT_BLOCK_INFO: Lazy<BlockInfo> = Lazy::new(|| {
BlockInfo::new(
*BLOCK_INFO_DEFAULT_ID,
*ACCUMULATOR_PLACEHOLDER_HASH,
vec![],
0,
0,
U512::zero(),
)
});
pub struct BlockChain<C, S, P>
where
C: Consensus,
S: Store + 'static,
P: TxPoolAsyncService + 'static,
{
pub config: Arc<NodeConfig>,
accumulator: MerkleAccumulator,
head: Block,
chain_state: ChainStateDB,
phantom_c: PhantomData<C>,
pub storage: Arc<S>,
pub txpool: P,
chain_info: ChainInfo,
pub block_chain_collection: Weak<BlockChainCollection<C, S, P>>,
}
impl<C, S, P> BlockChain<C, S, P>
where
C: Consensus,
S: Store,
P: TxPoolAsyncService,
{
pub fn new(
config: Arc<NodeConfig>,
chain_info: ChainInfo,
storage: Arc<S>,
txpool: P,
block_chain_collection: Weak<BlockChainCollection<C, S, P>>,
) -> Result<Self> {
let head_block_hash = chain_info.get_head();
let head = storage
.get_block_by_hash(head_block_hash)?
.ok_or(format_err!(
"Can not find block by hash {}",
head_block_hash
))?;
// let block_info = match storage.clone().get_block_info(head_block_hash) {
// Ok(Some(block_info_1)) => block_info_1,
// Err(e) => {
// warn!("err : {:?}", e);
// DEFAULT_BLOCK_INFO.clone()
// }
// _ => DEFAULT_BLOCK_INFO.clone(),
// };
let state_root = head.header().state_root();
let chain = Self {
config: config.clone(),
accumulator: MerkleAccumulator::new(
chain_info.branch_id(),
*ACCUMULATOR_PLACEHOLDER_HASH,
vec![],
0,
0,
storage.clone(),
)
.unwrap(),
head,
chain_state: ChainStateDB::new(storage.clone(), Some(state_root)),
phantom_c: PhantomData,
storage,
txpool,
chain_info,
block_chain_collection,
};
Ok(chain)
}
pub fn save_block(&self, block: &Block) {
if let Err(e) = self
.storage
.commit_branch_block(self.get_chain_info().branch_id(), block.clone())
{
warn!("err : {:?}", e);
}
debug!("commit block : {:?}", block.header().id());
}
fn get_block_info(&self, block_id: HashValue) -> BlockInfo {
let block_info = match self.storage.get_block_info(block_id) {
Ok(Some(block_info_1)) => block_info_1,
Err(e) => {
warn!("err : {:?}", e);
DEFAULT_BLOCK_INFO.clone()
}
_ => DEFAULT_BLOCK_INFO.clone(),
};
block_info
}
pub fn save_block_info(&self, block_info: BlockInfo) {
if let Err(e) = self.storage.save_block_info(block_info) {
warn!("err : {:?}", e);
}
}
fn gen_tx_for_test(&self) {
let tx = mock_create_account_txn();
let txpool = self.txpool.clone();
Arbiter::spawn(async move {
debug!("gen_tx_for_test call txpool.");
txpool.add(tx.try_into().unwrap()).await.unwrap();
});
}
pub fn latest_blocks(&self, size: u64) {
let mut count = 0;
let mut last = self.head.header().clone();
loop {
info!(
"block chain :: number : {} , block_id : {:?}",
last.number(),
last.id()
);
if last.number() == 0 || count >= size {
break;
}
last = self
.get_header(last.parent_hash())
.unwrap()
.unwrap()
.clone();
count = count + 1;
}
}
pub fn create_block_template_inner(
&self,
author: AccountAddress,
auth_key_prefix: Option<Vec<u8>>,
previous_header: BlockHeader,
user_txns: Vec<SignedUserTransaction>,
) -> Result<BlockTemplate> {
//TODO calculate gas limit etc.
let mut txns = user_txns
.iter()
.cloned()
.map(|user_txn| Transaction::UserTransaction(user_txn))
.collect::<Vec<Transaction>>();
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
txns.push(Transaction::BlockMetadata(BlockMetadata::new(
previous_header.id(),
timestamp,
author,
auth_key_prefix.clone(),
)));
let chain_state =
ChainStateDB::new(self.storage.clone(), Some(previous_header.state_root()));
// let block_info = self.get_block_info(previous_header.id());
let accumulator = MerkleAccumulator::new(
self.chain_info.branch_id(),
*ACCUMULATOR_PLACEHOLDER_HASH,
vec![],
0,
0,
self.storage.clone(),
)?;
let (accumulator_root, state_root, _) =
BlockExecutor::block_execute(&chain_state, &accumulator, txns, true)?;
Ok(BlockTemplate::new(
previous_header.id(),
timestamp,
previous_header.number() + 1,
author,
auth_key_prefix,
accumulator_root,
state_root,
0,
0,
user_txns.into(),
))
}
pub fn fork(&self, block_header: &BlockHeader) -> Option<ChainInfo> {
if self.exist_block(block_header.parent_hash()) {
Some(if self.head.header().id() == block_header.parent_hash() {
self.get_chain_info()
} else {
ChainInfo::new(
Some(self.get_chain_info().branch_id()),
block_header.parent_hash(),
block_header,
)
})
} else {
None
}
}
pub fn get_branch_id(&self, number: BlockNumber) -> Option<HashValue> {
self.block_chain_collection
.upgrade()
.unwrap()
.get_branch_id(&self.chain_info.branch_id(), number)
}
pub fn update_head(&mut self, latest_block: BlockHeader) {
self.chain_info.update_head(latest_block)
}
}
impl<C, S, P> Drop for BlockChain<C, S, P>
where
C: Consensus,
S: Store,
P: TxPoolAsyncService,
{
fn drop(&mut self) {
debug!(
"drop BlockChain: {}, {}",
self.block_chain_collection.strong_count(),
self.block_chain_collection.weak_count()
);
drop(&self.block_chain_collection);
}
}
impl<C, S, P> ChainReader for BlockChain<C, S, P>
where
C: Consensus,
S: Store,
P: TxPoolAsyncService,
{
fn head_block(&self) -> Block {
self.head.clone()
}
fn current_header(&self) -> BlockHeader {
self.head.header().clone()
}
fn get_header(&self, hash: HashValue) -> Result<Option<BlockHeader>> {
assert!(self.exist_block(hash));
Ok(Some(
self.get_block(hash).unwrap().unwrap().header().clone(),
))
}
fn get_header_by_number(&self, number: u64) -> Result<Option<BlockHeader>> {
if let Some(branch_id) = self.get_branch_id(number) {
self.storage.get_header_by_branch_number(branch_id, number)
} else {
Ok(None)
}
}
fn get_block_by_number(&self, number: BlockNumber) -> Result<Option<Block>> {
if let Some(branch_id) = self.get_branch_id(number) {
self.storage.get_block_by_branch_number(branch_id, number)
} else {
warn!("branch id not found.");
Ok(None)
}
}
fn get_blocks_by_number(&self, number: BlockNumber, count: u64) -> Result<Vec<Block>, Error> {
let mut block_vec = vec![];
let mut temp_number = number;
if number == 0 as u64 {
temp_number = self.current_header().number();
}
if let Some(branch_id) = self.get_branch_id(temp_number) {
let mut tmp_count = count;
let mut current_num = temp_number;
loop {
match self
.storage
.get_block_by_branch_number(branch_id, current_num)
{
Ok(block) => {
if block.is_some() {
block_vec.push(block.unwrap());
}
}
Err(_e) => {
error!(
"get block by branch {:?} number{:?} err.",
branch_id, current_num
);
}
}
if current_num == 0 || tmp_count == 1 {
break;
}
current_num = current_num - 1;
tmp_count = tmp_count - 1;
}
} else {
warn!("branch id not found.");
}
Ok(block_vec)
}
fn get_block(&self, hash: HashValue) -> Result<Option<Block>> {
let block = self.storage.get_block_by_hash(hash);
match block {
Ok(tmp) => match tmp {
Some(b) => {
if let Ok(Some(block_header)) = self.get_header_by_number(b.header().number()) {
if block_header.id() == b.header().id() {
return Ok(Some(b));
} else {
warn!("block is miss match {:?} : {:?}", hash, block_header.id());
}
}
}
None => {
warn!("Get block from storage return none.");
}
},
Err(e) => {
warn!("err:{:?}", e);
}
}
return Ok(None);
}
fn get_block_transactions(&self, block_id: HashValue) -> Result<Vec<TransactionInfo>, Error> {
let mut txn_vec = vec![];
match self.storage.get_block_transactions(block_id) {
Ok(vec_hash) => {
for hash in vec_hash {
match self.get_transaction_info(hash) {
Ok(Some(transaction_info)) => txn_vec.push(transaction_info),
_ => error!("get transaction info error: {:?}", hash),
}
}
}
_ => {}
}
Ok(txn_vec)
}
fn get_transaction(&self, txn_hash: HashValue) -> Result<Option<Transaction>, Error> {
self.storage.get_transaction(txn_hash)
}
fn get_transaction_info(&self, hash: HashValue) -> Result<Option<TransactionInfo>, Error> {
self.storage.get_transaction_info(hash)
}
fn create_block_template(
&self,
author: AccountAddress,
auth_key_prefix: Option<Vec<u8>>,
parent_hash: Option<HashValue>,
user_txns: Vec<SignedUserTransaction>,
) -> Result<BlockTemplate> {
let block_id = match parent_hash {
Some(hash) => hash,
None => self.current_header().id(),
};
assert!(self.exist_block(block_id));
let previous_header = self.get_header(block_id)?.unwrap();
self.create_block_template_inner(author, auth_key_prefix, previous_header, user_txns)
}
fn chain_state_reader(&self) -> &dyn ChainStateReader {
&self.chain_state
}
fn gen_tx(&self) -> Result<()> {
self.gen_tx_for_test();
Ok(())
}
fn get_chain_info(&self) -> ChainInfo {
self.chain_info.clone()
}
fn get_block_info(&self, block_id: Option<HashValue>) -> Result<Option<BlockInfo>> {
let id = match block_id {
Some(hash) => hash,
None => self.current_header().id(),
};
assert!(self.exist_block(id));
self.storage.get_block_info(id)
}
fn get_total_difficulty(&self) -> Result<U512> {
let block_info = self.storage.get_block_info(self.head.header().id())?;
Ok(block_info.map_or(U512::zero(), |info| info.total_difficulty))
}
fn exist_block(&self, block_id: HashValue) -> bool {
if let Ok(Some(_)) = self.get_block(block_id) {
true
} else {
false
}
}
}
impl<C, S, P> ChainWriter for BlockChain<C, S, P>
where
C: Consensus,
S: Store,
P: TxPoolAsyncService,
{
fn apply(&mut self, block: Block) -> Result<bool> {
let header = block.header();
debug!(
"Apply block {:?} to {:?}",
block.header(),
self.head.header()
);
//TODO custom verify macro
assert_eq!(self.head.header().id(), block.header().parent_hash());
let apply_begin_time = get_unix_ts();
if let Err(e) = C::verify_header(self.config.clone(), self, header) {
error!("err: {:?}", e);
return Ok(false);
}
let verify_end_time = get_unix_ts();
debug!("verify used time: {}", (verify_end_time - apply_begin_time));
let chain_state = &self.chain_state;
let mut txns = block
.transactions()
.iter()
.cloned()
.map(|user_txn| Transaction::UserTransaction(user_txn))
.collect::<Vec<Transaction>>();
let block_metadata = header.clone().into_metadata();
txns.push(Transaction::BlockMetadata(block_metadata));
let exe_begin_time = get_unix_ts();
let (accumulator_root, state_root, vec_transaction_info) =
BlockExecutor::block_execute(chain_state, &self.accumulator, txns.clone(), false)?;
let exe_end_time = get_unix_ts();
debug!("exe used time: {}", (exe_end_time - exe_begin_time));
assert_eq!(
block.header().state_root(),
state_root,
"verify block:{:?} state_root fail.",
block.header().id()
);
let total_difficulty = {
let pre_total_difficulty = self
.get_block_info(block.header().parent_hash())
.total_difficulty;
pre_total_difficulty + header.difficult().into()
};
let block_info = BlockInfo::new(
header.id().clone(),
accumulator_root,
self.accumulator.get_frozen_subtree_roots()?,
self.accumulator.num_leaves(),
self.accumulator.num_nodes(),
total_difficulty,
);
// save block's transaction relationship and save transaction
self.save(header.id().clone(), txns.clone())?;
self.storage.save_transaction_infos(vec_transaction_info)?;
let commit_begin_time = get_unix_ts();
self.commit(block.clone(), block_info)?;
let commit_end_time = get_unix_ts();
debug!(
"commit used time: {}",
(commit_end_time - commit_begin_time)
);
Ok(true)
}
fn commit(&mut self, block: Block, block_info: BlockInfo) -> Result<()> {
let block_id = block.header().id();
self.save_block(&block);
self.chain_info.update_head(block.header().clone());
self.head = block;
self.accumulator = MerkleAccumulator::new(
self.chain_info.branch_id(),
*ACCUMULATOR_PLACEHOLDER_HASH,
vec![],
0,
0,
self.storage.clone(),
)
.unwrap();
self.save_block_info(block_info);
self.chain_state =
ChainStateDB::new(self.storage.clone(), Some(self.head.header().state_root()));
debug!("save block {:?} succ.", block_id);
Ok(())
}
fn save(&mut self, block_id: HashValue, transactions: Vec<Transaction>) -> Result<()> {
let txn_id_vec = transactions
.iter()
.cloned()
.map(|user_txn| user_txn.id())
.collect::<Vec<HashValue>>();
// save block's transactions
self.storage
.save_block_transactions(block_id, txn_id_vec)
.unwrap();
// save transactions
self.storage.save_transaction_batch(transactions).unwrap();
Ok(())
}
fn chain_state(&mut self) -> &dyn ChainState {
&self.chain_state
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::prelude::*;
use std::fs::OpenOptions;
use std::string::String;
use std::ffi::CString;
use libc::*;
use super::vmspace::syscall::*;
use super::qlib::SysCallID;
pub fn GetRet(ret: i32) -> i32 {
if ret == -1 {
return -errno::errno().0
}
return ret
}
pub struct Util {}
impl Util {
fn WriteFile(filename: &str, str: &str) {
//let mut file = File::open(filename).expect("Open file fail");
let mut file = OpenOptions::new().write(true).truncate(true).open(&filename).expect("Open file fail");
file.write_all(str.as_bytes()).expect("write all fail");
}
pub fn Mount(src: &str, target: &str, fstype: &str, flags: u64, data: &str) -> i32 {
let src = CString::new(src.clone()).expect("CString::new src failed");
let target = CString::new(target.clone()).expect("CString::new target failed");
let fstype = CString::new(fstype.clone()).expect("CString::new fstype failed");
let data = CString::new(data.clone()).expect("CString::new fstype failed");
let srcAddr = if src.as_bytes().len() ==0 {
0 as *const c_char
} else {
src.as_ptr()
};
let targetAddr = if target.as_bytes().len() ==0 {
0 as *const c_char
} else {
target.as_ptr()
};
let fstypeAddr = if fstype.as_bytes().len() ==0 {
0 as *const c_char
} else {
fstype.as_ptr()
};
let dataAddr = if data.as_bytes().len() ==0 {
0 as *const c_void
} else {
data.as_ptr() as *const c_void
};
return unsafe {
GetRet(mount(srcAddr, targetAddr, fstypeAddr, flags, dataAddr as *const c_void))
}
}
pub fn Umount2(target: &str, flags: i32) -> i32 {
let target = CString::new(target.clone()).expect("CString::new target failed");
return unsafe {
GetRet(umount2(target.as_ptr(), flags))
}
}
pub fn Chdir(dir: &str) -> i32 {
let dir = CString::new(dir.clone()).expect("CString::new src failed");
return unsafe {
GetRet(chdir(dir.as_ptr()))
}
}
pub fn Mkdir(path: &str, mode: u32) -> i32 {
let path = CString::new(path.clone()).expect("CString::new src failed");
return unsafe {
GetRet(mkdir(path.as_ptr(), mode))
}
}
pub fn PivotRoot(newRoot: &str, putOld: &str) -> i32 {
let newRoot = CString::new(newRoot.clone()).expect("CString::new src failed");
let putOld = CString::new(putOld.clone()).expect("CString::new target failed");
let nr = SysCallID::sys_pivot_root as usize;
unsafe {
return GetRet(syscall2(nr, newRoot.as_ptr() as usize, putOld.as_ptr() as usize) as i32);
}
}
}
pub struct MountNs {
pub rootfs: String,
}
impl MountNs {
pub fn New(rootfs: String) -> Self {
return Self {
rootfs: rootfs
}
}
pub fn PivotRoot(&self) {
/*let flags = MS_REC | MS_SLAVE;
if Util::Mount("","/", "", flags, "") < 0 {
panic!("mount root fail")
}*/
if Util::Chdir(&self.rootfs) < 0 {
panic!("chdir fail for rootfs {}", &self.rootfs)
}
let errno = Util::PivotRoot(".", ".");
if errno != 0 {
panic!("pivot fail with errno = {}", errno)
}
if Util::Chdir("/") < 0 {
panic!("chdir fail")
}
if Util::Umount2("/", MNT_DETACH) < 0 {
panic!("UMount2 fail")
}
}
pub fn PivotRoot1(&self) {
let flags = MS_REC | MS_SLAVE;
if Util::Mount("","/", "", flags, "") < 0 {
panic!("mount root fail")
}
if Util::Mount(&self.rootfs, &self.rootfs, "", MS_REC | MS_BIND, "") < 0 {
panic!("mount rootfs fail")
}
if Util::Chdir(&self.rootfs) == -1 {
panic!("chdir fail")
}
let errno = Util::PivotRoot(".", ".");
if errno != 0 {
panic!("pivot fail with errno = {}", errno)
}
if Util::Chdir("/") == -1 {
panic!("chdir fail")
}
if Util::Umount2("/", MNT_DETACH) < 0 {
panic!("UMount2 fail")
}
}
pub fn PrepareProcfs(&self) {
let proc = "/proc".to_string();
if Util::Mkdir(&proc, 0o555) == -1 && errno::errno().0 != EEXIST {
panic!("mkdir put_old fail")
}
if Util::Mount(&"proc".to_string(), &proc, &"proc".to_string(), 0, &"".to_string()) < 0 {
panic!("mount rootfs fail")
}
}
}
pub struct UserNs {
pub pid: i32,
pub uid: i32,
pub gid: i32,
}
impl UserNs {
pub fn New(pid: i32, uid: i32) -> Self {
return Self {
pid: pid,
uid: uid,
gid: uid,
}
}
pub fn Set(&self) {
let path = format!("/proc/{}/uid_map", self.pid);
let line = format!("0 {} 1\n", self.uid);
Util::WriteFile(&path, &line);
let path = format!("/proc/{}/setgroups", self.pid);
let line = format!("deny");
Util::WriteFile(&path, &line);
let path = format!("/proc/{}/gid_map", self.pid);
let line = format!("0 {} 1\n", self.gid);
Util::WriteFile(&path, &line);
}
// Map nobody in the new namespace to nobody in the parent namespace.
//
// A sandbox process will construct an empty
// root for itself, so it has to have the CAP_SYS_ADMIN
// capability.
//
pub fn SetNobody(&self) {
let nobody = 65534;
let path = format!("/proc/{}/uid_map", self.pid);
let line = format!("0 {} 1\n", nobody - 1);
let line = line + &format!("{} {} 1\n", nobody, nobody);
Util::WriteFile(&path, &line);
let path = format!("/proc/{}/gid_map", self.pid);
let line = format!("{} {} 1\n", nobody, nobody);
Util::WriteFile(&path, &line);
}
} |
use std::ops::Deref;
/// Trait to allow trimming ascii whitespace from a &[u8].
pub trait TrimAsciiWhitespace {
/// Trim ascii whitespace (based on `is_ascii_whitespace()`) from the
/// start and end of a slice.
fn trim_ascii_whitespace(&self) -> &[u8];
}
impl<T: Deref<Target = [u8]>> TrimAsciiWhitespace for T {
fn trim_ascii_whitespace(&self) -> &[u8] {
let from = match self.iter().position(|x| !x.is_ascii_whitespace()) {
Some(i) => i,
None => return &self[0..0],
};
let to = self.iter().rposition(|x| !x.is_ascii_whitespace()).unwrap();
&self[from..=to]
}
}
#[cfg(test)]
mod test {
use super::TrimAsciiWhitespace;
#[test]
fn basic_trimming() {
assert_eq!(" A ".as_bytes().trim_ascii_whitespace(), "A".as_bytes());
assert_eq!(" AB ".as_bytes().trim_ascii_whitespace(), "AB".as_bytes());
assert_eq!("A ".as_bytes().trim_ascii_whitespace(), "A".as_bytes());
assert_eq!("AB ".as_bytes().trim_ascii_whitespace(), "AB".as_bytes());
assert_eq!(" A".as_bytes().trim_ascii_whitespace(), "A".as_bytes());
assert_eq!(" AB".as_bytes().trim_ascii_whitespace(), "AB".as_bytes());
assert_eq!(" A B ".as_bytes().trim_ascii_whitespace(), "A B".as_bytes());
assert_eq!("A B ".as_bytes().trim_ascii_whitespace(), "A B".as_bytes());
assert_eq!(" A B".as_bytes().trim_ascii_whitespace(), "A B".as_bytes());
assert_eq!(" ".as_bytes().trim_ascii_whitespace(), "".as_bytes());
assert_eq!(" ".as_bytes().trim_ascii_whitespace(), "".as_bytes());
}
}
|
#![recursion_limit = "10000"]
mod comparison;
mod constants;
mod macros;
mod nat_type;
use crate::comparison::{Cmp, Comparison, Max, Min};
use crate::constants::*;
use crate::macros::{add, digits, max, min, mul};
use crate::nat_type::{Add, Mul, Nat};
fn main() {
println!("--- multiplication and addition ---");
// Adding values happens at compile time.
println!("2+3+4 = {}", <add!(add!(N2, N3), N4)>::VALUE);
// We can nest computations as expected.
println!("3*10 + 7 = {}", <add!(mul!(N3, N10), N7)>::VALUE);
// We can construct multi-digit numbers using a macro, which uses
// multiplication and addition internally.
println!("732 = {}", <digits!([N7, N3, N2])>::VALUE);
// I couldn't solve this in my head; could you?
// The rust compiler can, in about 1 second.
println!(
"13*82 = {}",
<mul!(digits!([N1, N3]), digits!([N8, N2]))>::VALUE
);
// We can also compare numbers and get min/max.
println!("--- comparison ---");
println!(
"sign(7-3) = {}",
<<N7 as Cmp<N3>>::Result as Comparison>::VALUE
);
println!(
"sign(7-4) = {}",
<<N7 as Cmp<N4>>::Result as Comparison>::VALUE
);
println!(
"sign(4-7) = {}",
<<N4 as Cmp<N7>>::Result as Comparison>::VALUE
);
println!(
"sign(4-4) = {}",
<<N4 as Cmp<N4>>::Result as Comparison>::VALUE
);
println!("min(7,3) = {}", <min!(N7, N3)>::VALUE);
println!("max(7,3) = {}", <max!(N7, N3)>::VALUE);
println!("max(7,7) = {}", <max!(N7, N7)>::VALUE);
println!("min(7,7) = {}", <min!(N7, N7)>::VALUE);
}
|
use core::convert::TryInto;
use serde::{Deserialize, Serialize};
use crate::{
clock::ClockState,
mpu,
sdcard::{self, Settings, SD_BLOCK_SIZE},
SdCard,
};
#[derive(Serialize, Deserialize, Debug)]
pub struct LogEntry {
timestamp: LogTimestamp,
contents: LogContents,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum LogContents {
Measurement(mpu::Measurement),
Alarm(),
}
/// An internal type used to represent the time instant a log entry is logged.
#[derive(Serialize, Deserialize, Debug)]
struct LogTimestamp {
hour: u8,
minute: u8,
second: u8,
day: u8,
month: u8,
year: u8,
}
impl From<&ClockState> for LogTimestamp {
fn from(s: &ClockState) -> Self {
Self {
hour: s.hour,
minute: s.minute,
second: s.second,
day: s.day,
month: s.month,
year: s.year,
}
}
}
pub struct Logger {
buffer: [u8; SD_BLOCK_SIZE * 2],
current_idx: usize,
}
impl Logger {
pub fn new() -> Self {
Self {
buffer: [0u8; SD_BLOCK_SIZE * 2],
current_idx: 0,
}
}
/// Appends an new LogEntry containing the LogContents to the SD-card log
pub fn append(
&mut self,
clock: &ClockState,
contents: LogContents,
sd_card: &mut SdCard,
settings: &mut Settings,
) -> Result<(), sdcard::Error> {
// construct a new logger entry with timestamp (TODO)
let entry = LogEntry {
timestamp: clock.into(),
contents,
};
// get a mutable slice of the remaining content in the buffer array
let buff = &mut self.buffer[self.current_idx..];
// serialize the LogEntry to the buffer, note that this assumes that the entire LogEntry fits into the remaining buffer space
let serialized =
postcard::to_slice(&entry, buff).map_err(|e| sdcard::Error::PostcardError(e))?;
// increment next buffer index
self.current_idx += serialized.len();
// write the blocks while we have enough serialized data available
while self.current_idx >= SD_BLOCK_SIZE {
self.write_first_block(sd_card, settings)?;
}
Ok(())
}
/// Writes the first block in the buffer to the SD-card, shifts the buffer contents, and updates the `current_idx` pointer.
/// If the first block is not full (ie `current_idx < SD_BLOCK_SIZE`), the remaining bytes are zeroed before writing and the `current_idx` pointer is reset to zero.
// If `current_idx == 0`, the function does nothing.
fn write_first_block(
&mut self,
sd_card: &mut SdCard,
settings: &mut Settings,
) -> Result<(), sdcard::Error> {
// do nothing if we have no buffered bytes
if self.current_idx == 0 {
return Ok(());
}
// less than a complete block left, fill the remaining with zeroes (just for keeping the blocks nice and tidy when reading later)
if self.current_idx < SD_BLOCK_SIZE {
self.buffer[self.current_idx..].fill(0);
}
// extract an array of one block and write it to the SD-card
let data_to_write: &[u8; SD_BLOCK_SIZE] = &self.buffer[..SD_BLOCK_SIZE].try_into().unwrap();
sd_card.write_block(settings.logger_block, data_to_write)?;
// update the logger_block index
settings.logger_block += 1;
sd_card.store_settings(*settings).unwrap();
if self.current_idx < SD_BLOCK_SIZE {
// fill the beginning of the buffer with zeroes as well (now the entire buffer should be zeroed)
self.buffer[0..self.current_idx].fill(0);
self.current_idx = 0;
} else {
// adjust the index pointer
self.current_idx -= SD_BLOCK_SIZE;
// shift remaining data to the beginning of the buffer
for i in 0..self.current_idx {
self.buffer[i] = self.buffer[i + SD_BLOCK_SIZE];
}
}
defmt::debug!("Wrote block at address {}", &settings.logger_block - 1);
Ok(())
}
/// Forces the Logger to write the rest of the buffered serialized LogEntries to the SD-card.
/// Should be called when one wants to stop logging.
pub fn flush(
&mut self,
sd_card: &mut SdCard,
settings: &mut Settings,
) -> Result<(), sdcard::Error> {
// do nothing if we have no buffered bytes
if self.current_idx == 0 {
return Ok(());
}
// write blocks until there is no more data to write
while self.current_idx > 0 {
self.write_first_block(sd_card, settings)?;
}
Ok(())
}
}
|
use std::cmp::Ordering;
use std::fmt;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::{Path, PathBuf};
#[derive(Clone, Eq)]
pub struct Alias {
pub alias: String,
pub mime_type: String,
}
impl fmt::Debug for Alias {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "Alias {} {}", self.alias, self.mime_type)
}
}
impl PartialEq for Alias {
fn eq(&self, other: &Alias) -> bool {
self.alias == other.alias
}
}
impl Ord for Alias {
fn cmp(&self, other: &Alias) -> Ordering {
self.alias.cmp(&other.alias)
}
}
impl PartialOrd for Alias {
fn partial_cmp(&self, other: &Alias) -> Option<Ordering> {
Some(self.alias.cmp(&other.alias))
}
}
impl Alias {
pub fn new<S: Into<String>>(alias: S, mime_type: S) -> Alias {
Alias {
alias: alias.into(),
mime_type: mime_type.into(),
}
}
pub fn from_string(s: String) -> Option<Alias> {
let mut chunks = s.split_whitespace();
let alias = match chunks.next() {
Some(v) => v.to_string(),
None => return None,
};
let mime_type = match chunks.next() {
Some(v) => v.to_string(),
None => return None,
};
Some(Alias {
alias,
mime_type,
})
}
}
pub struct AliasesList {
aliases: Vec<Alias>,
}
impl AliasesList {
pub fn new() -> AliasesList {
AliasesList {
aliases: Vec::new(),
}
}
pub fn add_alias(&mut self, alias: Alias) {
self.aliases.push(alias);
}
pub fn add_aliases(&mut self, aliases: Vec<Alias>) {
self.aliases.extend(aliases);
}
pub fn sort(&mut self) {
self.aliases.sort_unstable();
}
pub fn unalias_mime_type(&self, mime_type: &str) -> Option<String> {
for a in self.aliases.iter() {
if a.alias == *mime_type {
return Some(a.mime_type.to_string());
}
}
None
}
}
pub fn read_aliases_from_file<P: AsRef<Path>>(file_name: P) -> Vec<Alias> {
let mut res = Vec::new();
let f = match File::open(file_name) {
Ok(v) => v,
Err(_) => return res,
};
let file = BufReader::new(&f);
for line in file.lines() {
let line = line.unwrap();
if line.is_empty() || line.starts_with('#') {
continue;
}
match Alias::from_string(line) {
Some(v) => res.push(v),
None => continue,
}
}
res
}
pub fn read_aliases_from_dir<P: AsRef<Path>>(dir: P) -> Vec<Alias> {
let mut alias_file = PathBuf::new();
alias_file.push(dir);
alias_file.push("aliases");
read_aliases_from_file(alias_file)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_alias() {
assert_eq!(
Alias::new("application/foo", "application/foo"),
Alias::new("application/foo", "application/x-foo")
);
}
#[test]
fn from_str() {
assert_eq!(
Alias::from_string("application/x-foo application/foo".to_string()).unwrap(),
Alias::new("application/x-foo", "application/foo")
);
}
}
|
use serenity::collector::CollectComponentInteraction;
use serenity::model::interactions::InteractionResponseType;
use serenity::{
client::Context,
framework::standard::{macros::command, CommandResult},
model::prelude::Message,
};
#[command("dropdowns")]
#[description = "dropdowns"]
async fn cmd_dropdowns(ctx: &Context, msg: &Message) -> CommandResult {
let m = msg
.channel_id
.send_message(&ctx, |m| {
m.content("dropdowns").components(|c| {
c.create_action_row(|r| {
r.create_select_menu(|m| {
m.custom_id("dropdown1")
.placeholder("pick something you lazy ass")
.options(|o| {
for (val, name) in
vec!["one", "two", "three", "four"].into_iter().enumerate()
{
o.create_option(|c| {
c.label(name).description((val + 1).to_string()).value(name)
});
}
o
})
})
})
})
})
.await?;
if let Some(i) = CollectComponentInteraction::new(&ctx)
.message_id(m.id)
.filter(|x| x.data.custom_id.as_str() == "dropdown1")
.await
{
match i.data.values.get(0) {
Some(val) => {
i.create_interaction_response(&ctx, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| d.content(format!("you picked {}", val)))
})
.await?
}
None => {
i.create_interaction_response(&ctx, |r| {
r.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|d| d.content("blame discord™"))
})
.await?
}
}
}
Ok(())
}
|
use std::error::Error;
use std::fmt::{Debug, Display};
use std::path::PathBuf;
use std::time::Duration;
use getopts::{Fail, Matches, Options};
pub const MAX_INPUT_CPLX_FLAG: &str = "max-cplx";
pub const INPUT_FILE_FLAG: &str = "input-file";
pub const IN_CORPUS_FLAG: &str = "in-corpus";
pub const NO_IN_CORPUS_FLAG: &str = "no-in-corpus";
pub const OUT_CORPUS_FLAG: &str = "out-corpus";
pub const NO_OUT_CORPUS_FLAG: &str = "no-out-corpus";
pub const ARTIFACTS_FLAG: &str = "artifacts";
pub const NO_ARTIFACTS_FLAG: &str = "no-artifacts";
pub const STATS_FLAG: &str = "stats";
pub const NO_STATS_FLAG: &str = "no-stats";
pub const COMMAND_FLAG: &str = "command";
pub const MAX_DURATION_FLAG: &str = "stop-after-duration";
pub const MAX_ITERATIONS_FLAG: &str = "stop-after-iterations";
pub const STOP_AFTER_FIRST_FAILURE_FLAG: &str = "stop-after-first-failure";
pub const DETECT_INFINITE_LOOP_FLAG: &str = "detect-infinite-loop";
pub const COMMAND_FUZZ: &str = "fuzz";
pub const COMMAND_MINIFY_INPUT: &str = "minify";
pub const COMMAND_READ: &str = "read";
#[derive(Clone)]
pub struct DefaultArguments {
pub max_input_cplx: f64,
}
impl Default for DefaultArguments {
#[no_coverage]
fn default() -> Self {
Self { max_input_cplx: 4096.0 }
}
}
/// The task that the fuzzer is asked to perform.
#[derive(Debug, Clone)]
pub enum FuzzerCommand {
Fuzz,
Read { input_file: PathBuf },
MinifyInput { input_file: PathBuf },
}
impl Default for FuzzerCommand {
fn default() -> Self {
Self::Fuzz
}
}
/// Various arguments given to the fuzzer, typically provided by the `cargo fuzzcheck` command line tool.
#[derive(Debug, Clone)]
pub struct Arguments {
pub command: FuzzerCommand,
pub max_input_cplx: f64,
pub detect_infinite_loop: bool,
pub maximum_duration: Duration,
pub maximum_iterations: usize,
pub stop_after_first_failure: bool,
pub corpus_in: Option<PathBuf>,
pub corpus_out: Option<PathBuf>,
pub artifacts_folder: Option<PathBuf>,
pub stats_folder: Option<PathBuf>,
}
impl Arguments {
pub fn for_internal_documentation_test() -> Self {
Self {
command: FuzzerCommand::Fuzz,
max_input_cplx: 256.,
detect_infinite_loop: false,
maximum_duration: Duration::MAX,
maximum_iterations: usize::MAX,
stop_after_first_failure: true,
corpus_in: None,
corpus_out: None,
artifacts_folder: None,
stats_folder: None,
}
}
}
/// The command line argument parser used by the fuzz target and `cargo fuzzcheck`
#[must_use]
#[no_coverage]
pub fn options_parser() -> Options {
let mut options = Options::new();
let defaults = DefaultArguments::default();
options.optopt(
"",
COMMAND_FLAG,
&format!(
"the action to be performed (default: fuzz). --{} is required when using `{}`",
INPUT_FILE_FLAG, COMMAND_MINIFY_INPUT
),
&format!("<{} | {}>", COMMAND_FUZZ, COMMAND_MINIFY_INPUT),
);
options.optopt(
"",
MAX_DURATION_FLAG,
"maximum duration of the fuzz test, in seconds",
"N",
);
options.optopt("", MAX_ITERATIONS_FLAG, "maximum number of iterations", "N");
options.optflag(
"",
DETECT_INFINITE_LOOP_FLAG,
"fail on tests running for more than one second",
);
options.optflag(
"",
STOP_AFTER_FIRST_FAILURE_FLAG,
"stop the fuzzer after the first test failure is found",
);
options.optopt("", IN_CORPUS_FLAG, "folder for the input corpus", "PATH");
options.optflag(
"",
NO_IN_CORPUS_FLAG,
format!(
"do not use an input corpus, overrides --{in_corpus}",
in_corpus = IN_CORPUS_FLAG
)
.as_str(),
);
options.optopt("", OUT_CORPUS_FLAG, "folder for the output corpus", "PATH");
options.optflag(
"",
NO_OUT_CORPUS_FLAG,
format!(
"do not use an output corpus, overrides --{out_corpus}",
out_corpus = OUT_CORPUS_FLAG
)
.as_str(),
);
options.optopt("", ARTIFACTS_FLAG, "folder where the artifacts will be written", "PATH");
options.optflag(
"",
NO_ARTIFACTS_FLAG,
format!(
"do not save artifacts, overrides --{artifacts}",
artifacts = ARTIFACTS_FLAG
)
.as_str(),
);
options.optopt("", STATS_FLAG, "folder where the statistics will be written", "PATH");
options.optflag(
"",
NO_STATS_FLAG,
format!("do not save statistics, overrides --{stats}", stats = STATS_FLAG).as_str(),
);
options.optopt("", INPUT_FILE_FLAG, "file containing a test case", "PATH");
options.optopt(
"",
MAX_INPUT_CPLX_FLAG,
format!(
"maximum allowed complexity of inputs (default: {default})",
default = defaults.max_input_cplx
)
.as_str(),
"N",
);
options.optflag("h", "help", "print this help menu");
options
}
impl Arguments {
/// Create an `Arguments` from the parsed result of [`options_parser()`].
///
/// ### Arguments
/// * `for_cargo_fuzzcheck` : true if this method is called within `cargo fuzzcheck`, false otherwise.
/// This is because `cargo fuzzcheck` also needs a fuzz target as argument, while the fuzzed binary
/// does not.
#[no_coverage]
pub fn from_matches(matches: &Matches, for_cargo_fuzzcheck: bool) -> Result<Self, ArgumentsError> {
if matches.opt_present("help") || matches.free.contains(&"help".to_owned()) {
return Err(ArgumentsError::WantsHelp);
}
if for_cargo_fuzzcheck && matches.free.is_empty() {
return Err(ArgumentsError::Validation(
"A fuzz target must be given to cargo fuzzcheck.".to_string(),
));
}
let command = matches.opt_str(COMMAND_FLAG).unwrap_or_else(
#[no_coverage]
|| COMMAND_FUZZ.to_owned(),
);
let command = command.as_str();
if !matches!(command, COMMAND_FUZZ | COMMAND_READ | COMMAND_MINIFY_INPUT) {
return Err(ArgumentsError::Validation(format!(
r#"The command {c} is not supported. It can either be ‘{fuzz}’ or ‘{minify}’."#,
c = &matches.free[0],
fuzz = COMMAND_FUZZ,
minify = COMMAND_MINIFY_INPUT,
)));
}
let max_input_cplx: Option<f64> = matches
.opt_str(MAX_INPUT_CPLX_FLAG)
.and_then(
#[no_coverage]
|x| x.parse::<usize>().ok(),
)
.map(
#[no_coverage]
|x| x as f64,
);
let detect_infinite_loop = matches.opt_present(DETECT_INFINITE_LOOP_FLAG);
let corpus_in: Option<PathBuf> = matches.opt_str(IN_CORPUS_FLAG).and_then(
#[no_coverage]
|x| x.parse::<PathBuf>().ok(),
);
let no_in_corpus = if matches.opt_present(NO_IN_CORPUS_FLAG) {
Some(())
} else {
None
};
let corpus_out: Option<PathBuf> = matches.opt_str(OUT_CORPUS_FLAG).and_then(
#[no_coverage]
|x| x.parse::<PathBuf>().ok(),
);
let no_out_corpus = if matches.opt_present(NO_OUT_CORPUS_FLAG) {
Some(())
} else {
None
};
let artifacts_folder: Option<PathBuf> = matches.opt_str(ARTIFACTS_FLAG).and_then(
#[no_coverage]
|x| x.parse::<PathBuf>().ok(),
);
let no_artifacts = if matches.opt_present(NO_ARTIFACTS_FLAG) {
Some(())
} else {
None
};
let stats_folder: Option<PathBuf> = matches.opt_str(STATS_FLAG).and_then(
#[no_coverage]
|x| x.parse::<PathBuf>().ok(),
);
let no_stats = if matches.opt_present(NO_STATS_FLAG) {
Some(())
} else {
None
};
let input_file: Option<PathBuf> = matches.opt_str(INPUT_FILE_FLAG).and_then(
#[no_coverage]
|x| x.parse::<PathBuf>().ok(),
);
// verify all the right options are here
let command = match command {
COMMAND_FUZZ => FuzzerCommand::Fuzz,
COMMAND_READ => {
let input_file = input_file.unwrap_or_else(
#[no_coverage]
|| {
panic!(
"An input file must be provided when reading a test case. Use --{}",
INPUT_FILE_FLAG
)
},
);
FuzzerCommand::Read { input_file }
}
COMMAND_MINIFY_INPUT => {
let input_file = input_file.unwrap_or_else(
#[no_coverage]
|| {
panic!(
"An input file must be provided when minifying a test case. Use --{}",
INPUT_FILE_FLAG
)
},
);
FuzzerCommand::MinifyInput { input_file }
}
_ => unreachable!(),
};
let maximum_duration = {
let seconds = matches
.opt_str(MAX_DURATION_FLAG)
.and_then(
#[no_coverage]
|x| x.parse::<u64>().ok(),
)
.unwrap_or(u64::MAX);
Duration::new(seconds, 0)
};
let maximum_iterations = matches
.opt_str(MAX_ITERATIONS_FLAG)
.and_then(
#[no_coverage]
|x| x.parse::<usize>().ok(),
)
.unwrap_or(usize::MAX);
let stop_after_first_failure = matches.opt_present(STOP_AFTER_FIRST_FAILURE_FLAG);
let defaults = DefaultArguments::default();
let max_input_cplx: f64 = max_input_cplx.unwrap_or(defaults.max_input_cplx as f64);
let corpus_in: Option<PathBuf> = if no_in_corpus.is_some() { None } else { corpus_in };
let corpus_out: Option<PathBuf> = if no_out_corpus.is_some() { None } else { corpus_out };
let artifacts_folder: Option<PathBuf> = if no_artifacts.is_some() { None } else { artifacts_folder };
let stats_folder: Option<PathBuf> = if no_stats.is_some() { None } else { stats_folder };
Ok(Arguments {
command,
detect_infinite_loop,
maximum_duration,
maximum_iterations,
stop_after_first_failure,
max_input_cplx,
corpus_in,
corpus_out,
artifacts_folder,
stats_folder,
})
}
}
/// The “help” output of cargo-fuzzcheck
#[no_coverage]
pub fn help(parser: &Options) -> String {
let mut help = r##"
USAGE:
cargo-fuzzcheck <FUZZ_TEST> [OPTIONS]
FUZZ_TEST:
The fuzz test is the exact path to the #[test] function that launches
fuzzcheck. For example, it can be "parser::tests::fuzz_test_1" if you have
the following snippet located at src/parser/mod.rs:
#[cfg(test)]
mod tests {{
#[test]
fn fuzz_test_1() {{
fuzzcheck::fuzz_test(some_function_to_test)
.default_options()
.launch();
}}
}}
"##
.to_owned();
help += parser.usage("").as_str();
help += format!(
r#"
EXAMPLES:
cargo-fuzzcheck tests::fuzz_test1
Launch the fuzzer on "tests::fuzz_test1", located in the crate’s library, with default options.
cargo-fuzzcheck tests::fuzz_bin --bin my_program
Launch the fuzzer on "tests::fuzz_bin", located in the "my_program" binary target, with default options.
cargo-fuzzcheck fuzz_test2 --test my_integration_test
Launch the fuzzer on "fuzz_test2", located in the "my_integration_test" test target, with default options.
cargo-fuzzcheck tests::fuzzit --{max_cplx} 4000 --{out_corpus} fuzz_results/out/
Fuzz "tests::fuzzit", generating inputs of complexity no greater than 4000,
and write the output corpus (i.e. the folder of most interesting test cases)
to fuzz_results/out/.
cargo-fuzzcheck tests::fuzz --command {minify} --{input_file} "artifacts/crash.json"
Using the fuzz test located at "tests::fuzz_test", minify the test input defined
in the file "artifacts/crash.json". It will put minified inputs in the folder
artifacts/crash.minified/ and name them {{complexity}}-{{hash}}.json.
For example, artifacts/crash.minified/4213--8cd7777109b57b8c.json
is a minified input of complexity 42.13.
"#,
minify = COMMAND_MINIFY_INPUT,
input_file = INPUT_FILE_FLAG,
max_cplx = MAX_INPUT_CPLX_FLAG,
out_corpus = OUT_CORPUS_FLAG,
)
.as_str();
help
}
#[derive(Clone)]
pub enum ArgumentsError {
NoArgumentsGiven(String),
Parsing(Fail),
Validation(String),
WantsHelp,
}
impl Debug for ArgumentsError {
#[no_coverage]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<Self as Display>::fmt(self, f)
}
}
impl Display for ArgumentsError {
#[no_coverage]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ArgumentsError::NoArgumentsGiven(help) => {
write!(f, "No arguments were given.\nHelp:\n{}", help)
}
ArgumentsError::Parsing(e) => {
write!(
f,
"{}
To display the help, run:
cargo fuzzcheck --help",
e
)
}
ArgumentsError::Validation(e) => {
write!(
f,
"{}
To display the help, run:
cargo fuzzcheck --help",
e
)
}
ArgumentsError::WantsHelp => {
write!(f, "Help requested.")
}
}
}
}
impl Error for ArgumentsError {}
impl From<Fail> for ArgumentsError {
#[no_coverage]
fn from(e: Fail) -> Self {
Self::Parsing(e)
}
}
|
#[doc = "Reader of register RNG_HTCR"]
pub type R = crate::R<u32, super::RNG_HTCR>;
#[doc = "Writer for register RNG_HTCR"]
pub type W = crate::W<u32, super::RNG_HTCR>;
#[doc = "Register RNG_HTCR `reset()`'s with value 0x000c_aa74"]
impl crate::ResetValue for super::RNG_HTCR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x000c_aa74
}
}
#[doc = "Reader of field `HTCFG`"]
pub type HTCFG_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `HTCFG`"]
pub struct HTCFG_W<'a> {
w: &'a mut W,
}
impl<'a> HTCFG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - health test configuration"]
#[inline(always)]
pub fn htcfg(&self) -> HTCFG_R {
HTCFG_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - health test configuration"]
#[inline(always)]
pub fn htcfg(&mut self) -> HTCFG_W {
HTCFG_W { w: self }
}
}
|
use sdl_main::sdl_main;
mod macros;
mod shader;
mod common;
mod camera;
mod sdl_main;
mod draw_text;
mod landscape;
mod player_shape;
mod model;
mod mesh;
mod bullet;
mod enemy_ship;
mod sound;
mod start_screen;
mod explosion;
fn main() {
sdl_main().unwrap();
}
|
use spin::RwLock;
pub static FRAME_BUFFER: RwLock<Option<FramebufferInfo>> = RwLock::new(None);
/// FramebufferInfo information
#[repr(C)]
#[derive(Debug)]
pub struct FramebufferInfo {
/// visible width
pub xres: u32,
/// visible height
pub yres: u32,
/// virtual width
pub xres_virtual: u32,
/// virtual height
pub yres_virtual: u32,
/// virtual offset x
pub xoffset: u32,
/// virtual offset y
pub yoffset: u32,
/// bits per pixel
pub depth: ColorDepth,
/// color encoding format of RGBA
pub format: ColorFormat,
/// phsyical address
pub paddr: usize,
/// virtual address
pub vaddr: usize,
/// screen buffer size
pub screen_size: usize,
}
#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub enum ColorDepth {
ColorDepth8 = 8,
ColorDepth16 = 16,
ColorDepth24 = 24,
ColorDepth32 = 32,
}
impl ColorDepth {
pub fn try_from(depth: u32) -> Result<Self, &'static str> {
match depth {
8 => Ok(Self::ColorDepth8),
16 => Ok(Self::ColorDepth16),
32 => Ok(Self::ColorDepth32),
24 => Ok(Self::ColorDepth24),
_ => Err("unsupported color depth"),
}
}
}
#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub enum ColorFormat {
RGB332,
RGB565,
RGBA8888, // QEMU and low version RPi use RGBA
BGRA8888, // RPi3 B+ uses BGRA
VgaPalette,
}
|
use std::io;
fn main() {
loop {
let mut input = String::new();
println!("\nType a \"good\" value:");
io::stdin().read_line(&mut input)
.expect("Can't read your input");
let _value = match input.trim().parse::<i32>() {
Ok(v) => match v {
0..=10 => {
println!("{:?} is a correct value!", v);
},
_ => {
println!("Not in 0 to 10 included range!");
continue;
}
},
Err(e) => {
println!("Not a 32bits integer! Error -> {:?}", e);
continue;
}
};
println!("Got a good unsigned integer within expected range, exiting happily!");
return;
}
}
|
use tokio::sync::oneshot::Sender;
use crate::{
actor::{Actor, AsyncContext},
context::Context,
handler::{Handler, Message, MessageResponse},
};
/// Converter trait, packs message into a suitable envelope.
pub trait ToEnvelope<A, M: Message>
where
A: Actor + Handler<M>,
A::Context: ToEnvelope<A, M>,
{
/// Pack message into suitable envelope
fn pack(msg: M, tx: Option<Sender<M::Result>>) -> Envelope<A>;
}
pub trait EnvelopeProxy<A: Actor> {
/// handle message within new actor and context
fn handle(&mut self, act: &mut A, ctx: &mut A::Context);
}
impl<A, M> ToEnvelope<A, M> for Context<A>
where
A: Actor<Context = Context<A>> + Handler<M>,
M: Message + Send + 'static,
M::Result: Send,
{
fn pack(msg: M, tx: Option<Sender<M::Result>>) -> Envelope<A> {
Envelope::new(msg, tx)
}
}
pub struct Envelope<A: Actor>(Box<dyn EnvelopeProxy<A> + Send>);
impl<A: Actor> Envelope<A> {
pub fn new<M>(msg: M, tx: Option<Sender<M::Result>>) -> Self
where
A: Handler<M>,
A::Context: AsyncContext<A>,
M: Message + Send + 'static,
M::Result: Send,
{
Envelope(Box::new(SyncEnvelopeProxy { tx, msg: Some(msg) }))
}
pub fn with_proxy(proxy: Box<dyn EnvelopeProxy<A> + Send>) -> Self {
Envelope(proxy)
}
}
impl<A: Actor> EnvelopeProxy<A> for Envelope<A> {
fn handle(&mut self, act: &mut A, ctx: &mut <A as Actor>::Context) {
self.0.handle(act, ctx)
}
}
pub struct SyncEnvelopeProxy<M>
where
M: Message + Send,
M::Result: Send,
{
msg: Option<M>,
tx: Option<Sender<M::Result>>,
}
impl<A, M> EnvelopeProxy<A> for SyncEnvelopeProxy<M>
where
M: Message + Send + 'static,
M::Result: Send,
A: Actor + Handler<M>,
A::Context: AsyncContext<A>,
{
fn handle(&mut self, act: &mut A, ctx: &mut <A as Actor>::Context) {
let tx = self.tx.take();
if tx.is_some() && tx.as_ref().unwrap().is_closed() {
return;
}
if let Some(msg) = self.msg.take() {
let fut = <A as Handler<M>>::handle(act, msg, ctx);
fut.handle(ctx, tx)
}
}
}
|
use std::{convert::TryFrom, path::PathBuf};
use config::{Config, File};
use serde::Deserialize;
#[derive(Deserialize, Clone)]
pub struct Credentials {
pub username: String,
pub password: Option<String>,
pub device_id: String,
pub device_name: String,
pub access_token: Option<String>,
}
#[derive(Deserialize, Clone)]
pub struct HomeServer {
pub url: String,
}
#[derive(Deserialize, Clone)]
pub struct Sync {
pub interval: u64,
}
#[derive(Deserialize, Clone)]
pub struct BotConfig {
pub credentials: Credentials,
pub server: HomeServer,
pub sync: Sync,
pub storage: Storage,
}
#[derive(Deserialize, Clone)]
pub struct Storage {
pub path: String,
}
impl TryFrom<PathBuf> for BotConfig {
type Error = anyhow::Error;
fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
let mut s = Config::new();
// Start off by merging in the "default" configuration file
s.merge(File::from(path))?;
s.try_into().map(Ok)?
}
}
|
use crate::enums;
use crate::core;
use std::time;
use std::ptr::null_mut;
use winapi::um::processthreadsapi::*;
use winapi::um::tlhelp32::*;
use winapi::um::handleapi::*;
use winapi::um::winbase::*;
use winapi::ctypes::c_void;
use ntapi::ntexapi;
use winapi::shared::minwindef::MAX_PATH;
pub struct Process {
handle: core::KernelHandle,
}
impl Process {
pub fn current() -> Self {
Self {
handle: core::KernelHandle::new( unsafe { GetCurrentProcess() })
}
}
pub fn open(access_mask: enums::ProcessAccessMask, pid: u32) -> Result<Self, core::Win32Error> {
let handle = unsafe { OpenProcess(access_mask as u32, 0, pid) };
if handle != null_mut() {
Ok(Process {
handle: core::KernelHandle::new(handle)
})
}
else {
Err(core::Win32Error::new())
}
}
pub fn id(&self) -> u32 {
unsafe { GetProcessId(self.handle.get()) }
}
pub fn full_path(&self) -> Result<String, core::Win32Error> {
unsafe {
let mut path = Vec::new();
path.resize(MAX_PATH, 0u16);
let mut size = MAX_PATH as u32;
if QueryFullProcessImageNameW(self.handle.get(), 0, path.as_mut_ptr(), &mut size) == 0 {
Err(core::Win32Error::new())
}
else {
Ok(String::from_utf16(&path[..size as usize]).unwrap())
}
}
}
}
#[derive(Debug, Clone)]
pub struct ProcessInfo {
pub id: u32,
pub parent_id: u32,
pub thread_count: u32,
pub name: String,
}
#[derive(Debug, Clone)]
pub struct ThreadInfoEx {
}
#[derive(Debug, Clone)]
pub struct ProcessInfoEx {
pub id: u32,
pub parent_id: u32,
pub thread_count: u32,
pub name: String,
pub handle_count: u32,
pub priority: i32,
pub create_time: i64,
pub user_time: std::time::Duration,
pub kernel_time: std::time::Duration,
pub session_id: u32,
pub virtual_size: usize,
pub peak_virtual_size: usize,
pub working_set: usize,
pub peak_working_set: usize,
pub page_fault_count: u32,
pub commit_size: usize,
pub peak_commit_size: usize,
pub paged_pool: usize,
pub non_paged_pool: usize,
pub peak_paged_pool: usize,
pub peak_non_paged_pool: usize,
pub threads: Vec<ThreadInfoEx>,
}
impl ProcessInfoEx {
unsafe fn from_native(p: ntexapi::PSYSTEM_PROCESS_INFORMATION, name: String, include_threads: bool) -> Self {
let pp = &*p;
ProcessInfoEx {
id: pp.UniqueProcessId as u32,
parent_id: pp.InheritedFromUniqueProcessId as u32,
thread_count: pp.NumberOfThreads,
name: if pp.UniqueProcessId as u32 == 0 { "(Idle)".to_string() } else { String::from_utf16(std::slice::from_raw_parts(pp.ImageName.Buffer, (pp.ImageName.Length / 2) as usize)).unwrap() },
create_time: *pp.CreateTime.QuadPart(),
user_time: time::Duration::from_nanos((*pp.UserTime.QuadPart() * 100) as u64),
kernel_time: time::Duration::from_nanos((*pp.KernelTime.QuadPart() * 100) as u64),
handle_count: pp.HandleCount,
priority: pp.BasePriority,
session_id: pp.SessionId,
working_set: pp.WorkingSetSize,
peak_working_set: pp.PeakWorkingSetSize,
commit_size: pp.PagefileUsage,
peak_commit_size: pp.PeakPagefileUsage,
paged_pool: pp.QuotaPagedPoolUsage,
non_paged_pool: pp.QuotaNonPagedPoolUsage,
peak_paged_pool: pp.QuotaPeakPagedPoolUsage,
peak_non_paged_pool: pp.QuotaPeakNonPagedPoolUsage,
virtual_size: pp.VirtualSize,
peak_virtual_size: pp.PeakVirtualSize,
page_fault_count: pp.PageFaultCount,
threads: if include_threads { enum_threads(pp) } else { Vec::new() },
}
}
}
pub fn enum_processes_native_pid(pid: u32, include_threads: bool) -> Option<ProcessInfoEx> {
let mut result = enum_processes_native_generic(include_threads, pid, "").unwrap();
if result.is_empty() {
None
}
else {
Some(result.pop().unwrap())
}
}
pub fn enum_processes_native_name(name: &str, include_threads: bool) -> Result<Vec<ProcessInfoEx>, core::Win32Error> {
enum_processes_native_generic(include_threads, std::u32::MAX, &name)
}
pub fn enum_processes_native(include_threads: bool) -> Result<Vec<ProcessInfoEx>, core::Win32Error> {
enum_processes_native_generic(include_threads, std::u32::MAX, "")
}
fn enum_processes_native_generic(include_threads: bool, pid: u32, pname: &str) -> Result<Vec<ProcessInfoEx>, core::Win32Error> {
unsafe {
let mut buffer = Vec::new();
let size: u32 = 1 << 22;
buffer.resize(size as usize, 0u8);
let status = ntexapi::NtQuerySystemInformation(ntexapi::SystemExtendedProcessInformation, buffer.as_mut_ptr() as *mut c_void, size, null_mut());
if status != 0 {
return Err(core::Win32Error::from_ntstatus(status));
}
let mut p = buffer.as_mut_ptr() as ntexapi::PSYSTEM_PROCESS_INFORMATION;
let mut processes = Vec::with_capacity(512);
loop {
let pp = &*p;
let name = if pp.UniqueProcessId as u32 == 0 { "(Idle)".to_string() } else { String::from_utf16(std::slice::from_raw_parts(pp.ImageName.Buffer, (pp.ImageName.Length / 2) as usize)).unwrap() };
if (pid == std::u32::MAX || pid == pp.UniqueProcessId as u32) && (pname.len() == 0 || pname == name) {
let pi = ProcessInfoEx::from_native(p, name, include_threads);
processes.push(pi);
}
if pp.NextEntryOffset == 0 {
break;
}
p = (p as *mut u8).offset((*p).NextEntryOffset as isize) as ntexapi::PSYSTEM_PROCESS_INFORMATION;
}
processes.shrink_to_fit();
Ok(processes)
}
}
fn enum_threads(pi: &ntexapi::SYSTEM_PROCESS_INFORMATION) -> Vec<ThreadInfoEx> {
todo!();
}
pub fn enum_processes_toolhelp() -> Result<Vec<ProcessInfo>, core::Win32Error> {
unsafe {
let handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
// create a KernelHandle that is automatically closed
let _khandle = core::KernelHandle::new(handle);
if handle == INVALID_HANDLE_VALUE {
return Err(core::Win32Error::new())
}
let mut processes = Vec::with_capacity(512);
let mut pe = PROCESSENTRY32W::default();
pe.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
if Process32FirstW(handle, &mut pe) != 0 {
loop {
let pi = ProcessInfo {
id: pe.th32ProcessID,
parent_id: pe.th32ParentProcessID,
thread_count: pe.cntThreads,
name: String::from_utf16(&pe.szExeFile[..lstrlenW(pe.szExeFile.as_ptr()) as usize]).unwrap()
};
processes.push(pi);
if Process32NextW(handle, &mut pe) == 0 {
break;
}
}
}
else {
return Err(core::Win32Error::new());
}
processes.shrink_to_fit();
Ok(processes)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn locate_process(name: &str) -> u32 {
for pi in &enum_processes_toolhelp().unwrap() {
if pi.name == name && pi.thread_count > 0 {
return pi.id;
}
}
0
}
#[test]
fn open_process() {
let explorer = locate_process("explorer.exe");
assert!(explorer != 0);
let process = Process::open(enums::ProcessAccessMask::QueryLimitedInformation, explorer).unwrap();
assert_eq!(process.id(), explorer);
let path = process.full_path().unwrap();
assert!(path.eq_ignore_ascii_case("c:\\Windows\\explorer.exe"));
}
#[test]
fn enum_processes1() {
let processes = enum_processes_toolhelp().unwrap();
for pi in &processes {
println!("{:?}", pi);
}
}
#[test]
fn enum_processes2() {
let processes = enum_processes_native(false).unwrap();
for pi in &processes {
println!("{:?}", pi);
}
}
#[test]
fn current_process() {
let process = Process::current();
unsafe {
assert_eq!(process.id(), GetCurrentProcessId());
}
println!("{}", process.full_path().unwrap());
}
}
|
use node::Node;
use std::collections::BTreeMap;
use std::net::{IpAddr,Ipv4Addr};
use std::time::Duration;
use std::u64;
use std::u32;
// Trait methods cannot use 'Self'; &self or &mut self is OK
// https://doc.rust-lang.org/error-index.html#E0038
pub trait LoadBalancing {
//fn new() -> Self ;
fn select_node(&mut self,&BTreeMap<IpAddr,Node>) -> IpAddr;
}
#[derive(Clone)]
pub struct RoundRobin {
pub index: usize
}
impl LoadBalancing for RoundRobin {
fn select_node(&mut self,map: &BTreeMap<IpAddr,Node>) -> IpAddr{
self.index = self.index + 1;
if self.index >= map.len(){
self.index = 0;
}
map.iter().nth(self.index).unwrap().0.clone()
}
}
#[derive(Clone)]
pub struct LatencyAware;
impl LoadBalancing for LatencyAware {
fn select_node(&mut self,map: &BTreeMap<IpAddr,Node>) -> IpAddr{
let mut latency = Duration::new(u64::max_value()/2, u32::max_value()/2);
let mut node_ip = IpAddr::V4(Ipv4Addr::new(0,0,0,0));
for (ip,node) in map{
if node.get_latency() < latency{
latency = node.get_latency();
node_ip = ip.clone();
}
}
node_ip
}
}
pub enum BalancerType{
RoundRobin,
LatencyAware
} |
use spin::RwLock;
use rcore_fs::dev::*;
pub struct MemBuf(RwLock<&'static mut [u8]>); //一块用于模拟磁盘的内存
impl MemBuf {
// 初始化参数为磁盘的头尾虚拟地址
pub unsafe fn new(begin: usize, end: usize) -> Self {
use core::slice;
MemBuf(
// 我们使用读写锁
// 可以有多个线程同时获取 & 读
// 但是一旦有线程获取 &mut 写,那么其他所有线程都将被阻塞
RwLock::new(
slice::from_raw_parts_mut(begin as *mut u8, end - begin)
)
)
}
}
// 作为文件系统所用的设备驱动,只需实现下面三个接口
// 而在设备实际上是内存的情况下,实现变的极其简单
impl Device for MemBuf {
fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize> {
let slice = self.0.read();
let len = buf.len().min(slice.len() - offset);
buf[..len].copy_from_slice(&slice[offset..offset + len]);
Ok(len)
}
fn write_at(&self, offset: usize, buf: &[u8]) -> Result<usize> {
let mut slice = self.0.write();
let len = buf.len().min(slice.len() - offset);
slice[offset..offset + len].copy_from_slice(&buf[..len]);
Ok(len)
}
fn sync(&self) -> Result<()> {
Ok(())
}
} |
use crate::auth;
use crate::handlers::types::*;
use crate::Pool;
use actix_web::{web, Error, HttpResponse};
use actix_web_httpauth::extractors::bearer::BearerAuth;
use crate::controllers::task_controller::*;
//http calls
pub async fn create_task(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<AddUserToFolderPath>,
item: web::Json<AddTask>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
create_task_db(db, auth.token().to_string(), space_name, item)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(false, "Error creating task".to_string()))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn update_task(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<AddUserToFolderPath>,
item: web::Json<UpdateTask>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
update_task_db(db, auth.token().to_string(), space_name, item)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(false, "Error updating task".to_string()))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn delete_task(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<AddUserToFolderPath>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(
web::block(move || delete_task_db(db, auth.token().to_string(), space_name))
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok()
.json(Response::new(false, "Error deleting task".to_string()))
})?,
)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn update_task_status(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<AddUserToFolderPath>,
item: web::Json<UpdateTaskStatus>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
update_task_status_db(db, auth.token().to_string(), space_name, item)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(false, "Error updating task".to_string()))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
pub async fn get_task_in_project(
db: web::Data<Pool>,
auth: BearerAuth,
space_name: web::Path<ChannelPathInfo>,
) -> Result<HttpResponse, Error> {
match auth::validate_token(&auth.token().to_string()) {
Ok(res) => {
if res == true {
Ok(web::block(move || {
get_task_in_project_db(db, auth.token().to_string(), space_name)
})
.await
.map(|response| HttpResponse::Ok().json(response))
.map_err(|_| {
HttpResponse::Ok().json(Response::new(false, "Error getting task".to_string()))
})?)
} else {
Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string())))
}
}
Err(_) => Ok(HttpResponse::Ok().json(ResponseError::new(false, "jwt error".to_string()))),
}
}
|
use std::fmt;
struct Encoding {
data: [i64; 24],
len: usize,
val: i64,
}
struct EncodingGenerator {
count: i64,
}
impl Iterator for EncodingGenerator {
type Item = Encoding;
fn next(&mut self) -> Option<Encoding> {
let mut enc = Encoding{data: [0i64; 24], len: 0, val: 0};
if self.count == 0 {
enc.len = 1;
enc.val = 1;
self.count += 1;
return Some(enc);
}
let mut c = self.count;
while c > 0 {
enc.data[enc.len] = c % 3;
enc.len += 1;
enc.val = match c % 3 {
0 => enc.val + (enc.len as i64),
1 => enc.val - (enc.len as i64),
2 => enc.val * (enc.len as i64),
_ => enc.val,
};
c /= 3;
}
self.count += 1;
Some(enc)
}
}
impl fmt::Display for Encoding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for x in self.data.iter().take(self.len) { write!(f, "{}", x).unwrap(); };
Ok(())
}
}
fn find_enc(x: i64) -> Box<Iterator<Item=Encoding>> {
let it = EncodingGenerator{count: 0}
.filter(move |e| e.val == x)
.scan(0, |len, e| {
if *len == 0 || e.len == *len {
*len = e.len;
Some(e)
} else {
None
}});
Box::new(it)
}
fn main() {
for x in 0..501 {
println!("Encodings for: {}", x);
for enc in find_enc(x) {
println!(" {}", enc);
}
}
}
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_expression::TableSchemaRef;
use crate::plan::datasource::datasource_info::DataSourceInfo;
use crate::plan::PartStatistics;
use crate::plan::Partitions;
use crate::plan::PushDownInfo;
use crate::table_args::TableArgs;
// TODO: Delete the scan plan field, but it depends on plan_parser:L394
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct DataSourcePlan {
// TODO catalog id is better
pub catalog: String,
pub source_info: DataSourceInfo,
pub output_schema: TableSchemaRef,
pub parts: Partitions,
pub statistics: PartStatistics,
pub description: String,
pub tbl_args: Option<TableArgs>,
pub push_downs: Option<PushDownInfo>,
pub query_internal_columns: bool,
}
impl DataSourcePlan {
#[inline]
pub fn schema(&self) -> TableSchemaRef {
self.output_schema.clone()
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IPdfRendererNative(pub ::windows::core::IUnknown);
impl IPdfRendererNative {
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common", feature = "Win32_Graphics_Dxgi"))]
pub unsafe fn RenderPageToSurface<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>, Param1: ::windows::core::IntoParam<'a, super::super::super::Graphics::Dxgi::IDXGISurface>, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::POINT>>(&self, pdfpage: Param0, psurface: Param1, offset: Param2, prenderparams: *const PDF_RENDER_PARAMS) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pdfpage.into_param().abi(), psurface.into_param().abi(), offset.into_param().abi(), ::core::mem::transmute(prenderparams)).ok()
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D", feature = "Win32_Graphics_Direct2D_Common"))]
pub unsafe fn RenderPageToDeviceContext<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>, Param1: ::windows::core::IntoParam<'a, super::super::super::Graphics::Direct2D::ID2D1DeviceContext>>(&self, pdfpage: Param0, pd2ddevicecontext: Param1, prenderparams: *const PDF_RENDER_PARAMS) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pdfpage.into_param().abi(), pd2ddevicecontext.into_param().abi(), ::core::mem::transmute(prenderparams)).ok()
}
}
unsafe impl ::windows::core::Interface for IPdfRendererNative {
type Vtable = IPdfRendererNative_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d9dcd91_d277_4947_8527_07a0daeda94a);
}
impl ::core::convert::From<IPdfRendererNative> for ::windows::core::IUnknown {
fn from(value: IPdfRendererNative) -> Self {
value.0
}
}
impl ::core::convert::From<&IPdfRendererNative> for ::windows::core::IUnknown {
fn from(value: &IPdfRendererNative) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPdfRendererNative {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IPdfRendererNative {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IPdfRendererNative_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common", feature = "Win32_Graphics_Dxgi"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdfpage: ::windows::core::RawPtr, psurface: ::windows::core::RawPtr, offset: super::super::super::Foundation::POINT, prenderparams: *const PDF_RENDER_PARAMS) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common", feature = "Win32_Graphics_Dxgi")))] usize,
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D", feature = "Win32_Graphics_Direct2D_Common"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdfpage: ::windows::core::RawPtr, pd2ddevicecontext: ::windows::core::RawPtr, prenderparams: *const PDF_RENDER_PARAMS) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D", feature = "Win32_Graphics_Direct2D_Common")))] usize,
);
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common"))]
pub struct PDF_RENDER_PARAMS {
pub SourceRect: super::super::super::Graphics::Direct2D::Common::D2D_RECT_F,
pub DestinationWidth: u32,
pub DestinationHeight: u32,
pub BackgroundColor: super::super::super::Graphics::Direct2D::Common::D2D_COLOR_F,
pub IgnoreHighContrast: super::super::super::Foundation::BOOLEAN,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common"))]
impl PDF_RENDER_PARAMS {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common"))]
impl ::core::default::Default for PDF_RENDER_PARAMS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common"))]
impl ::core::fmt::Debug for PDF_RENDER_PARAMS {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("PDF_RENDER_PARAMS").field("SourceRect", &self.SourceRect).field("DestinationWidth", &self.DestinationWidth).field("DestinationHeight", &self.DestinationHeight).field("BackgroundColor", &self.BackgroundColor).field("IgnoreHighContrast", &self.IgnoreHighContrast).finish()
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common"))]
impl ::core::cmp::PartialEq for PDF_RENDER_PARAMS {
fn eq(&self, other: &Self) -> bool {
self.SourceRect == other.SourceRect && self.DestinationWidth == other.DestinationWidth && self.DestinationHeight == other.DestinationHeight && self.BackgroundColor == other.BackgroundColor && self.IgnoreHighContrast == other.IgnoreHighContrast
}
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common"))]
impl ::core::cmp::Eq for PDF_RENDER_PARAMS {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Graphics_Direct2D_Common"))]
unsafe impl ::windows::core::Abi for PDF_RENDER_PARAMS {
type Abi = Self;
}
#[cfg(feature = "Win32_Graphics_Dxgi")]
pub type PFN_PDF_CREATE_RENDERER = unsafe extern "system" fn(param0: ::windows::core::RawPtr, param1: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT;
#[cfg(feature = "Win32_Graphics_Dxgi")]
#[inline]
pub unsafe fn PdfCreateRenderer<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Graphics::Dxgi::IDXGIDevice>>(pdevice: Param0) -> ::windows::core::Result<IPdfRendererNative> {
#[cfg(windows)]
{
#[link(name = "windows")]
extern "system" {
fn PdfCreateRenderer(pdevice: ::windows::core::RawPtr, pprenderer: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT;
}
let mut result__: <IPdfRendererNative as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
PdfCreateRenderer(pdevice.into_param().abi(), &mut result__).from_abi::<IPdfRendererNative>(result__)
}
#[cfg(not(windows))]
unimplemented!("Unsupported target OS");
}
|
use std::collections::BTreeMap;
use std::fs::{create_dir_all, File};
use std::io::{BufWriter, Write};
use std::path::Path;
use {Class, Result};
mod code;
mod header;
static MODULE_MAP: &str = include_str!("module.map");
pub fn write<P: AsRef<Path>>(path: P, classes: &BTreeMap<String, Class>) -> Result<()> {
let mut path = path.as_ref().to_owned();
path.push("LiveSplitCoreNative");
create_dir_all(&path)?;
path.push("livesplit_core.h");
header::write(BufWriter::new(File::create(&path)?), classes)?;
path.pop();
path.push("module.map");
write!(BufWriter::new(File::create(&path)?), "{}", MODULE_MAP)?;
path.pop();
path.pop();
path.push("LiveSplitCore.swift");
code::write(BufWriter::new(File::create(&path)?), classes)?;
path.pop();
Ok(())
}
|
use anyhow::{anyhow, Result};
use code_writer::{write_bootstrap, write_code};
use parser::parse;
use std::io::{BufWriter, Write};
use std::{env, ffi::OsStr};
use std::{fs::File, path::Path};
mod arithmetic_command;
mod code_writer;
mod command;
mod parser;
mod segment;
fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
return Err(anyhow!("please enter file name"));
}
let path_dir = Path::new(&args[1]);
if path_dir.is_dir() {
let file_name = path_dir.file_stem().unwrap().to_str().unwrap();
let new_file_path = path_dir.join(Path::new(file_name).with_extension("asm"));
let new_file = File::create(new_file_path)?;
let mut writer = BufWriter::new(new_file);
let file_names = path_dir
.read_dir()?
.filter_map(|entry| {
entry.ok().and_then(|e| {
e.path()
.file_name()
.and_then(|n| n.to_str().map(|s| s.to_string()))
})
})
.collect::<Vec<String>>();
if file_names.contains(&"Sys.vm".to_string()) {
writer.write(write_bootstrap().as_bytes())?;
writer.write(b"\n\n")?;
}
let dirs = path_dir.read_dir()?;
for dir in dirs {
let dir = dir?;
if let Some(extension) = dir.path().extension() {
if extension == OsStr::new("vm") {
let commands = parse(&dir.path())?;
let mut id: i32 = 0;
for command in commands {
writer.write(
write_code(
dir.path().file_stem().unwrap().to_str().unwrap(),
&command,
&id,
)
.as_bytes(),
)?;
writer.write(b"\n\n")?;
id += 1;
}
}
}
}
} else {
if let Some(extension) = path_dir.extension() {
if extension == OsStr::new("vm") {
let commands = parse(&path_dir.to_path_buf())?;
let new_file_path = Path::new(path_dir.parent().unwrap())
.join(Path::new(path_dir.file_stem().unwrap()).with_extension("asm"));
let new_file = File::create(new_file_path)?;
let mut writer = BufWriter::new(new_file);
let mut id: i32 = 0;
for command in commands {
writer.write(
write_code(
&path_dir.file_stem().unwrap().to_str().unwrap(),
&command,
&id,
)
.as_bytes(),
)?;
writer.write(b"\n\n")?;
id += 1;
}
}
}
}
Ok(())
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use failure::Fail;
use fuchsia_pkg::{BuildError, CreationManifestError, MetaPackageError};
use std::io;
#[derive(Debug, Fail)]
pub enum PmBuildError {
#[fail(display = "io error: {}", _0)]
IoError(#[cause] io::Error),
#[fail(display = "creation manifest error: {}", _0)]
CreationManifest(#[cause] CreationManifestError),
#[fail(display = "meta package error: {}", _0)]
MetaPackage(#[cause] MetaPackageError),
#[fail(display = "build error: {}", _0)]
Build(#[cause] BuildError),
#[fail(display = "signing key file should be 64 bytes but was: {}", actual_size)]
WrongSizeSigningKey { actual_size: u64 },
}
impl From<io::Error> for PmBuildError {
fn from(err: io::Error) -> Self {
PmBuildError::IoError(err)
}
}
impl From<CreationManifestError> for PmBuildError {
fn from(err: CreationManifestError) -> Self {
PmBuildError::CreationManifest(err)
}
}
impl From<MetaPackageError> for PmBuildError {
fn from(err: MetaPackageError) -> Self {
PmBuildError::MetaPackage(err)
}
}
impl From<BuildError> for PmBuildError {
fn from(err: BuildError) -> Self {
PmBuildError::Build(err)
}
}
|
use crate::{Force, ForceToNode, Point, MIN_DISTANCE};
use petgraph::graph::{Graph, IndexType, NodeIndex};
use petgraph::EdgeType;
use quadtree::{Element, NodeId, Quadtree, Rect};
#[derive(Copy, Clone, Debug)]
struct Body {
x: f32,
y: f32,
strength: f32,
}
impl Body {
fn new(x: f32, y: f32, strength: f32) -> Body {
Body { x, y, strength }
}
}
impl Default for Body {
fn default() -> Body {
Body::new(0., 0., 0.)
}
}
fn accumulate(tree: &mut Quadtree<Body>, node_id: NodeId) {
let mut sum_weight = 0.;
let mut sum_strength = 0.;
let mut sum_x = 0.;
let mut sum_y = 0.;
for &(ref e, _) in tree.elements(node_id).iter() {
match **e {
Element::Leaf { x, y, n, value } => {
let strength = value * n as f32;
let weight = strength.abs();
sum_strength += strength;
sum_weight += weight;
sum_x += x * weight;
sum_y += y * weight;
}
Element::Node { node_id } => {
accumulate(tree, node_id);
let data = tree.data(node_id);
let strength = data.strength;
let weight = strength.abs();
sum_strength += strength;
sum_weight += weight;
sum_x += data.x * weight;
sum_y += data.y * weight;
}
Element::Empty => {}
}
}
let data = tree.data_mut(node_id);
data.strength = sum_strength;
data.x = sum_x / sum_weight;
data.y = sum_y / sum_weight;
}
fn apply_many_body(
point: &mut Point,
tree: &Quadtree<Body>,
node_id: NodeId,
alpha: f32,
theta2: f32,
) {
for &(ref e, _) in tree.elements(node_id).iter() {
match **e {
Element::Node { node_id } => {
let data = tree.data(node_id);
let rect = tree.rect(node_id);
let dx = rect.cx - point.x;
let dy = rect.cy - point.y;
let l = (dx * dx + dy * dy).max(MIN_DISTANCE);
if rect.width * rect.height / theta2 < l {
point.vx += dx * data.strength * alpha / l;
point.vy += dy * data.strength * alpha / l;
} else {
apply_many_body(point, tree, node_id, alpha, theta2);
}
}
Element::Leaf { x, y, n, value } => {
if x != point.x || y != point.y {
let strength = value * n as f32;
let dx = x - point.x;
let dy = y - point.y;
let l = (dx * dx + dy * dy).max(MIN_DISTANCE);
point.vx += dx * strength * alpha / l;
point.vy += dy * strength * alpha / l;
}
}
Element::Empty => {}
}
}
}
pub struct ManyBodyForce {
strength: Vec<f32>,
}
impl ManyBodyForce {
pub fn new<N, E, Ty: EdgeType, Ix: IndexType>(graph: &Graph<N, E, Ty, Ix>) -> ManyBodyForce {
ManyBodyForce::new_with_accessor(graph, |_, _| None)
}
pub fn new_with_accessor<
N,
E,
Ty: EdgeType,
Ix: IndexType,
F: Fn(&Graph<N, E, Ty, Ix>, NodeIndex<Ix>) -> Option<f32>,
>(
graph: &Graph<N, E, Ty, Ix>,
strength_accessor: F,
) -> ManyBodyForce {
let strength = graph
.node_indices()
.map(|u| {
if let Some(v) = strength_accessor(graph, u) {
v
} else {
default_strength_accessor(graph, u)
}
})
.collect();
ManyBodyForce { strength }
}
}
impl Force for ManyBodyForce {
fn apply(&self, points: &mut [Point], alpha: f32) {
let max_x = points.iter().fold(0.0 / 0.0, |m, v| v.x.max(m));
let min_x = points.iter().fold(0.0 / 0.0, |m, v| v.x.min(m));
let max_y = points.iter().fold(0.0 / 0.0, |m, v| v.y.max(m));
let min_y = points.iter().fold(0.0 / 0.0, |m, v| v.y.min(m));
let width = max_x - min_x;
let height = max_y - min_y;
let size = width.max(height);
let mut tree: Quadtree<Body> = Quadtree::new(Rect {
cx: (min_x + max_x) / 2.,
cy: (min_y + max_y) / 2.,
width: size,
height: size,
});
let root = tree.root();
for (point, &strength) in points.iter().zip(&self.strength) {
tree.insert(root, point.x, point.y, strength);
}
accumulate(&mut tree, root);
for point in points.iter_mut() {
apply_many_body(point, &tree, root, alpha, 0.81);
}
}
}
impl ForceToNode for ManyBodyForce {
fn apply_to_node(&self, i: usize, points: &mut [Point], alpha: f32) {
let n = points.len();
for j in 0..n {
if i == j {
continue;
}
let Point { x, y, .. } = points[j];
let ref mut point = points[i];
let dx = x - point.x;
let dy = y - point.y;
let l = (dx * dx + dy * dy).max(MIN_DISTANCE);
point.vx += dx * self.strength[j] * alpha / l;
point.vy += dy * self.strength[j] * alpha / l;
}
}
}
pub fn default_strength_accessor<N, E, Ty: EdgeType, Ix: IndexType>(
_graph: &Graph<N, E, Ty, Ix>,
_u: NodeIndex<Ix>,
) -> f32 {
-30.
}
// #[test]
// fn test_many_body() {
// let mut points = Vec::new();
// points.push(Point::new(10., 10.));
// points.push(Point::new(10., -10.));
// points.push(Point::new(-10., 10.));
// points.push(Point::new(-10., -10.));
// let context = QuadTreeManyBodyForceContext::new(vec![-30., -30., -30., -30.]);
// context.apply(&mut points, 1.0);
// assert!(points[0].vx == 2.25);
// assert!(points[0].vy == 2.25);
// assert!(points[1].vx == 2.25);
// assert!(points[1].vy == -2.25);
// assert!(points[2].vx == -2.25);
// assert!(points[2].vy == 2.25);
// assert!(points[3].vx == -2.25);
// assert!(points[3].vy == -2.25);
// }
|
// use std::ops::*;
// use std::fmt::*;
// use traits::{Zero, One};
// use Math;
// #[derive(PartialEq, Copy, Clone)]
// pub struct Vector3<T> {
// x: T,
// y: T,
// z: T
// }
// pub type Vector3i = Vector3<i32>;
// pub type Vector3u = Vector3<u32>;
// pub type Vector3f = Vector3<f32>;
// impl<T> Vector3<T> {
// /// Constructs a new vector out of three values of type T
// ///
// /// # Examples
// /// ```
// /// use nostra::Vector3i;
// /// let a = Vector3i::new(4, 5, -2);
// /// ```
// /// ---
// /// ```
// /// use nostra::Vector3f;
// /// let b = Vector3f::new(-1.0, 34.0, 12.1);
// /// ```
// pub fn new(x: T, y: T, z: T) -> Self {
// Vector3 { x, y, z }
// }
// }
// impl Vector3<f32> {
// /// Returns the length of the vector
// pub fn length(&self) -> f32 {
// self.length_squared().sqrt()
// }
// /// Returns the squared length of the vector
// pub fn length_squared(&self) -> f32 {
// self.x * self.x + self.y * self.y + self.z * self.z
// }
// /// Normalises the vector so that its length becomes 1
// pub fn normalize(&mut self) {
// let length = self.length();
// self.x /= length;
// self.y /= length;
// }
// }
// impl<T: PartialOrd + Copy> Vector3<T> {
// /// Clamps the vector between a min and a max vector
// pub fn clamp(&mut self, min: Vector3<T>, max: Vector3<T>) {
// self.x = Math::clamp(self.x, min.x, max.x);
// self.y = Math::clamp(self.y, min.y, max.y);
// self.z = Math::clamp(self.z, min.z, max.z);
// }
// }
// impl<T: Zero + One> Vector3<T> {
// /// Constructs a new unit X (1, 0, 0) vector
// pub fn unit_x() -> Self {
// Vector3 { x: T::one(), y: T::zero(), z: T::zero() }
// }
// /// Constructs a new unit Y (0, 1, 0) vector
// pub fn unit_y() -> Self {
// Vector3 { x: T::zero(), y: T::one(), z: T::zero() }
// }
// /// Constructs a new unit Z (0, 0, 1) vector
// pub fn unit_z() -> Self {
// Vector3 { x: T::zero(), y: T::zero(), z: T::one() }
// }
// }
// impl<T: Zero + One + Neg<Output = T>> Vector3<T> {
// /// Constructs a new vector pointing up (0, 1, 0)
// pub fn up() -> Self {
// Vector3 { x: T::zero(), y: T::one(), z: T::zero() }
// }
// /// Constructs a new vector pointing down (0, -1, 0)
// pub fn down() -> Self {
// Vector3 { x: T::zero(), y: -T::one(), z: T::zero() }
// }
// /// Constructs a new vector pointing right (1, 0, 0)
// pub fn right() -> Self {
// Vector3 { x: T::one(), y: T::zero(), z: T::zero() }
// }
// /// Constructs a new vector pointing left (-1, 0, 0)
// pub fn left() -> Self {
// Vector3 { x: -T::one(), y: T::zero(), z: T::zero() }
// }
// /// Constructs a new vector pointing forward (0, 0, -1)
// pub fn forward() -> Self {
// Vector3 { x: T::zero(), y: T::zero(), z: -T::one() }
// }
// /// Constructs a new vector pointing backward (0, 0, 1)
// pub fn backward() -> Self {
// Vector3 { x: T::zero(), y: T::zero(), z: T::one() }
// }
// }
// impl<T: Add<Output = T>> Add for Vector3<T> {
// type Output = Self;
// fn add(self, other: Self) -> Self {
// Vector3 {
// x: self.x + other.x,
// y: self.y + other.y,
// z: self.z + other.z,
// }
// }
// }
// impl<T: AddAssign> AddAssign for Vector3<T> {
// fn add_assign(&mut self, other: Self) {
// self.x += other.x;
// self.y += other.y;
// self.z += other.z;
// }
// }
// impl<T: Sub<Output = T>> Sub for Vector3<T> {
// type Output = Self;
// fn sub(self, other: Self) -> Self {
// Vector3 {
// x: self.x - other.x,
// y: self.y - other.y,
// z: self.z - other.z,
// }
// }
// }
// impl<T: SubAssign> SubAssign for Vector3<T> {
// fn sub_assign(&mut self, other: Self) {
// self.x -= other.x;
// self.y -= other.y;
// self.z -= other.z;
// }
// }
// impl<T: Mul<Output = T>> Mul for Vector3<T> {
// type Output = Self;
// fn mul(self, other: Self) -> Self {
// Vector3 {
// x: self.x * other.x,
// y: self.y * other.y,
// z: self.z * other.z,
// }
// }
// }
// impl<T: MulAssign> MulAssign for Vector3<T> {
// fn mul_assign(&mut self, other: Self) {
// self.x *= other.x;
// self.y *= other.y;
// self.z *= other.z;
// }
// }
// impl<T: Div<Output = T>> Div for Vector3<T> {
// type Output = Self;
// fn div(self, other: Self) -> Self {
// Vector3 {
// x: self.x / other.x,
// y: self.y / other.y,
// z: self.z / other.z,
// }
// }
// }
// impl<T: DivAssign> DivAssign for Vector3<T> {
// fn div_assign(&mut self, other: Self) {
// self.x /= other.x;
// self.y /= other.y;
// self.z /= other.z;
// }
// }
// impl<T: Neg<Output = T>> Neg for Vector3<T> {
// type Output = Self;
// fn neg(self) -> Self {
// Vector3 {
// x: -self.x,
// y: -self.y,
// z: -self.z,
// }
// }
// }
// impl<T: Zero> Zero for Vector3<T> {
// fn zero() -> Self {
// Vector3 {
// x: T::zero(),
// y: T::zero(),
// z: T::zero(),
// }
// }
// }
// impl<T: One> One for Vector3<T> {
// fn one() -> Self {
// Vector3 {
// x: T::one(),
// y: T::one(),
// z: T::one(),
// }
// }
// }
// impl<T: Display> Debug for Vector3<T> {
// fn fmt(&self, f: &mut Formatter) -> Result {
// write!(f, "{{ x: {}, y: {}, z: {} }}",
// self.x, self.y, self.z)
// }
// }
// #[cfg(test)]
// mod tests {
// macro_rules! assert_vector_eq {
// ($vector:expr, $x:expr, $y:expr, $z:expr) => {{
// assert_eq!($vector.x, $x);
// assert_eq!($vector.y, $y);
// assert_eq!($vector.z, $z)
// }}
// }
// mod constructions {
// use super::super::*;
// #[test]
// fn it_constructs() {
// let v = Vector3::new(-1.0, 23.1, 14.1);
// assert_vector_eq!(v, -1.0, 23.1, 14.1);
// }
// #[test]
// fn it_creates_unit_x_vector() {
// let v = Vector3f::unit_x();
// assert_vector_eq!(v, 1.0, 0.0, 0.0);
// }
// #[test]
// fn it_creates_unit_y_vector() {
// let v = Vector3i::unit_y();
// assert_vector_eq!(v, 0, 1, 0);
// }
// #[test]
// fn it_creates_up_vector() {
// let v = Vector3i::up();
// assert_vector_eq!(v, 0, 1, 0);
// }
// #[test]
// fn it_creates_down_vector() {
// let v = Vector3f::down();
// assert_vector_eq!(v, 0.0, -1.0, 0.0);
// }
// #[test]
// fn it_creates_right_vector() {
// let v = Vector3f::right();
// assert_vector_eq!(v, 1.0, 0.0, 0.0);
// }
// #[test]
// fn it_creates_left_vector() {
// let v = Vector3i::left();
// assert_vector_eq!(v, -1, 0, 0);
// }
// #[test]
// fn it_creates_forward_vector() {
// let v = Vector3f::forward();
// assert_vector_eq!(v, 0.0, 0.0, -1.0);
// }
// #[test]
// fn it_creates_backward_vector() {
// let v = Vector3f::backward();
// assert_vector_eq!(v, 0.0, 0.0, 1.0);
// }
// }
// mod operators {
// use super::super::*;
// #[test]
// fn it_adds_with_vector() {
// let v = Vector3::new(2, 10, -1) + Vector3::new(1, 24, -1);
// assert_vector_eq!(v, 3, 34, -2);
// }
// #[test]
// fn it_addassigns_with_vector() {
// let mut v = Vector3::new(1, 2, 3);
// v += Vector3::new(3, 4, 5);
// assert_vector_eq!(v, 4, 6, 8);
// }
// #[test]
// fn it_subtracts_with_vector() {
// let v = Vector3::new(-1.2, 4.3, 1.2) - Vector3::new(5.0, 24.2, -123.2);
// assert_vector_eq!(v, -6.2, -19.9, 124.4);
// }
// #[test]
// fn it_subassigns_with_vector() {
// let mut v = Vector3::new(2.0, -22.0, 23.0);
// v -= Vector3::new(1.0, 5.0, 23.0);
// assert_vector_eq!(v, 1.0, -27.0, 0.0);
// }
// #[test]
// fn it_multiplies_with_vector() {
// let v = Vector3::new(1.0, 4.0, 2.3) * Vector3::new(1.2, 3.3, -1.2);
// assert_vector_eq!(v, 1.2, 13.2, -2.76);
// }
// #[test]
// fn it_mulassigns_with_vector() {
// let mut v = Vector3::new(4, 5, 2);
// v *= Vector3::new(1, 2, 3);
// assert_vector_eq!(v, 4, 10, 6);
// }
// #[test]
// fn it_divides_with_vector() {
// let v = Vector3::new(4.0, 25.0, 0.05) / Vector3::new(2.0, 5.0, 1.0);
// assert_vector_eq!(v, 2.0, 5.0, 0.05);
// }
// #[test]
// fn it_divassigns_with_vector() {
// let mut v = Vector3::new(2, 21, 28);
// v /= Vector3::new(2, 7, 2);
// assert_vector_eq!(v, 1, 3, 14);
// }
// #[test]
// fn it_equals_with_vector() {
// let a = Vector3::new(2.2, 4.0001, 22.21);
// assert!(a == Vector3::new(2.2, 4.0001, 22.21));
// }
// #[test]
// fn it_negates() {
// let v = -Vector3::new(2.3, -12.23, 123.0);
// assert_vector_eq!(v, -2.3, 12.23, -123.0)
// }
// }
// mod traits {
// use super::super::*;
// #[test]
// fn it_implements_zero() {
// let v = Vector3i::zero();
// assert_vector_eq!(v, 0, 0, 0);
// }
// #[test]
// fn it_implements_one() {
// let v = Vector3f::one();
// assert_vector_eq!(v, 1.0, 1.0, 1.0);
// }
// }
// mod methods {
// use super::super::*;
// #[test]
// fn it_returns_length() {
// let v = Vector3f::new(2.0, 3.0, 4.0);
// assert!(v.length() - 5.385164 < 0.001);
// }
// #[test]
// fn it_returns_length_squared() {
// let v = Vector3f::new(1.0, 2.0, 3.0);
// assert_eq!(v.length_squared(), 14.0);
// }
// #[test]
// fn it_normalizes() {
// let mut a = Vector3f::new(1.0, 2.0, 3.0);
// let b = a;
// let length = b.length();
// a.normalize();
// assert!(a.length() - 3.4116 < 0.001);
// assert_eq!(a.x, b.x / length);
// assert_eq!(a.y, b.y / length);
// }
// #[test]
// fn it_clamps() {
// let mut v = Vector3i::new(10, -2, 4);
// v.clamp(Vector3i::new(0, 3, 1), Vector3i::new(2, 4, 6));
// assert_vector_eq!(v, 2, 3, 4);
// }
// }
// }
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use liblumen_alloc::erts::exception;
use liblumen_alloc::erts::process::Process;
use liblumen_alloc::erts::term::prelude::*;
#[native_implemented::function(erlang:map_size/1)]
pub fn result(process: &Process, map: Term) -> exception::Result<Term> {
let boxed_map = term_try_into_map_or_badmap!(process, map)?;
let len = boxed_map.len();
let len_term = process.integer(len);
Ok(len_term)
}
|
#[derive(Clone)]
enum Movement {
Up,
Down,
Left,
Right,
}
impl From<u8> for Movement {
fn from(b: u8) -> Self {
match b {
b'U' => Movement::Up,
b'D' => Movement::Down,
b'L' => Movement::Left,
b'R' => Movement::Right,
_ => unreachable!(),
}
}
}
impl Movement {
fn from_command(command: &str) -> Vec<Self> {
let re = regex::Regex::new(r"(U|D|L|R) (\d+)").unwrap();
let cap = re.captures(command).unwrap();
let num_moves = cap.get(2).unwrap().as_str().parse::<usize>().unwrap();
let direction = cap.get(1).unwrap().as_str().as_bytes()[0].into();
vec![direction; num_moves]
}
}
#[derive(Clone, Copy, Debug)]
struct Head(i64, i64);
impl From<Head> for (i64, i64) {
fn from(h: Head) -> (i64, i64) {
(h.0, h.1)
}
}
impl From<Head> for Tail {
fn from(h: Head) -> Self {
Self(h.0, h.1)
}
}
impl Head {
pub fn new() -> Self {
Self(0, 0)
}
pub fn r#move(self, command: Movement) -> (Head, Head) {
let old_head = self;
let new_head = match command {
Movement::Up => Head(old_head.0, old_head.1 + 1),
Movement::Down => Head(old_head.0, old_head.1 - 1),
Movement::Left => Head(old_head.0 - 1, old_head.1),
Movement::Right => Head(old_head.0 + 1, old_head.1),
};
(old_head, new_head)
}
}
#[derive(Copy, Clone, Eq, PartialEq, std::hash::Hash, Debug)]
struct Tail(i64, i64);
impl From<Tail> for (i64, i64) {
fn from(t: Tail) -> (i64, i64) {
(t.0, t.1)
}
}
impl Tail {
pub fn new() -> Self {
Self(0, 0)
}
fn follow(self, (old, new): ((i64, i64), (i64, i64))) -> (Self, Self) {
if self.is_adjacent(&new) {
return (self, self);
}
if old.0 == new.0 || old.1 == new.1 {
return (self, Self(old.0, old.1));
}
if self.0 == new.0 {
return (self, Self(self.0, old.1));
}
if self.1 == new.1 {
return (self, Self(old.0, self.1));
}
let delta = (new.0 - old.0, new.1 - old.1);
(self, Self(self.0 + delta.0, self.1 + delta.1))
}
fn is_adjacent(&self, other: &(i64, i64)) -> bool {
self.0 - 1 <= other.0
&& other.0 <= self.0 + 1
&& self.1 - 1 <= other.1
&& other.1 <= self.1 + 1
}
}
#[derive(Debug, Clone)]
struct Rope {
head: Head,
rest: [Tail; 9],
}
impl Rope {
pub fn new() -> Self {
Rope {
head: Head::new(),
rest: [Tail::new(); 9],
}
}
pub fn r#move(mut self, m: Movement) -> Self {
let (old_head, new_head) = self.head.r#move(m);
self.head = new_head;
let (mut old_tail, mut new_tail): (Tail, Tail) = (old_head.into(), new_head.into());
for t in self.rest.iter_mut() {
(old_tail, new_tail) = t.follow((old_tail.into(), new_tail.into()));
*t = new_tail;
}
tracing::debug!("{self:?}");
self
}
}
pub fn part1(input: &str) {
let mut tail_positions = std::collections::HashSet::new();
let mut head = Head::new();
let mut tail = Tail::new();
tail_positions.insert(tail);
for command in input.trim().split('\n') {
let movements = Movement::from_command(command);
for m in movements {
let (old_head, new_head) = head.r#move(m);
head = new_head;
tail = tail.follow((old_head.into(), new_head.into())).1;
tail_positions.insert(tail);
}
}
tracing::info!("Part 1 Answer: {}", tail_positions.len());
}
pub fn part2(input: &str) {
let mut rope = Rope::new();
let mut tail_positions = std::collections::HashSet::new();
tail_positions.insert(rope.rest[8]);
for command in input.trim().split('\n') {
tracing::debug!("rope: {:?}", rope);
let movements = Movement::from_command(command);
for m in movements {
rope = rope.r#move(m);
tail_positions.insert(rope.rest[8]);
}
}
tracing::info!("Part 2 Answer: {}", tail_positions.len());
}
|
/*
Bob is a lackadaisical teenager. In conversation, his responses are very limited.
Bob answers 'Sure.' if you ask him a question.
He answers 'Whoa, chill out!' if you yell at him.
He answers 'Calm down, I know what I'm doing!' if you yell a question at him.
He says 'Fine. Be that way!' if you address him without actually saying anything.
He answers 'Whatever.' to anything else.
Bob's conversational partner is a purist when it comes to written communication and always follows
normal rules regarding sentence punctuation in English.
*/
fn is_yelling(message: &str) -> bool {
let hasLetters: bool = message.chars().filter(|x| x.is_alphabetic()).count() > 0;
message.to_uppercase() == message && hasLetters // is all caps?
}
pub fn reply(message: &str) -> &str {
match message.trim() {
m if m.len() == 0 => "Fine. Be that way!",
m if m.ends_with("?") && !is_yelling(m) => "Sure.",
m if m.ends_with("?") && is_yelling(m) => "Calm down, I know what I'm doing!",
m if is_yelling(m) => "Whoa, chill out!",
_ => "Whatever."
}
}
|
use ffi;
use error;
use std::mem;
use std::sync::Arc;
use device::Device;
use CommandBufferExt;
use ImageExt;
use MantleObject;
use presentable_image::PresentableImage;
pub struct CommandBuffer {
device: Arc<Device>,
cmd: ffi::GR_CMD_BUFFER,
memory_refs: Vec<ffi::GR_MEMORY_REF>,
}
pub struct CommandBufferBuilder {
device: Arc<Device>,
cmd: Option<ffi::GR_CMD_BUFFER>,
memory_refs: Vec<ffi::GR_MEMORY_REF>,
}
impl CommandBufferBuilder {
/// Builds a new prototype of a command buffer.
pub fn new(device: &Arc<Device>) -> CommandBufferBuilder {
let infos = ffi::GR_CMD_BUFFER_CREATE_INFO {
queueType: ffi::GR_QUEUE_UNIVERSAL,
flags: 0,
};
let cmd_buffer = unsafe {
let mut cmd = mem::uninitialized();
error::check_result(ffi::grCreateCommandBuffer(*device.get_id(),
&infos, &mut cmd)).unwrap();
cmd
};
error::check_result(unsafe { ffi::grBeginCommandBuffer(cmd_buffer, 0) }).unwrap();
CommandBufferBuilder {
device: device.clone(),
cmd: Some(cmd_buffer),
memory_refs: Vec::new(),
}
}
/// Adds a command that clears the given image to a specific color.
pub fn clear_image(mut self, image: &Arc<PresentableImage>, red: f32, green: f32, blue: f32, alpha: f32) -> CommandBufferBuilder {
let (image, image_mem, original_state) = (image.get_image(), image.get_mem(), image.get_normal_state());
// switching to `GR_IMAGE_STATE_CLEAR`
if original_state != ffi::GR_IMAGE_STATE_CLEAR {
let transition = ffi::GR_IMAGE_STATE_TRANSITION {
image: image,
oldState: original_state,
newState: ffi::GR_IMAGE_STATE_CLEAR,
subresourceRange: ffi::GR_IMAGE_SUBRESOURCE_RANGE {
aspect: ffi::GR_IMAGE_ASPECT_COLOR,
baseMipLevel: 0,
mipLevels: 1,
baseArraySlice: 0,
arraySize: 1,
},
};
unsafe {
ffi::grCmdPrepareImages(self.cmd.unwrap(), 1, &transition);
}
}
// clear color command
{
let color = [red, green, blue, alpha];
let range = ffi::GR_IMAGE_SUBRESOURCE_RANGE {
aspect: ffi::GR_IMAGE_ASPECT_COLOR,
baseMipLevel: 0,
mipLevels: 1,
baseArraySlice: 0,
arraySize: 1,
};
unsafe {
ffi::grCmdClearColorImage(self.cmd.unwrap(), image, color.as_ptr(), 1, &range);
}
}
// switching back to the previous state
if original_state != ffi::GR_IMAGE_STATE_CLEAR {
let transition = ffi::GR_IMAGE_STATE_TRANSITION {
image: image,
oldState: ffi::GR_IMAGE_STATE_CLEAR,
newState: original_state,
subresourceRange: ffi::GR_IMAGE_SUBRESOURCE_RANGE {
aspect: ffi::GR_IMAGE_ASPECT_COLOR,
baseMipLevel: 0,
mipLevels: 1,
baseArraySlice: 0,
arraySize: 1,
},
};
unsafe {
ffi::grCmdPrepareImages(self.cmd.unwrap(), 1, &transition);
}
}
self.memory_refs.push(ffi::GR_MEMORY_REF {
mem: image_mem,
flags: 0,
});
self
}
/// Builds the command buffer containing all the commands.
pub fn build(mut self) -> Arc<CommandBuffer> {
let cmd_buffer = self.cmd.take().unwrap();
error::check_result(unsafe { ffi::grEndCommandBuffer(cmd_buffer) }).unwrap();
Arc::new(CommandBuffer {
device: self.device.clone(),
cmd: cmd_buffer,
memory_refs: mem::replace(&mut self.memory_refs, Vec::with_capacity(0)),
})
}
}
impl Drop for CommandBufferBuilder {
fn drop(&mut self) {
if let Some(cmd) = self.cmd {
error::check_result(unsafe { ffi::grEndCommandBuffer(cmd) }).unwrap();
error::check_result(unsafe { ffi::grDestroyObject(cmd) }).unwrap();
}
}
}
impl MantleObject for CommandBuffer {
type Id = ffi::GR_CMD_BUFFER;
fn get_id(&self) -> &ffi::GR_CMD_BUFFER {
&self.cmd
}
}
impl CommandBufferExt for CommandBuffer {
fn build_memory_refs(&self) -> Vec<ffi::GR_MEMORY_REF> {
self.memory_refs.clone()
}
}
impl Drop for CommandBuffer {
fn drop(&mut self) {
error::check_result(unsafe { ffi::grDestroyObject(self.cmd) }).unwrap();
}
}
|
// Copyright 2019-2020 PolkaX. Licensed under MIT or Apache-2.0.
use std::fmt;
use std::ops::Deref;
use std::result;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use serde_cbor::Value;
use super::{Amt, Item, Node};
use crate::blocks::Blocks;
impl<B> Serialize for Amt<B>
where
B: Blocks,
{
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where
S: Serializer,
{
(self.height, self.count, &self.root).serialize(serializer)
}
}
impl<B> Eq for Amt<B> where B: Blocks {}
impl<B> PartialEq for Amt<B>
where
B: Blocks,
{
fn eq(&self, other: &Self) -> bool {
self.height.eq(&other.height) && self.count.eq(&other.count) && self.root.eq(&other.root)
}
}
impl<B> fmt::Debug for Amt<B>
where
B: Blocks,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Root{{ height:{:}, count:{:}, node:{:?} }}",
self.height, self.count, self.root
)
}
}
#[derive(Debug, Deserialize)]
pub struct PartAmt(pub u64, pub u64, pub Node);
impl Serialize for Item {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
match self {
Item::Link(cid) => cid::ipld_dag_cbor::serialize(cid, serializer),
Item::Ptr(_) => unreachable!("could not serialize `Ptr`, just allow `Link`"),
}
}
}
impl<'de> Deserialize<'de> for Item {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
cid::ipld_dag_cbor::deserialize(deserializer).map(Item::Link)
}
}
impl Serialize for Node {
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let r = self.bitmap.to_be_bytes();
let bytes: [u8; 1] = [r[r.len() - 1]; 1];
(
serde_bytes::Bytes::new(bytes.as_ref()),
self.branches.borrow().deref(),
&self.leafs,
)
.serialize(serializer)
}
}
#[derive(Deserialize)]
struct NodeVisitor(serde_bytes::ByteBuf, Vec<Item>, Vec<Value>);
impl<'de> Deserialize<'de> for Node {
fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let visitor = NodeVisitor::deserialize(deserializer)?;
if visitor.0.len() != 1 {
return Err(D::Error::custom(format!(
"node bitmap must be 1 byte, current is:{:?}",
visitor.0
)));
}
Ok(Node::new_from_raw(
visitor.0[0] as usize,
visitor.1,
visitor.2,
))
}
}
|
const a: i32 = 0;
fn main() {
let a = 0;
}
|
pub mod update_characters;
pub use self::update_characters::*;
|
use std::fmt::{self, Debug, Display, Formatter};
/// A single-byte character.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct ByteChar(u8);
impl ByteChar {
/// Creates a new `ByteChar` from a byte.
pub fn new(c: u8) -> Self {
ByteChar(c)
}
/// Unwraps the byte.
pub fn into_byte(self) -> u8 {
self.0
}
}
impl Debug for ByteChar {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "b'{}'", self.0 as char)
}
}
impl Display for ByteChar {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.0 as char)
}
}
|
mod begin;
mod bye;
mod commit;
mod discard;
mod failure;
mod hello;
mod pull;
mod record;
mod reset;
mod rollback;
mod run;
mod success;
use crate::errors::*;
use crate::types::*;
use crate::version::Version;
use begin::Begin;
use bytes::*;
use commit::Commit;
use discard::Discard;
use failure::Failure;
use hello::Hello;
use pull::Pull;
use record::Record;
use reset::Reset;
use rollback::Rollback;
use run::Run;
use std::cell::RefCell;
use std::rc::Rc;
use success::Success;
#[derive(Debug, PartialEq, Clone)]
pub enum BoltResponse {
SuccessMessage(Success),
FailureMessage(Failure),
RecordMessage(Record),
}
#[derive(Debug, PartialEq, Clone)]
pub enum BoltRequest {
HelloMessage(Hello),
RunMessage(Run),
PullMessage(Pull),
DiscardMessage(Discard),
BeginMessage(Begin),
CommitMessage(Commit),
RollbackMessage(Rollback),
ResetMessage(Reset),
}
impl BoltRequest {
pub fn hello(agent: &str, principal: String, credentials: String) -> BoltRequest {
let mut data = BoltMap::default();
data.put("user_agent".into(), agent.into());
data.put("scheme".into(), "basic".into());
data.put("principal".into(), principal.into());
data.put("credentials".into(), credentials.into());
BoltRequest::HelloMessage(Hello::new(data))
}
pub fn run(db: &str, query: &str, params: BoltMap) -> BoltRequest {
BoltRequest::RunMessage(Run::new(db.into(), query.into(), params))
}
pub fn pull(n: usize, qid: i64) -> BoltRequest {
BoltRequest::PullMessage(Pull::new(n as i64, qid))
}
pub fn discard() -> BoltRequest {
BoltRequest::DiscardMessage(Discard::default())
}
pub fn begin() -> BoltRequest {
BoltRequest::BeginMessage(Begin::new(BoltMap::default()))
}
pub fn commit() -> BoltRequest {
BoltRequest::CommitMessage(Commit::new())
}
pub fn rollback() -> BoltRequest {
BoltRequest::RollbackMessage(Rollback::new())
}
pub fn reset() -> BoltRequest {
BoltRequest::ResetMessage(Reset::new())
}
}
impl BoltRequest {
pub fn into_bytes(self, version: Version) -> Result<Bytes> {
let bytes: Bytes = match self {
BoltRequest::HelloMessage(hello) => hello.into_bytes(version)?,
BoltRequest::RunMessage(run) => run.into_bytes(version)?,
BoltRequest::PullMessage(pull) => pull.into_bytes(version)?,
BoltRequest::DiscardMessage(discard) => discard.into_bytes(version)?,
BoltRequest::BeginMessage(begin) => begin.into_bytes(version)?,
BoltRequest::CommitMessage(commit) => commit.into_bytes(version)?,
BoltRequest::RollbackMessage(rollback) => rollback.into_bytes(version)?,
BoltRequest::ResetMessage(reset) => reset.into_bytes(version)?,
};
Ok(bytes)
}
}
impl BoltResponse {
pub fn parse(version: Version, response: Bytes) -> Result<BoltResponse> {
match Rc::new(RefCell::new(response)) {
input if Success::can_parse(version, input.clone()) => Ok(
BoltResponse::SuccessMessage(Success::parse(version, input)?),
),
input if Failure::can_parse(version, input.clone()) => Ok(
BoltResponse::FailureMessage(Failure::parse(version, input)?),
),
input if Record::can_parse(version, input.clone()) => {
Ok(BoltResponse::RecordMessage(Record::parse(version, input)?))
}
msg => Err(Error::UnknownMessage(format!("{:?}", msg))),
}
}
}
|
use actix_web::{fs::NamedFile, HttpRequest, Error, Result};
pub fn index(_req: &HttpRequest) -> Result<NamedFile> {
Ok(NamedFile::open("public/index.html")?)
}
pub fn path(_req: &HttpRequest) -> Result<NamedFile> {
Ok(NamedFile::open("public/index.html")?)
} |
#![allow(unused_attributes)]
#![feature(no_coverage)]
use fuzzcheck::mutators::testing_utilities::test_mutator;
use fuzzcheck::DefaultMutator;
#[derive(Clone, Debug, PartialEq, Eq, Hash, DefaultMutator)]
struct S<T, const M: usize, const N: usize = 8> {
x: [T; N],
y: [bool; M],
}
#[test]
fn test_const_generics_mutator() {
let mutator = S::<u8, 2>::default_mutator();
test_mutator(mutator, 1000., 1000., false, true, 100, 100);
}
|
use crate::AST;
// todo: remove redundant forward
impl AST {
pub fn rewrite(&self) -> AST {
match self {
AST::Function { .. } => self.clone(),
// ```rs
// AST::AdditiveExpression { terms, position } => {
// let mut new = vec![];
// for e in terms {
// match e {
// AST::Integer(i) => {
// if i.is_zero() {
// continue;
// }
// else {
// new.push(e.clone())
// }
// }
// AST::AdditiveExpression { .. } => new.push(e.clone()),
// _ => new.push(e.clone()),
// }
// }
// AST::AdditiveExpression { terms: new, position: position.clone() }
// }
//
// AST::MultiplicativeExpression { .. } => self.clone(),
// ```
// AST::List(..) => self.clone(),
_ => self.clone(),
}
}
}
|
use super::{ HashedPassword, PasswordHasher, HashSalt };
use std::io;
use std::ptr;
use std::mem;
use std::intrinsics::volatile_set_memory;
/// The maximum length of the clear text password buffer.
///
/// If you decide to lower this length, you are a bad
/// person. If, however, you decide that you need more
/// password bytes for your hashing function, then...
/// well... go on!
pub const CLEAR_TEXT_LEN: usize = 512 - 8;
// You might want to ask why I chose this weird number
// `512 - 8` instead of just `512`. Why at all `512`
// and not `777`? Well, many allocators organise their
// memory in size classes of powers of two. Chunks of
// 64 bytes, chunks of 8 bytes, chunks of 2KiB, and so on.
// The password's data additionally contains a length
// indicator, which might be up to 8 bytes in size depending
// on the target platform. So, this "weird" size ensures
// that the password data's size is close to or exactly a
// big power of two, making most use of the actual memory
// reserved by an allocator.
//
// Btw., sorry that you can only change this number by
// changing the source code directly. I'd like to make it
// more like this:
//
// = parse_int!(option_env!("PASSWORS_CLEAR_TEXT_LEN").unwrap_or("0"))
//
// However, this isn't possible without extra fancy compiler
// plugins and yet even more constant functions.
/// All clear text passwords must have at least this
/// size in bytes.
///
/// Obviously, `default` does not fulfill this constraint.
pub const MIN_CLEAR_TEXT_LEN: usize = 16;
/// A clear text password is a fixed-sized buffer
/// of raw password bytes data.
///
/// # Why?
///
/// ## Why fixed-sized?
///
/// Well, to avoid giving your password hashing functions way
/// too much work, pretty much everyone sets a maximum length
/// for passwords. The important thing here is to set this
/// maximum length to a reasonably high limit. `passwors`
/// enforces a minimum buffer size of 248 bytes, which should
/// be small enough to not kill your hashing functions and
/// large enough to make even the most paranoid password owners
/// happy.
///
/// ## Why risk breaking multibyte characters?
///
/// Keeping unicode characters intact only matters if you handle
/// passwords like text someone is meant to read. However, noöne
/// should be reading passwords, except for maybe the password's
/// owner while he/she/it is typing the password into some form.
/// Okay, right, the hashing functions should be able to read the
/// password data as well. However, they don't care whether the
/// password is a markdown document or a PNG image. All they care
/// about is raw bytes.
///
/// ## Why not make it `Copy` or `Clone`?
///
/// Clear text passwords have only one raison d'être: Getting
/// hashed. This is also the reason why there are no functions
/// for inspecting the password's contents, not even its length.
/// And as they only should be hashed, there is no reason to
/// have multiple copies of clear text password's in memory.
///
/// ## Why zero-filling the password on `Drop`?
///
/// As mentioned before, clear text passwords only exist to be
/// hashed. Thus, there shouldn't be multiple copies of the
/// password running around in memory. Create it, hash it, forget
/// it. And zero-filling prevents others from allocating old
/// password memory and reading its old contents.
///
/// ## Why boxing the password data?
///
/// Although this sadly complicates making this crate `no_std`
/// compatible, this is a necessary step for ensuring a password's
/// uniqueness in memory. As there currently is no easy way to
/// modify how Rust moves values around, I cannot prevent Rust
/// from leaving non-zeroed password copies behind. I also cannot
/// prevent Rust from allowing to move clear text passwords around.
/// Therefore, I use boxed password data, including the password's
/// size. The boxed pointer can safely leave non-nulled pointer
/// copies behind, without leaking any information about the
/// corresponding password data.
///
/// ## Why not dropping the clear text after hashing?
///
/// Although this might be a sensible thing to do, I also have to
/// keep the possibility of upgraded hashers in mind. In the case
/// of upgrading password hashers, you'd have to hash a user's
/// clear text password twice, using the old and the new method.
/// So, either clear text passwords are copyable, or hashing
/// does not drop them.
pub struct ClearTextPassword {
data: Box<ClearTextPasswordData>,
}
struct ClearTextPasswordData {
text: [u8; CLEAR_TEXT_LEN],
len: usize,
}
impl ClearTextPassword {
/// Takes a string and extracts its contents as a
/// clear text password.
///
/// The string's data will be truncated to the clear
/// text password buffer's size with no respect for
/// multibyte unicode characters. I.e. the string
/// will be treated like a vector of raw bytes.
///
/// In addition to that, the whole string's allocated
/// buffer will be zero-filled to avoid having multiple
/// copies of passwords in memory, before finally dropping
/// the string.
///
/// If the given password is too short, `None` will be returned.
pub fn from_string(mut take: String) -> Option<ClearTextPassword> {
// Cheap overflow avoidance.
debug_assert!((take.len() as isize) >= 0, "Wtf, just how long is this string?!");
if take.len() < MIN_CLEAR_TEXT_LEN { return None; }
let mut ret = ClearTextPassword::empty_password();
(*ret.data).len = if take.len() > CLEAR_TEXT_LEN { CLEAR_TEXT_LEN } else { take.len() };
let src: *mut u8 = unsafe { mem::transmute(take.as_ptr()) };
let tgt: *mut u8 = (*ret.data).as_ptr_mut();
for i in 0..((*ret.data).len as isize) {
unsafe { ptr::write(tgt.offset(i), ptr::read(src.offset(i))) };
}
unsafe { volatile_set_memory(src, 0, take.capacity()) };
take.clear(); // Sets its `len` to zero. `capacity` could still leak a maximum length, though.
Some(ret)
}
/// Takes a vector of raw bytes and extracts its contents
/// as a clear text password.
///
/// The vector's data will be truncated to the clear text
/// password buffer's size. In addition to that, the whole
/// vector's allocated buffer will be zero-filled to avoid
/// having multiple copies of passwords in memory, before
/// finally dropping the vector.
///
/// If the given password is too short, `None` will be returned.
pub fn from_vec(mut take: Vec<u8>) -> Option<ClearTextPassword> {
if take.len() < MIN_CLEAR_TEXT_LEN { return None; }
let mut ret = ClearTextPassword::empty_password();
(*ret.data).len = if take.len() > CLEAR_TEXT_LEN { CLEAR_TEXT_LEN } else { take.len() };
for i in 0..(*ret.data).len { (*ret.data).text[i] = take[i]; }
unsafe { volatile_set_memory(take.as_mut_ptr(), 0, take.capacity()) };
take.clear();
Some(ret)
}
/// Grabs a clear text password out of a slice of bytes.
///
/// The whole slice will be overridden with zero bytes.
/// This is meant to avoid having multiple copies of
/// passwords in memory.
///
/// Returns `None` if the slice is too short.
pub fn from_slice(steal: &mut [u8]) -> Option<ClearTextPassword> {
if steal.len() < MIN_CLEAR_TEXT_LEN { return None; }
let mut ret = ClearTextPassword::empty_password();
(*ret.data).len = if steal.len() > CLEAR_TEXT_LEN { CLEAR_TEXT_LEN } else { steal.len() };
for i in 0..(*ret.data).len {
(*ret.data).text[i] = steal[i];
steal[i] = 0;
}
for i in (*ret.data).len..steal.len() { steal[i] = 0; }
Some(ret)
}
/// Reads a password from a reader and stores it into
/// a new clear text password buffer.
///
/// Note that this method has no influence on whether
/// the reader keeps its copy of the password or whether
/// an internal read buffer containing the password would
/// be overridden.
///
/// Returns `None` if there is not enough data to read.
///
/// # Errors
///
/// If the read operation failed, the clear text password
/// buffer will be zero-filled as usual and an error code
/// will be returned.
pub fn from_reader<R: io::Read>(r: &mut R) -> io::Result<Option<ClearTextPassword>> {
let mut ret = ClearTextPassword::empty_password();
let len = r.read((*ret.data).as_slice_mut())?;
if len < MIN_CLEAR_TEXT_LEN { return Ok(None); }
(*ret.data).len = len;
Ok(Some(ret))
}
/// Generates a hashed password using a given password hasher
/// and a hash salt.
///
/// Choose and configure your password hasher wisely. Otherwise,
/// guessing the clear text password corresponding to the
/// resulting hash might be too easy.
pub fn hash<H: PasswordHasher>(&self, hasher: &H, salt: &HashSalt) -> HashedPassword {
let mut hash = HashedPassword::new();
unsafe { hasher.hash(hash.as_slice_mut(), (*self.data).get_password(), salt.as_slice()) };
hash
}
fn empty_password() -> ClearTextPassword { ClearTextPassword { data: box ClearTextPasswordData {
text: [0_u8; CLEAR_TEXT_LEN],
len: 0,
}}}
}
impl ClearTextPasswordData {
fn as_ptr_mut(&mut self) -> *mut u8 { &mut self.text[0] }
fn as_slice_mut(&mut self) -> &mut [u8] { &mut self.text[..] }
fn get_password(&self) -> &[u8] { &self.text[0..self.len] }
fn is_cleared(&self) -> bool {
for x in &self.text[..] {
if 0 != unsafe { ptr::read_volatile(x) } { return false; }
}
self.len == 0
}
}
impl Drop for ClearTextPasswordData {
/// Zeros out the clear text password.
fn drop(&mut self) {
let data: *mut u8 = &mut self.text[0];
unsafe { volatile_set_memory(data, 0, self.text.len()) };
// Not only should you clear the password's data, but
// also any hint on the clear text password's length.
unsafe { ptr::write_volatile(&mut self.len, 0) };
if cfg!(test) { assert!(self.is_cleared()); }
}
}
#[cfg(test)]
mod test {
use super::{ClearTextPassword, CLEAR_TEXT_LEN, MIN_CLEAR_TEXT_LEN};
use std::ptr;
use test::Bencher;
use std::io::Cursor;
#[test]
fn clear_text_len_is_reasonably_large() {
assert!(CLEAR_TEXT_LEN >= (256 - 8), "You are a bad person.");
assert!(MIN_CLEAR_TEXT_LEN >= 14, "Recommended by NIST (2016).");
}
#[test]
fn short_passwords_are_shitty() {
assert!(
ClearTextPassword::from_string("lego".to_owned()).is_none(),
"Really, 4 bytes passwords?"
);
}
// This test **might crash** in case the allocator
// responsible for allocating the test password
// just happens to de-commit its memory pages
// previously used by our string.
#[cfg(not(skip_unsafe_tests))]
#[test]
#[allow(non_snake_case)]
fn take_string_and_zero___TRY_RERUN_IF_FAILED() {
let pw = "P@$$w0rd1!......".to_owned(); // Bad password. Don't you dare using it!
let data = pw.as_ptr();
let len = pw.len();
ClearTextPassword::from_string(pw).unwrap();
for i in 0..(len as isize) {
assert_eq!(unsafe { ptr::read_volatile(data.offset(i)) }, 0);
}
}
#[cfg(not(skip_unsafe_tests))]
#[test]
#[allow(non_snake_case)]
fn take_vec_and_zero___TRY_RERUN_IF_FAILED() {
let pw: Vec<u8> = vec![3, 4, 7, 42, 1,1,1,1,1,1,1,1,1,1,1,1];
let data = pw.as_ptr();
let len = pw.len();
ClearTextPassword::from_vec(pw).unwrap();
for i in 0..(len as isize) {
assert_eq!(unsafe { ptr::read_volatile(data.offset(i)) }, 0);
}
}
#[test]
fn take_slice_and_zero() {
let mut pw: [u8; 16] = [3, 4, 7, 42, 1,1,1,1,1,1,1,1,1,1,1,1];
ClearTextPassword::from_slice(&mut pw[..]).unwrap();
for x in &pw[..] { assert_eq!(*x, 0); }
}
#[test]
fn take_reader_and_hope() {
let pw: [u8; 16] = [3, 4, 7, 42, 1,1,1,1,1,1,1,1,1,1,1,1];
let mut reader = Cursor::new(&pw[..]);
ClearTextPassword::from_reader(&mut reader).unwrap().unwrap();
}
#[test]
fn dropping_really_clears() {
// Checks done by `drop`.
// Why? Because analysing free'd memory might
// result in rubbish. Someone else might have
// claimed and overridden it.
let _pw = ClearTextPassword::from_string(
"1234............".to_owned()
).unwrap(); // Really, don't you dare!
}
// Copy of `dropping_really_clears`. As benchmarks are
// optimised, this works as a final check that `volatile`
// really has the expected behaviour.
#[bench]
fn dropping_really_clears_okay_im_serious(_: &mut Bencher) {
let _pw = ClearTextPassword::from_string(
"asdf............".to_owned()
).unwrap(); // This password is fine, however.
}
}
|
pub fn swap(arr: &mut [i32], i: usize, j: usize) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp
}
pub fn partion(arr: &mut [i32]) -> usize {
let mut j: usize = 1;
for n in 1..arr.len() {
if arr[n] < arr[0] {
swap(arr, n, j);
j += 1;
}
}
swap(arr, 0, j - 1);
j - 1
}
pub fn quick_sort(arr: &mut [i32], times: &mut i32) {
if *times >= 4 {
return;
}
*times += 1;
if arr.len() <= 1 {
return;
}
let pos = partion(arr);
println!("pos={}", pos);
if pos > 1 {
quick_sort(&mut arr[..pos], times);
}
quick_sort(&mut arr[pos..], times);
}
#[test]
fn test_quick_sort() {
let mut arr: [i32; 10] = [8, 3, 2, 5, 6, 1, 9, 7, 0, 4];
let mut times = 0;
quick_sort(&mut arr[0..10], &mut times);
for value in arr.iter() {
print!("{} ", value);
}
println!("");
}
|
use clap::{crate_description, crate_name, crate_version, App, Arg};
use morgan_tokenbot::drone::{run_drone, Drone, DRONE_PORT};
use morgan_tokenbot::socketaddr;
use morgan_interface::signature::read_keypair;
use std::error;
use std::net::{Ipv4Addr, SocketAddr};
use std::sync::{Arc, Mutex};
use std::thread;
fn main() -> Result<(), Box<error::Error>> {
morgan_logger::setup();
morgan_metricbot::set_panic_hook("drone");
let matches = App::new(crate_name!())
.about(crate_description!())
.version(crate_version!())
.arg(
Arg::with_name("keypair")
.short("k")
.long("keypair")
.value_name("PATH")
.takes_value(true)
.required(true)
.help("File from which to read the mint's keypair"),
)
.arg(
Arg::with_name("slice")
.long("slice")
.value_name("SECS")
.takes_value(true)
.help("Time slice over which to limit requests to drone"),
)
.arg(
Arg::with_name("cap")
.long("cap")
.value_name("NUM")
.takes_value(true)
.help("Request limit for time slice"),
)
.get_matches();
let mint_keypair =
read_keypair(matches.value_of("keypair").unwrap()).expect("failed to read client keypair");
let time_slice: Option<u64>;
if let Some(secs) = matches.value_of("slice") {
time_slice = Some(secs.to_string().parse().expect("failed to parse slice"));
} else {
time_slice = None;
}
let request_cap: Option<u64>;
if let Some(c) = matches.value_of("cap") {
request_cap = Some(c.to_string().parse().expect("failed to parse cap"));
} else {
request_cap = None;
}
let drone_addr = socketaddr!(0, DRONE_PORT);
let drone = Arc::new(Mutex::new(Drone::new(
mint_keypair,
time_slice,
request_cap,
)));
let drone1 = drone.clone();
thread::spawn(move || loop {
let time = drone1.lock().unwrap().time_slice;
thread::sleep(time);
drone1.lock().unwrap().clear_request_count();
});
run_drone(drone, drone_addr, None);
Ok(())
}
|
use std::collections::HashMap;
use std::collections::VecDeque;
use std::hash::Hash;
pub mod graph_builders;
pub struct Graph<T> where T : Clone + Eq + Hash {
directed : bool,
nodes : Vec<T>,
node_indices : HashMap<T, usize>,
adjacency_list : Vec<Vec<usize>>,
}
#[derive(PartialEq, Eq, Clone)]
pub enum BFSTraversalState {
Undiscovered,
Discovered,
Processed,
}
#[derive(PartialEq, Eq, Clone)]
pub enum DFSTraversalState {
Undiscovered,
Processing (usize),
Processed (usize, usize),
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum DFSEdgeType {
Tree,
Back,
Cross,
Forward,
}
impl<T> Graph<T> where T : Clone + Eq + Hash {
pub fn new() -> Graph<T> {
Graph { nodes : Vec::new(), directed : false, node_indices : HashMap::new(), adjacency_list : Vec::new() }
}
pub fn number_of_vertices(&self) -> usize {
self.nodes.len()
}
pub fn is_directed(&self) -> bool {
self.directed
}
pub fn node_from_index(&self, index : usize) -> T {
if index < self.number_of_vertices() {
self.nodes[index].clone()
} else {
panic!("Called node_from_index({}) on a graph with only {} vertices!", index, self.number_of_vertices())
}
}
pub fn index_from_node(&self, node : T) -> usize {
match self.node_indices.get(&node) {
Some(i) => i.clone(),
None => panic!("Node was not present in the graph."),
}
}
pub fn get_degree_from_index(&self, index : usize) -> usize {
self.adjacency_list[index].len()
}
pub fn add_directed_edge(&mut self, source_index : usize, dest_index : usize) {
if dest_index >= self.number_of_vertices() {
panic!("dest_index {} was >= {}, the number of vertices in the graph.", dest_index, self.number_of_vertices())
}
if source_index >= self.number_of_vertices() {
panic!("source_index {} was >= {}, the number of vertices in the graph.", source_index, self.number_of_vertices())
}
if !self.adjacency_list[source_index].contains(&dest_index) {
self.adjacency_list[source_index].push(dest_index);
}
}
pub fn add_undirected_edge(&mut self, source_index : usize, dest_index : usize) {
self.add_directed_edge(source_index, dest_index);
self.add_directed_edge(dest_index, source_index);
}
pub fn breadth_first_iter_from_index<F, G> (&self,
mut process_vertex : F,
mut process_edge : G,
root_index : usize)
where F : FnMut(&T) -> (), G : FnMut(&T, &T) -> () {
let mut node_states = vec![BFSTraversalState::Undiscovered; self.number_of_vertices()];
node_states[root_index] = BFSTraversalState::Discovered;
let mut nodes_to_process = VecDeque::<usize>::new();
nodes_to_process.push_back(root_index);
while let Some(current_node) = nodes_to_process.pop_front() {
for dest_node in &self.adjacency_list[current_node] {
// Note - this does both edges in both directions for an undirected graph.
process_edge(&self.nodes[current_node], &self.nodes[*dest_node]);
if node_states[*dest_node] == BFSTraversalState::Undiscovered {
node_states[*dest_node] = BFSTraversalState::Discovered;
nodes_to_process.push_back(*dest_node);
}
}
process_vertex(&self.nodes[current_node]);
node_states[current_node] = BFSTraversalState::Processed;
}
}
// FIXME - I don't understand why process_edge and process_vertex don't need
// to be mutable here, whereas they do in the fn above (which I call!)
pub fn breadth_first_iter_from_node<F, G> (&self,
process_vertex : F,
process_edge : G,
root_node : T)
where F : FnMut(&T) -> (), G : FnMut(&T, &T) -> () {
let root_index = self.index_from_node(root_node);
self.breadth_first_iter_from_index(process_vertex, process_edge, root_index)
}
pub fn depth_first_iter_from_index<F, G, H> (&self,
mut process_vertex_early : F,
mut process_vertex_late : G,
mut process_edge : H,
root_node : usize)
where F : FnMut(&T) -> (), G : FnMut(&T) -> (), H : FnMut(&T, &T, DFSEdgeType, &Vec<Option<usize>>) -> () {
let mut discovery_state = vec![DFSTraversalState::Undiscovered; self.number_of_vertices()];
let mut parent = vec![None; self.number_of_vertices()];
// Call into a recursive function
self.inner_dfs(&mut process_vertex_early,
&mut process_vertex_late,
&mut process_edge,
&mut discovery_state,
&mut parent,
0usize,
root_node);
}
pub fn depth_first_iter<F, G, H> (&self,
mut process_vertex_early : F,
mut process_vertex_late : G,
mut process_edge : H)
where F : FnMut(&T) -> (), G : FnMut(&T) -> (), H : FnMut(&T, &T, DFSEdgeType, &Vec<Option<usize>>) -> () {
let mut discovery_state = vec![DFSTraversalState::Undiscovered; self.number_of_vertices()];
let mut parent = vec![None; self.number_of_vertices()];
for root_node in 0..self.number_of_vertices() {
if discovery_state[root_node] == DFSTraversalState::Undiscovered {
// Call into a recursive function
self.inner_dfs(&mut process_vertex_early,
&mut process_vertex_late,
&mut process_edge,
&mut discovery_state,
&mut parent,
0usize,
root_node);
}
};
}
// Recursive part of DFS
fn inner_dfs<F, G, H>(&self,
process_vertex_early : &mut F,
process_vertex_late : &mut G,
process_edge : &mut H,
discovery_state : &mut Vec<DFSTraversalState>,
parent : &mut Vec<Option<usize>>,
time : usize,
current_node : usize) -> usize // Returns the exit time + 1
where F : FnMut(&T) -> (), G : FnMut(&T) -> (),
H : FnMut(&T, &T, DFSEdgeType, &Vec<Option<usize>>) -> () {
process_vertex_early(&self.nodes[current_node]);
let entry_time : usize = time;
let mut running_time = time + 1;
discovery_state[current_node] = DFSTraversalState::Processing(entry_time);
running_time += 1;
for dest_node in &self.adjacency_list[current_node] {
match discovery_state[*dest_node] {
DFSTraversalState::Undiscovered => {
parent[*dest_node] = Some(current_node);
process_edge(&self.nodes[current_node], &self.nodes[*dest_node], DFSEdgeType::Tree, &parent);
running_time = self.inner_dfs(process_vertex_early,
process_vertex_late,
process_edge,
discovery_state,
parent,
running_time,
*dest_node);
},
DFSTraversalState::Processing(_) => {
if parent[current_node] != Some(*dest_node) || self.is_directed() {
process_edge(&self.nodes[current_node], &self.nodes[*dest_node], DFSEdgeType::Back, &parent);
}
},
DFSTraversalState::Processed(dest_entry_time, _) => {
if self.is_directed() {
if dest_entry_time > entry_time {
process_edge(&self.nodes[current_node], &self.nodes[*dest_node], DFSEdgeType::Forward, &parent);
} else {
process_edge(&self.nodes[current_node], &self.nodes[*dest_node], DFSEdgeType::Cross, &parent);
}
}
},
}
}
discovery_state[current_node] = DFSTraversalState::Processed(entry_time, running_time);
running_time += 1;
process_vertex_late(&self.nodes[current_node]);
// Return the next time available for use
running_time
}
}
|
#[get("/")]
pub fn other() -> &'static str {
"yolo!"
}
|
use crate::traits::CkbChainInterface;
use ckb_std::error::SysError;
use ckb_std::high_level::load_tx_hash;
pub struct CKBChain {}
impl CkbChainInterface for CKBChain {
fn load_tx_hash(&self) -> Result<[u8; 32], SysError> {
load_tx_hash()
}
}
|
use std::cmp::{max, min};
use std::fmt;
///A Player is either Order or Chaos.
#[derive(Ord, PartialOrd, Eq, PartialEq, Copy, Clone, Debug)]
pub enum Player {
Order,
Chaos,
}
impl Player {
///Print out the current player type.
pub fn display(&self) -> &'static str {
match self {
Player::Order => "Order",
Player::Chaos => "Chaos",
}
}
///Get the type of the other player.
pub fn other_player(&self) -> Self {
match self {
Player::Order => Player::Chaos,
Player::Chaos => Player::Order,
}
}
}
///A game of Order and Chaos may be in progress, or won by either player.
#[derive(Debug, Eq, PartialEq)]
pub enum GameStatus {
InProgress,
OrderWins,
ChaosWins,
}
///A move in Order and Chaos is either placing an X piece or an O piece.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MoveType {
X,
O,
}
const SIZE: usize = 6;
///A move consists of a piece and a location in the board.
#[derive(Clone, Copy, Debug)]
pub struct Move {
mov_type: MoveType,
row: usize,
col: usize,
}
impl Move {
///Creates a new move with the specified MoveType and location.
pub fn new(mov_type: MoveType, row: usize, col: usize) -> Self {
Move {
mov_type,
row,
col,
}
}
}
///Defines directions for checking if the game is in a won state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BoardDirection {
Row,
Column,
Diagonal,
AntiDiagonal,
}
///A game of order and chaos.
#[derive(Clone)]
pub struct Game {
size: usize,
num_to_win: usize,
board: [[Option<MoveType>; SIZE]; SIZE],
pieces_placed: usize,
last_move: Option<(usize, usize)>,
}
impl Game {
///Create a new game.
pub fn new() -> Self {
Game {
size: SIZE,
board: [[None; SIZE];SIZE],
pieces_placed: 0,
num_to_win: 5,
last_move: None,
}
}
///Return the coordinates of the last move made. Returns none if the game is over.
pub fn last_move(&self) -> Option<(usize, usize)> {
self.last_move.clone()
}
///Query the board for the Piece at a given location.
pub fn index(&self, row: usize, col: usize) -> Option<MoveType> {
self.board[row][col].clone()
}
///Get the size of the board.
pub fn size(&self) -> usize {
self.size
}
///Get the number of like pieces in a given direction.
fn num_consecutive(to_search: usize, f: impl Fn(usize) -> Option<MoveType>) -> usize {
let mut max_count = 0;
let mut count = 0;
let mut cell_type = MoveType::X;
for i in 0..to_search {
count = match f(i) {
Some(cell) => {
if cell == cell_type {
count + 1
} else {
max_count = max(count, max_count);
cell_type = cell;
1
}
}
None => {
max_count = max(count, max_count);
0
}
}
}
max(count, max_count)
}
///Counts the number of like pieces in a given direction on the board. Used
///to determine whether a win state has been reached.
pub fn count_direction(&self, direction: BoardDirection, row: usize, col: usize) -> usize {
//There are only 6 diagonals that allow for a win condition for Order,
//Use the coordinates of the last move to determine if the move is on
//one of these diagonals and if so, how many cells need to be checked
let diag_min = min(col, row);
let diag_search = match row as i64 - col as i64 {
-1 => 5,
0 => 6,
1 => 5,
_ => 0,
};
let anti_diag_min = min(col, self.size - row - 1);
let anti_diag_search = match row + col {
4 => 5,
5 => 6,
6 => 5,
_ => 0,
};
match direction {
BoardDirection::Row => Self::num_consecutive(self.size, &|i| self.index(row, i)),
BoardDirection::Column => Self::num_consecutive(self.size, &|i| self.index(i, col)),
BoardDirection::Diagonal => Self::num_consecutive(diag_search, &|i| {
self.index(row + i - diag_min, col + i - diag_min)
}),
BoardDirection::AntiDiagonal => Self::num_consecutive(anti_diag_search, &|i| {
self.index(row + anti_diag_min - i, col + i - anti_diag_min)
}),
}
}
///Get an iterator over the open spaces in the game.
pub fn open_indices(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
self.board
.iter()
.enumerate()
.flat_map(|(x, row)| row.iter()
.enumerate()
.flat_map(move |(y, column)| match column {
Some(_) => None,
None => Some((x, y)),
}))
}
///Query the status of the game. Indicates if a player won or if the game still in progress.
pub fn get_status(&self) -> GameStatus {
// No move has been made yet (or the invariant is broken...)
let (col, row) = match self.last_move {
Some(pair) => pair,
None => return GameStatus::InProgress,
};
// Short-circuit if we can
if self.num_to_win > self.pieces_placed {
return GameStatus::InProgress;
}
// Could return Chaos victory earlier if Order cannot win
if self.pieces_placed == self.size * self.size {
return GameStatus::ChaosWins;
}
if self.count_direction(BoardDirection::Row, row, col) == self.num_to_win
|| self.count_direction(BoardDirection::Column, row, col) == self.num_to_win
|| self.count_direction(BoardDirection::Diagonal, row, col) == self.num_to_win
|| self.count_direction(BoardDirection::AntiDiagonal, row, col) == self.num_to_win
{
return GameStatus::OrderWins;
}
GameStatus::InProgress
}
///Places a piece with a location specified by the move into the game. Returns none if the game
/// has been won or if the move is invalid.
pub fn make_move(&self, m: Move) -> Option<Game> {
if self.index(m.row, m.col).is_some() || self.get_status() != GameStatus::InProgress {
None
} else {
let mut new_board = self.board.clone();
new_board[m.row][m.col] = Some(m.mov_type);
Some(Game {
size: self.size,
num_to_win: self.num_to_win,
board: new_board,
pieces_placed: self.pieces_placed + 1,
last_move: Some((m.col, m.row)),
})
}
}
}
impl fmt::Display for Game {
///Command line representation of the game. Useful for visualizing AI moves, or tests on Travis.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, " {} {} {} {} {} {}", 0, 1, 2, 3, 4, 5)?;
writeln!(f, " ------------------------------")?;
for row in 0..self.size {
write!(f, "{}", row)?;
for col in 0..self.size {
if let Some(cell) = self.index(row, col) {
write!(f, " | {:?} ", cell)?;
} else {
write!(f, " | ")?;
}
}
write!(f, "| ")?;
writeln!(f, "\n ------------------------------")?;
}
Ok(())
}
}
///Provides the strategy for an AI player to play the game. A new AI player can
/// be implemented simply by defining a new implementation for ai_move.
pub trait Strategy {
///Specified computer player makes a move in the current game.
fn ai_move(&self, player: Player) -> Self;
}
#[cfg(test)]
mod test {
use super::{Game, GameStatus, Move, MoveType};
#[test]
fn test_horizontal_win_left() {
let mut game = Game::new();
let x = MoveType::X;
game = game.make_move(Move::new(x, 0, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 2, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 4, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_horizontal_win_right() {
let mut game = Game::new();
let x = MoveType::X;
game = game.make_move(Move::new(x, 5, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 4, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 2, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_vertical_win_up() {
let mut game = Game::new();
let x = MoveType::X;
game = game.make_move(Move::new(x, 1, 5)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 4)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_vertical_win_down() {
let mut game = Game::new();
let x = MoveType::X;
game = game.make_move(Move::new(x, 5, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 5, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 5, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 5, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 5, 4)).unwrap();
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_diagonal_win() {
let mut game = Game::new();
let x = MoveType::O;
game = game.make_move(Move::new(x, 0, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 2, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 4, 4)).unwrap();
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_anti_diagonal_win() {
let mut game = Game::new();
let x = MoveType::O;
game = game.make_move(Move::new(x, 4, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 2, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 1, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 4)).unwrap();
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_diagonal_win2() {
let mut game = Game::new();
let x = MoveType::O;
game = game.make_move(Move::new(x, 1, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 2, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 4, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 5)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 5, 4)).unwrap();
assert_eq!(game.get_status(), GameStatus::OrderWins);
}
#[test]
fn test_anti_np_win() {
let mut game = Game::new();
let x = MoveType::X;
let o = MoveType::O;
game = game.make_move(Move::new(x, 1, 0)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(o, 2, 1)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 3, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(o, 4, 3)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(x, 0, 5)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(o, 5, 4)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
game = game.make_move(Move::new(o, 3, 2)).unwrap();
assert_eq!(game.get_status(), GameStatus::InProgress);
}
}
|
mod common;
use std::env;
use std::io::{stdout, Write};
use env_logger;
use rn2xx3::{ConfirmationMode, DataRateEuCn, JoinMode};
fn main() {
env_logger::init();
let args: Vec<String> = env::args().collect();
if args.len() != 6 {
println!("Join the network via OTAA and send an uplink.");
println!(
"Usage: {} <path-to-serial> <appeui> <appkey> <port> <hexdata>",
args[0]
);
println!(
"Example: {} /dev/ttyUSB0 70B3D57ED000XXXX 120EEXXXXXXXXXXXXXXXXXXXXXXXXXXX 10 2342",
args[0]
);
std::process::exit(1);
}
let mut rn = common::init_rn(&args[1]);
// Reset module
println!("Resetting module...");
rn.reset().expect("Could not reset");
// Set keys
println!("Setting keys...");
rn.set_app_eui_hex(&args[2]).expect("Could not set app EUI");
rn.set_app_key_hex(&args[3]).expect("Could not set app key");
// Join
print!("Joining via OTAA...");
stdout().flush().expect("Could not flush stdout");
rn.join(JoinMode::Otaa).expect("Could not join");
println!("OK");
// Set data rate
rn.set_data_rate(DataRateEuCn::Sf9Bw125)
.expect("Could not set data rate");
// Send data
let port: u8 = args[4].parse().expect("Invalid port");
rn.transmit_hex(ConfirmationMode::Unconfirmed, port, &args[5])
.expect("Could not transmit data");
println!("Success.");
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt::Display;
use common_exception::ErrorCode;
use common_exception::Result;
use common_exception::ToErrorCode;
use common_proto_conv::FromToProto;
pub fn serialize_struct<T, ErrFn, CtxFn, D>(
value: &T,
err_code_fn: ErrFn,
context_fn: CtxFn,
) -> Result<Vec<u8>>
where
T: FromToProto + 'static,
T::PB: common_protos::prost::Message + Default,
ErrFn: FnOnce(String) -> ErrorCode + std::marker::Copy,
D: Display,
CtxFn: FnOnce() -> D + std::marker::Copy,
{
let p = value.to_pb().map_err_to_code(err_code_fn, context_fn)?;
let mut buf = vec![];
common_protos::prost::Message::encode(&p, &mut buf).map_err_to_code(err_code_fn, context_fn)?;
Ok(buf)
}
pub fn deserialize_struct<T, ErrFn, CtxFn, D>(
buf: &[u8],
err_code_fn: ErrFn,
context_fn: CtxFn,
) -> Result<T>
where
T: FromToProto,
T::PB: common_protos::prost::Message + Default,
ErrFn: FnOnce(String) -> ErrorCode + std::marker::Copy,
D: Display,
CtxFn: FnOnce() -> D + std::marker::Copy,
{
let p: T::PB =
common_protos::prost::Message::decode(buf).map_err_to_code(err_code_fn, context_fn)?;
let v: T = FromToProto::from_pb(p).map_err_to_code(err_code_fn, context_fn)?;
Ok(v)
}
|
// 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 {
failure::Error,
fidl_fuchsia_paver::{Configuration, PaverRequest, PaverRequestStream},
fidl_fuchsia_sys::LauncherProxy,
fuchsia_async as fasync,
fuchsia_component::{
client::AppBuilder,
server::{NestedEnvironment, ServiceFs},
},
fuchsia_zircon::Status,
futures::{future::BoxFuture, prelude::*},
parking_lot::Mutex,
std::sync::Arc,
};
const PARTITION_MARKER_CMX: &str = "fuchsia-pkg://fuchsia.com/mark-active-configuration-healthy-tests#meta/mark-active-configuration-healthy.cmx";
struct TestEnv {
env: NestedEnvironment,
}
impl TestEnv {
fn launcher(&self) -> &LauncherProxy {
self.env.launcher()
}
fn new(paver_service: Arc<dyn PaverService>) -> Self {
let mut fs = ServiceFs::new();
let paver_service_clone = paver_service.clone();
fs.add_fidl_service(move |stream: PaverRequestStream| {
let paver_service_clone = paver_service_clone.clone();
fasync::spawn(
paver_service_clone
.run_service(stream)
.unwrap_or_else(|e| panic!("error running paver service: {:?}", e)),
)
});
let env = fs
.create_salted_nested_environment("partition_marker_env")
.expect("nested environment to create successfully");
fasync::spawn(fs.collect());
Self { env }
}
async fn run_partition_marker(&self) {
let launcher = self.launcher();
let partition_marker = AppBuilder::new(PARTITION_MARKER_CMX);
let output = partition_marker
.output(launcher)
.expect("partition_marker to launch")
.await
.expect("no errors while waiting for exit");
output.ok().expect("component exited with status code 0");
}
}
#[derive(Debug, PartialEq, Eq)]
enum PaverEvent {
SetActiveConfigurationHealthy,
QueryActiveConfiguration,
SetConfigurationUnbootable { config: Configuration },
}
trait PaverService: Sync + Send {
fn run_service(
self: Arc<Self>,
stream: PaverRequestStream,
) -> BoxFuture<'static, Result<(), Error>>;
}
struct PaverServiceState {
events: Vec<PaverEvent>,
active_config: Configuration,
}
struct PaverServiceSupportsABR {
state: Mutex<PaverServiceState>,
}
impl PaverServiceSupportsABR {
fn new(active_config: Configuration) -> Self {
Self { state: Mutex::new(PaverServiceState { events: Vec::new(), active_config }) }
}
fn set_active_configuration(&self, config: Configuration) {
self.state.lock().active_config = config;
}
fn take_events(&self) -> Vec<PaverEvent> {
std::mem::replace(&mut self.state.lock().events, vec![])
}
}
impl PaverService for PaverServiceSupportsABR {
fn run_service(
self: Arc<Self>,
mut stream: PaverRequestStream,
) -> BoxFuture<'static, Result<(), Error>> {
async move {
while let Some(req) = stream.try_next().await? {
match req {
PaverRequest::SetActiveConfigurationHealthy { responder } => {
self.state.lock().events.push(PaverEvent::SetActiveConfigurationHealthy);
let status = match self.state.lock().active_config {
Configuration::Recovery => Status::NOT_SUPPORTED,
_ => Status::OK,
};
responder.send(status.into_raw()).expect("send ok");
}
PaverRequest::QueryActiveConfiguration { responder } => {
self.state.lock().events.push(PaverEvent::QueryActiveConfiguration);
responder
.send(&mut Ok(self.state.lock().active_config))
.expect("send config");
}
PaverRequest::SetConfigurationUnbootable { responder, configuration } => {
self.state
.lock()
.events
.push(PaverEvent::SetConfigurationUnbootable { config: configuration });
responder.send(Status::OK.into_raw()).expect("send ok");
}
req => panic!("unhandled paver request: {:?}", req),
}
}
Ok(())
}
.boxed()
}
}
// We should call SetConfigurationUnbootable when the device supports ABR and is not in recovery
#[fasync::run_singlethreaded(test)]
async fn test_calls_set_configuration_unbootable() {
// Works when A is active config
let paver_service = Arc::new(PaverServiceSupportsABR::new(Configuration::A));
let env = TestEnv::new(paver_service.clone());
assert_eq!(paver_service.take_events(), Vec::new());
env.run_partition_marker().await;
assert_eq!(
paver_service.take_events(),
vec![
PaverEvent::SetActiveConfigurationHealthy,
PaverEvent::QueryActiveConfiguration,
PaverEvent::SetConfigurationUnbootable { config: Configuration::B }
]
);
// Works when B is active config
paver_service.set_active_configuration(Configuration::B);
assert_eq!(paver_service.take_events(), Vec::new());
env.run_partition_marker().await;
assert_eq!(
paver_service.take_events(),
vec![
PaverEvent::SetActiveConfigurationHealthy,
PaverEvent::QueryActiveConfiguration,
PaverEvent::SetConfigurationUnbootable { config: Configuration::A }
]
);
}
struct PaverServiceDoesNotSupportsABR {
events: Mutex<Vec<PaverEvent>>,
}
impl PaverServiceDoesNotSupportsABR {
fn new() -> Self {
Self { events: Mutex::new(Vec::new()) }
}
fn take_events(&self) -> Vec<PaverEvent> {
std::mem::replace(&mut *self.events.lock(), vec![])
}
}
impl PaverService for PaverServiceDoesNotSupportsABR {
fn run_service(
self: Arc<Self>,
mut stream: PaverRequestStream,
) -> BoxFuture<'static, Result<(), Error>> {
async move {
while let Some(req) = stream.try_next().await? {
match req {
PaverRequest::SetActiveConfigurationHealthy { responder } => {
self.events.lock().push(PaverEvent::SetActiveConfigurationHealthy);
responder.send(Status::NOT_SUPPORTED.into_raw()).expect("send ok");
}
PaverRequest::QueryActiveConfiguration { responder } => {
self.events.lock().push(PaverEvent::QueryActiveConfiguration);
responder.send(&mut Err(Status::NOT_SUPPORTED.into_raw())).expect("send config");
}
PaverRequest::SetConfigurationUnbootable { responder: _, configuration:_ } => {
panic!("SetConfigurationUnbootable should not be called if device doesn't support ABR")
}
req => panic!("unhandled paver request: {:?}", req),
}
}
Ok(())
}.boxed()
}
}
#[fasync::run_singlethreaded(test)]
async fn test_calls_exclusively_set_active_configuration_healthy_when_device_does_not_support_abr()
{
let paver_service = Arc::new(PaverServiceDoesNotSupportsABR::new());
let env = TestEnv::new(paver_service.clone());
assert_eq!(paver_service.take_events(), Vec::new());
env.run_partition_marker().await;
assert_eq!(paver_service.take_events(), vec![PaverEvent::SetActiveConfigurationHealthy]);
}
#[fasync::run_singlethreaded(test)]
async fn test_calls_exclusively_set_active_configuration_healthy_when_device_in_recovery() {
let paver_service = Arc::new(PaverServiceSupportsABR::new(Configuration::Recovery));
let env = TestEnv::new(paver_service.clone());
assert_eq!(paver_service.take_events(), Vec::new());
env.run_partition_marker().await;
assert_eq!(paver_service.take_events(), vec![PaverEvent::SetActiveConfigurationHealthy]);
}
|
/// running code on cleanup with the `Drop` trait
#[derive(Debug)]
pub struct CustomSmartPointer {
pub data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.