text stringlengths 8 4.13M |
|---|
// TODO: [Object] Type Validation: §4 (interfaces) for objects
// TODO: [Non-Null] §1 A Non‐Null type must not wrap another Non‐Null type.
#[rustversion::nightly]
#[test]
fn test_failing_compilation() {
let t = trybuild::TestCases::new();
t.compile_fail("fail/**/*.rs");
}
|
#![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 IRadio(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IRadio {
type Vtable = IRadio_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x252118df_b33e_416a_875f_1cf38ae2d83e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IRadio_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, value: RadioState, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eventcookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut RadioState) -> ::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 RadioKind) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IRadioStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IRadioStatics {
type Vtable = IRadioStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5fb6a12e_67cb_46ae_aae9_65919f86eff4);
}
#[repr(C)]
#[doc(hidden)]
pub struct IRadioStatics_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 = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, deviceid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[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)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct Radio(pub ::windows::core::IInspectable);
impl Radio {
#[cfg(feature = "Foundation")]
pub fn SetStateAsync(&self, value: RadioState) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<RadioAccessStatus>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<RadioAccessStatus>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn StateChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<Radio, ::windows::core::IInspectable>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveStateChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, eventcookie: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), eventcookie.into_param().abi()).ok() }
}
pub fn State(&self) -> ::windows::core::Result<RadioState> {
let this = self;
unsafe {
let mut result__: RadioState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RadioState>(result__)
}
}
pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Kind(&self) -> ::windows::core::Result<RadioKind> {
let this = self;
unsafe {
let mut result__: RadioKind = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RadioKind>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn GetRadiosAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Radio>>> {
Self::IRadioStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<Radio>>>(result__)
})
}
pub fn GetDeviceSelector() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IRadioStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn FromIdAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(deviceid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<Radio>> {
Self::IRadioStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), deviceid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<Radio>>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn RequestAccessAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<RadioAccessStatus>> {
Self::IRadioStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<RadioAccessStatus>>(result__)
})
}
pub fn IRadioStatics<R, F: FnOnce(&IRadioStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Radio, IRadioStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for Radio {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Radios.Radio;{252118df-b33e-416a-875f-1cf38ae2d83e})");
}
unsafe impl ::windows::core::Interface for Radio {
type Vtable = IRadio_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x252118df_b33e_416a_875f_1cf38ae2d83e);
}
impl ::windows::core::RuntimeName for Radio {
const NAME: &'static str = "Windows.Devices.Radios.Radio";
}
impl ::core::convert::From<Radio> for ::windows::core::IUnknown {
fn from(value: Radio) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&Radio> for ::windows::core::IUnknown {
fn from(value: &Radio) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for Radio {
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 Radio {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<Radio> for ::windows::core::IInspectable {
fn from(value: Radio) -> Self {
value.0
}
}
impl ::core::convert::From<&Radio> for ::windows::core::IInspectable {
fn from(value: &Radio) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for Radio {
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 Radio {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for Radio {}
unsafe impl ::core::marker::Sync for Radio {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct RadioAccessStatus(pub i32);
impl RadioAccessStatus {
pub const Unspecified: RadioAccessStatus = RadioAccessStatus(0i32);
pub const Allowed: RadioAccessStatus = RadioAccessStatus(1i32);
pub const DeniedByUser: RadioAccessStatus = RadioAccessStatus(2i32);
pub const DeniedBySystem: RadioAccessStatus = RadioAccessStatus(3i32);
}
impl ::core::convert::From<i32> for RadioAccessStatus {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RadioAccessStatus {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for RadioAccessStatus {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Radios.RadioAccessStatus;i4)");
}
impl ::windows::core::DefaultType for RadioAccessStatus {
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 RadioKind(pub i32);
impl RadioKind {
pub const Other: RadioKind = RadioKind(0i32);
pub const WiFi: RadioKind = RadioKind(1i32);
pub const MobileBroadband: RadioKind = RadioKind(2i32);
pub const Bluetooth: RadioKind = RadioKind(3i32);
pub const FM: RadioKind = RadioKind(4i32);
}
impl ::core::convert::From<i32> for RadioKind {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RadioKind {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for RadioKind {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Radios.RadioKind;i4)");
}
impl ::windows::core::DefaultType for RadioKind {
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 RadioState(pub i32);
impl RadioState {
pub const Unknown: RadioState = RadioState(0i32);
pub const On: RadioState = RadioState(1i32);
pub const Off: RadioState = RadioState(2i32);
pub const Disabled: RadioState = RadioState(3i32);
}
impl ::core::convert::From<i32> for RadioState {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RadioState {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for RadioState {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Radios.RadioState;i4)");
}
impl ::windows::core::DefaultType for RadioState {
type DefaultType = Self;
}
|
use std::io::{Read, BufReader, Seek, Error as IOError, Result as IOResult, SeekFrom};
use package_entry::PackageEntry;
use std::collections::HashMap;
use archive_md5_section_entry::ArchiveMD5SectionEntry;
use read_util::{PrimitiveRead, StringRead, StringReadError, RawDataRead};
use crc::{self, Crc};
use utilities::AsnKeyParser;
use rsa::{BigUint, PaddingScheme, PublicKey, Pkcs1v15Encrypt};
use rand::rngs::OsRng;
use std::sync::Mutex;
#[derive(Debug)]
pub enum PackageError {
IOError(IOError),
FileError(String)
}
pub struct Package<R>
where R : Read + Seek {
reader: Mutex<R>,
is_dir_vpk: bool,
header_size: u32,
/// The file name
file_name: String,
/// The VPK version
version: u32,
/// The size in bytes of the directory tree.
tree_size: u32,
/// How many bytes of file content are stored in this VPK file (0 in CSGO)
file_data_section_size: u32,
/// The size in bytes of the section containing MD5 checksums for external archive content
archive_md5_section_size: u32,
/// The size in bytes of the section containing MD5 checksums for content in this file
other_md5_section_size: u32,
/// The size in bytes of the section containing the public key and signature
signature_section_size: u32,
/// The MD5 checksum of the file tree
tree_checksum: [u8; 16],
/// The MD5 checksum of the archive MD5 checksum section entries.
archive_md5_entries_checksum: [u8; 16],
/// The MD5 checksum of the complete package until the signature structure
whole_file_checksum: [u8; 16],
/// The public key
public_key: Box<[u8]>,
/// The signature
signature: Box<[u8]>,
/// The package entries
entries: HashMap<String, Vec<PackageEntry>>,
/// The archive MD5 checksum section entries. Also known as cache line hashes.
archive_md5_entries: Vec<ArchiveMD5SectionEntry>,
archive_files: Mutex<HashMap<u16, BufReader<R>>>
}
pub const MAGIC: u32 = 0x55AA1234;
/// Always '/' as per Valve's vpk implementation.
pub const DIRECTORY_SEPARATOR: &str = "/";
impl<R> Package<R>
where R : Read + Seek {
/// Gets the File Name
pub fn file_name(&self) -> &str {
self.file_name.as_str()
}
/// Gets the VPK version.
pub fn version(&self) -> u32 {
self.version
}
/// Gets the size in bytes of the directory tree.
pub fn tree_size(&self) -> u32 {
self.tree_size
}
/// Gets how many bytes of file content are stored in this VPK file (0 in CSGO).
pub fn file_data_section_size(&self) -> u32 {
self.file_data_section_size
}
/// Gets the size in bytes of the section containing MD5 checksums for external archive content.
pub fn archive_md5_section_size(&self) -> u32 {
self.archive_md5_section_size
}
/// Gets the size in bytes of the section containing MD5 checksums for content in this file.
pub fn other_md5_section_size(&self) -> u32 {
self.other_md5_section_size
}
/// Gets the size in bytes of the section containing MD5 checksums for content in this file.
pub fn signature_section_size(&self) -> u32 {
self.signature_section_size
}
/// Gets the MD5 checksum of the file tree.
pub fn tree_checksum(&self) -> &[u8] {
&self.tree_checksum
}
/// Gets the MD5 checksum of the archive MD5 checksum section entries.
pub fn archive_md5_entries_checksum(&self) -> &[u8] {
&self.archive_md5_entries_checksum
}
/// Gets the MD5 checksum of the complete package until the signature structure.
pub fn whole_file_checksum(&self) -> &[u8] {
&self.whole_file_checksum
}
/// Gets the public key.
pub fn public_key(&self) -> &[u8] {
&self.public_key
}
/// Gets the signature.
pub fn signature(&self) -> &[u8] {
&self.signature
}
/// Gets the package entries.
pub fn entries(&self) -> &HashMap<String, Vec<PackageEntry>> {
&self.entries
}
/// Gets the archive MD5 checksum section entries. Also known as cache line hashes.
pub fn archive_md5_entries(&self) -> &Vec<ArchiveMD5SectionEntry> {
&self.archive_md5_entries
}
pub fn sanitize_file_name(file_name: &str) -> (String, bool) {
let lower_file_name = file_name.to_lowercase();
let mut file_name_str = lower_file_name.as_str();
if file_name_str.ends_with(".vpk") {
file_name_str = &file_name[0 .. file_name_str.len() - 4];
}
if file_name_str.ends_with("_dir") {
return (file_name_str[0 .. file_name_str.len() - 4].to_string(), true);
}
(file_name_str.to_string(), false)
}
pub fn read<F: 'static + Send + Sync + Fn(&str) -> IOResult<R>>(file_name: &str, mut input: R, open_file_callback: F) -> Result<Self, PackageError> {
let (file_name, is_dir_vpk) = Self::sanitize_file_name(file_name);
if input.read_u32().map_err(PackageError::IOError)? != MAGIC {
return Err(PackageError::FileError("Given file is not a VPK.".to_string()));
}
let version = input.read_u32().map_err(PackageError::IOError)?;
let tree_size = input.read_u32().map_err(PackageError::IOError)?;
let (file_data_section_size,
archive_md5_section_size,
other_md5_section_size,
signature_section_size) =
if version == 1 {
(0u32, 0u32, 0u32, 0u32)
} else if version == 2 {
(
input.read_u32().map_err(PackageError::IOError)?,
input.read_u32().map_err(PackageError::IOError)?,
input.read_u32().map_err(PackageError::IOError)?,
input.read_u32().map_err(PackageError::IOError)?,
)
} else {
return Err(PackageError::FileError(format!("Bad VPK version: {}", version)));
};
let header_size = input.seek(SeekFrom::Current(0)).map_err(PackageError::IOError)? as u32;
let entries = Self::read_entries(&mut input)?;
let mut archive_files = HashMap::<u16, BufReader<R>>::new();
for (_name, entries) in &entries {
for entry in entries {
if archive_files.contains_key(&entry.archive_index) {
continue;
}
let file_name = format!("{}_{:03}.vpk", file_name, entry.archive_index);
let file = (open_file_callback)(&file_name);
if file.is_err() {
// apparently broken entries are a thing and supposed to be ignored I guess
continue;
}
archive_files.insert(entry.archive_index, BufReader::new(file.map_err(PackageError::IOError)?));
}
}
let (archive_md5_entries, tree_checksum, archive_md5_entries_checksum, whole_file_checksum, public_key, signature) =
if version == 2 {
input.seek(SeekFrom::Current(file_data_section_size as i64)).map_err(PackageError::IOError)?;
let archive_md5_entries = Self::read_archive_md5_section(&mut input, archive_md5_section_size)?;
let (tree_checksum, archive_md5_entries_checksum, whole_file_checksum) = Self::read_other_md5_section(&mut input, other_md5_section_size)?;
let (public_key, signature) = Self::read_signature_section(&mut input, signature_section_size)?;
(archive_md5_entries, tree_checksum, archive_md5_entries_checksum, whole_file_checksum, public_key, signature)
} else {
Default::default()
};
Ok(Self {
reader: Mutex::new(input),
is_dir_vpk,
header_size,
file_name,
version,
tree_size,
file_data_section_size,
archive_md5_section_size,
other_md5_section_size,
signature_section_size,
tree_checksum,
archive_md5_entries_checksum,
whole_file_checksum,
public_key,
signature,
entries,
archive_md5_entries,
archive_files: Mutex::new(archive_files)
})
}
/// Searches for a given file entry in the file list.
pub fn find_entry(&self, file_path: &str) -> Option<&PackageEntry> {
let file_path = file_path.replace("\\", DIRECTORY_SEPARATOR).to_lowercase();
let last_separator = file_path.rfind(DIRECTORY_SEPARATOR);
let (file_name, directory) = if let Some(last_separator) = last_separator {
(&file_path[last_separator + 1 ..], &file_path[.. last_separator])
} else {
(file_path.as_str(), "")
};
self.find_entry_in_dir(directory, file_name)
}
/// Searches for a given file entry in the file list.
pub fn find_entry_in_dir(&self, directory: &str, file_name: &str) -> Option<&PackageEntry> {
let dot = file_name.rfind('.');
let (file_name, extension) = if let Some(dot) = dot {
(&file_name[.. dot], &file_name[dot + 1 ..])
} else {
(file_name, "")
};
self.find_entry_in_dir_with_extension(directory, file_name, extension)
}
pub fn find_entry_in_dir_with_extension(&self, directory: &str, file_name: &str, file_extension: &str) -> Option<&PackageEntry> {
if !self.entries.contains_key(file_extension) {
return None;
}
// We normalize path separators when reading the file list
// And remove the trailing slash
let directory_separator_char: char = DIRECTORY_SEPARATOR.parse().unwrap();
let directory = directory.replace('\\', DIRECTORY_SEPARATOR);
let mut trimmed_directory = directory.trim_matches(directory_separator_char);
// If the directory is empty after trimming, set it to a space to match Valve's behaviour
if trimmed_directory.is_empty() {
trimmed_directory = " ";
}
self.entries[file_extension].iter().find(|x| x.directory_name.as_str() == trimmed_directory && x.file_name.as_str() == file_name)
}
pub fn read_entry(&self, entry: &PackageEntry, validate_crc: bool) -> Result<Box<[u8]>, PackageError> {
let output_size = entry.small_data.len() + entry.len as usize;
let mut output = Vec::with_capacity(output_size);
unsafe { output.set_len(output_size); }
if entry.small_data.len() > 0 {
output[.. entry.small_data.len()].copy_from_slice(&entry.small_data);
}
if entry.len > 0 {
if entry.archive_index != 0x7FFF {
if !self.is_dir_vpk {
return Err(PackageError::FileError("Given VPK is not a _dir, but entry is referencing an external archive.".to_string()));
}
let offset = entry.offset;
let mut files = self.archive_files.lock().unwrap();
let file = files.get_mut(&entry.archive_index).unwrap();
file.seek(SeekFrom::Start(offset as u64)).map_err(PackageError::IOError)?;
file.read_exact(&mut output[entry.small_data.len() .. entry.small_data.len() + entry.len as usize]).map_err(PackageError::IOError)?;
} else {
let offset = self.header_size + self.tree_size + entry.offset;
let mut reader = self.reader.lock().unwrap();
reader.seek(SeekFrom::Start(offset as u64)).map_err(PackageError::IOError)?;
reader.read_exact(&mut output[entry.small_data.len() .. entry.small_data.len() + entry.len as usize]).map_err(PackageError::IOError)?;
}
}
let crc = Crc::<u32>::new(&crc::CRC_32_ISCSI);
if validate_crc && entry.crc32 != crc.checksum(&output) {
return Err(PackageError::FileError("CRC32 mismatch for read data.".to_string()));
}
Ok(output.into_boxed_slice())
}
fn read_entries(input: &mut R) -> Result<HashMap<String, Vec<PackageEntry>>, PackageError> {
let mut type_entries = HashMap::<String, Vec<PackageEntry>>::new();
'types: loop {
let type_name = input.read_null_terminated_string().map_err(|e| match e {
StringReadError::IOError(e) => PackageError::IOError(e),
StringReadError::StringConstructionError(_) => PackageError::FileError("Failed to read type name".to_string())
})?;
if type_name.is_empty() {
break 'types;
}
let mut entries = Vec::<PackageEntry>::new();
'entries: loop {
let directory_name = input.read_null_terminated_string().map_err(|e| match e {
StringReadError::IOError(e) => PackageError::IOError(e),
StringReadError::StringConstructionError(_) => PackageError::FileError("Failed to read type name".to_string())
})?;
if directory_name.is_empty() {
break 'entries;
}
'files: loop {
let file_name = input.read_null_terminated_string().map_err(|e| match e {
StringReadError::IOError(e) => PackageError::IOError(e),
StringReadError::StringConstructionError(_) => PackageError::FileError("Failed to read type name".to_string())
})?;
if file_name.is_empty() {
break 'files;
}
let crc32 = input.read_u32().map_err(PackageError::IOError)?;
let small_data_len = input.read_u16().map_err(PackageError::IOError)? as usize;
let archive_index = input.read_u16().map_err(PackageError::IOError)?;
let offset = input.read_u32().map_err(PackageError::IOError)?;
let len = input.read_u32().map_err(PackageError::IOError)?;
let mut entry = PackageEntry {
file_name: file_name.to_lowercase(),
directory_name: directory_name.to_lowercase(),
type_name: type_name.to_lowercase(),
crc32,
small_data: Vec::new().into_boxed_slice(),
archive_index,
offset,
len
};
if input.read_u16().map_err(PackageError::IOError)? != 0xFFFF {
return Err(PackageError::FileError("Invalid terminator.".to_string()));
}
if small_data_len > 0 {
entry.small_data = input.read_data(small_data_len).map_err(PackageError::IOError)?;
}
entries.push(entry);
}
}
type_entries.insert(type_name, entries);
}
Ok(type_entries)
}
/// Verify checksums and signatures provided in the VPK
pub fn verify_hashes(&self) -> Result<(), PackageError> {
if self.version != 2 {
return Err(PackageError::FileError("Only version 2 is supported.".to_string()));
}
{
let mut reader = self.reader.lock().unwrap();
reader.seek(SeekFrom::Start(0)).map_err(PackageError::IOError)?;
let mut buffer = reader.read_data((self.header_size + self.tree_size + self.file_data_section_size + self.archive_md5_section_size + 32) as usize).map_err(PackageError::IOError)?;
let mut hash = md5::compute(&buffer);
if hash.0 != self.whole_file_checksum {
return Err(PackageError::FileError(format!("Package checksum mismatch ({:?} != expected {:?}).", &hash, &self.whole_file_checksum)));
}
reader.seek(SeekFrom::Start((self.header_size + self.tree_size + self.file_data_section_size) as u64)).map_err(PackageError::IOError)?;
reader.read_exact(&mut buffer[..self.archive_md5_section_size as usize]).map_err(PackageError::IOError)?;
hash = md5::compute(&buffer[..self.archive_md5_section_size as usize]);
if hash.0 != self.whole_file_checksum {
return Err(PackageError::FileError(format!("Archive MD5 entries checksum mismatch ({:?} != expected {:?}).", &hash, &self.archive_md5_entries_checksum)));
}
// TODO: verify archive checksums
}
if self.public_key.is_empty() || self.signature.is_empty() {
return Ok(());
}
if !self.is_signature_valid() {
return Err(PackageError::FileError("VPK signature is not valid.".to_string()));
}
Ok(())
}
pub fn is_signature_valid(&self) -> bool {
let mut reader = self.reader.lock().unwrap();
let seek_res = reader.seek(SeekFrom::Start(0));
if seek_res.is_err() {
return false;
}
let mut key_parser = AsnKeyParser::new(&self.public_key);
let parameters_res = key_parser.parse_rsa_public_key();
if parameters_res.is_err() {
return false;
}
let parameters = parameters_res.unwrap();
let public_key_res = rsa::RsaPublicKey::new(BigUint::from_bytes_le(¶meters.modulus), BigUint::from_bytes_le(¶meters.exponent));
if public_key_res.is_err() {
return false;
}
let public_key = public_key_res.unwrap();
let data_res = reader.read_data((self.header_size + self.tree_size + self.file_data_section_size + self.archive_md5_section_size + self.other_md5_section_size) as usize);
if data_res.is_err() {
return false;
}
let data = data_res.unwrap();
let mut rng = OsRng;
let enc_data_res = public_key.encrypt(&mut rng, Pkcs1v15Encrypt, &data);
if enc_data_res.is_err() {
return false;
}
let enc_data = enc_data_res.unwrap();
enc_data[..] == self.signature[..]
}
fn read_archive_md5_section(input: &mut R, archive_md5_section_size: u32) -> Result<Vec<ArchiveMD5SectionEntry>, PackageError> {
let mut archive_md5_entries = Vec::<ArchiveMD5SectionEntry>::new();
if archive_md5_section_size == 0 {
return Ok(archive_md5_entries);
}
let entries = archive_md5_section_size / std::mem::size_of::<ArchiveMD5SectionEntry>() as u32;
for _ in 0..entries {
let mut entry = ArchiveMD5SectionEntry {
archive_index: input.read_u32().map_err(PackageError::IOError)?,
offset: input.read_u32().map_err(PackageError::IOError)?,
length: input.read_u32().map_err(PackageError::IOError)?,
checksum: Default::default()
};
input.read_exact(&mut entry.checksum).map_err(PackageError::IOError)?;
archive_md5_entries.push(entry);
}
Ok(archive_md5_entries)
}
fn read_other_md5_section(input: &mut R, other_md5_section_size: u32) -> Result<([u8; 16], [u8; 16], [u8; 16]), PackageError> {
if other_md5_section_size != 48 {
return Err(PackageError::FileError(format!("Encountered OtherMD5Section with size of {} (should be 48)", other_md5_section_size)));
}
let mut tree_checksum = [0u8; 16];
input.read_exact(&mut tree_checksum).map_err(PackageError::IOError)?;
let mut archive_md5_entries_checksum = [0u8; 16];
input.read_exact(&mut archive_md5_entries_checksum).map_err(PackageError::IOError)?;
let mut whole_file_checksum = [0u8; 16];
input.read_exact(&mut whole_file_checksum).map_err(PackageError::IOError)?;
Ok((tree_checksum, archive_md5_entries_checksum, whole_file_checksum))
}
fn read_signature_section(input: &mut R, signature_section_size: u32) -> Result<(Box<[u8]>, Box<[u8]>), PackageError> {
if signature_section_size == 0 {
return Ok((Vec::new().into_boxed_slice(), Vec::new().into_boxed_slice()));
}
let public_key_size = input.read_u32().map_err(PackageError::IOError)? as usize;
let public_key = input.read_data(public_key_size).map_err(PackageError::IOError)?;
let signature_size = input.read_u32().map_err(PackageError::IOError)? as usize;
let signature = input.read_data(signature_size).map_err(PackageError::IOError)?;
Ok((public_key, signature))
}
}
|
//! LoRa device configuration definitions
/// LoRa mode radio configuration
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct LoRaConfig {
// Preamble length in symbols (defaults to 8)
pub preamble_length: u8,
/// LoRa header configuration, defaults to variable packet length with explicit headers
pub header_type: LoRaHeader,
/// Payload length configuration (or maximum length for variable mode)
pub payload_length: u8,
/// Payload RX CRC configuration (defaults to enabled)
pub crc_mode: LoRaCrc,
/// IQ inversion configuration (defaults to disabled)
pub invert_iq: LoRaIq,
}
impl Default for LoRaConfig {
fn default() -> Self {
Self {
preamble_length: 08,
header_type: LoRaHeader::Explicit,
payload_length: 0x40,
crc_mode: LoRaCrc::Enabled,
invert_iq: LoRaIq::Inverted,
}
}
}
/// LoRa mode channel configuration
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct LoRaChannel {
/// LoRa frequency in Hz (defaults to 2.4GHz)
pub freq: u32,
/// LoRa Spreading Factor (defaults to SF8)
pub sf: LoRaSpreadingFactor,
/// LoRa channel bandwidth (defaults to 200kHz)
pub bw: LoRaBandwidth,
/// LoRa Coding rate (defaults to 4/5)
pub cr: LoRaCodingRate,
}
impl Default for LoRaChannel {
fn default() -> Self {
Self {
freq: 2_440_000_000,
sf: LoRaSpreadingFactor::Sf8,
bw: LoRaBandwidth::Bw200kHz,
cr: LoRaCodingRate::Cr4_5,
}
}
}
/// Spreading factor for LoRa mode
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LoRaSpreadingFactor {
Sf5 = 0x50,
Sf6 = 0x60,
Sf7 = 0x70,
Sf8 = 0x80,
Sf9 = 0x90,
Sf10 = 0xA0,
Sf11 = 0xB0,
Sf12 = 0xC0,
}
/// Bandwidth for LoRa mode
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LoRaBandwidth {
/// 200 kHz bandwidth mode (actually 203.125 kHz)
Bw200kHz = 0x34,
/// 400 kHz bandwidth mode (actually 406.250 kHz)
Bw400kHz = 0x26,
/// 800 kHz bandwidth mode (actually 812.500 kHz)
Bw800kHz = 0x18,
/// 1600 kHz bandwidth mode (actually 1625.000 kHz)
Bw1600kHz = 0x0A,
}
impl LoRaBandwidth {
/// Fetch the bandwidth in Hz for a given bandwidth configuration
pub fn get_bw_hz(&self) -> u32 {
match self {
LoRaBandwidth::Bw200kHz => 203125,
LoRaBandwidth::Bw400kHz => 406250,
LoRaBandwidth::Bw800kHz => 812500,
LoRaBandwidth::Bw1600kHz => 1625000,
}
}
}
/// Coding rates for LoRa mode
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LoRaCodingRate {
/// LoRa coding rate 4/5
Cr4_5 = 0x01,
/// LoRa coding rate 4/6
Cr4_6 = 0x02,
/// LoRa coding rate 4/7
Cr4_7 = 0x03,
/// LoRa coding rate 4/8
Cr4_8 = 0x04,
CrLI_4_5 = 0x05,
CrLI_4_6 = 0x06,
CrLI_4_7 = 0x07,
}
/// CRC mode for LoRa packet types
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LoRaCrc {
Enabled = 0x20,
Disabled = 0x00,
}
/// IQ mode for LoRa packet types
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LoRaIq {
Normal = 0x40,
Inverted = 0x00,
}
/// Header configuration for LoRa packet types
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LoRaHeader {
/// Variable length packets, length header included in packet
Explicit = 0x00,
/// Constant length packets, no length header included in packet
Implicit = 0x80,
}
|
trait Functor {
type Current;
type Target<V>: Functor;
fn fmap<F, V>(self, f: F) -> Self::Target<V>
where F: Fn(Self::Current) -> V;
}
impl<A> Functor for Option<A> {
type Current = A;
type Target<B> = Option<B>;
fn fmap<F, B>(self, f: F) -> Self::Target<B>
where F: Fn(Self::Current) -> B
{
self.map(f)
}
}
fn main() {
let f = |x| x * 2;
let r = Option::fmap(Some(5), f);
println!("{:?}", r);
let r2 = None::<i32>.fmap(f);
println!("{:?}", r2);
let f2 = |x: i32| format!("value-{}", x);
let r3 = Option::fmap(Some(5), f2);
println!("{:?}", r3);
}
|
pub mod constants;
pub mod particle_in_a_box;
pub mod particle_in_a_box_eigenfunction_sampling;
pub mod shared;
|
// Copyright 2020, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use chrono::NaiveDateTime;
use futures::{Stream, StreamExt};
use std::{sync::Arc, time::Duration};
use tari_wallet::transaction_service::handle::TransactionEvent;
use tokio::sync::broadcast::RecvError;
pub const LOG_TARGET: &str = "base_node::app::utils";
/// Asynchronously processes the event stream checking to see if the given tx_id is present or not
/// ## Parameters
/// `event_stream` - The stream of events to search
/// `expected_tx_id` - The transaction id to be searched for
///
/// ## Returns
/// True if found, false otherwise
pub async fn wait_for_discovery_transaction_event<S>(mut event_stream: S, expected_tx_id: u64) -> bool
where S: Stream<Item = Result<Arc<TransactionEvent>, RecvError>> + Unpin {
loop {
match event_stream.next().await {
Some(event_result) => match event_result {
Ok(event) => {
if let TransactionEvent::TransactionDirectSendResult(tx_id, is_success) = &*event {
if *tx_id == expected_tx_id {
break *is_success;
}
}
},
Err(e) => {
log::error!(target: LOG_TARGET, "Error reading from event broadcast channel {:?}", e);
break false;
},
},
None => {
break false;
},
}
}
}
pub fn format_duration_basic(duration: Duration) -> String {
let secs = duration.as_secs();
if secs > 60 {
let mins = secs / 60;
if mins > 60 {
let hours = mins / 60;
format!("{}h {}m {}s", hours, mins % 60, secs % 60)
} else {
format!("{}m {}s", mins, secs % 60)
}
} else {
format!("{}s", secs)
}
}
/// Standard formatting helper function for a NaiveDateTime
pub fn format_naive_datetime(dt: &NaiveDateTime) -> String {
dt.format("%Y-%m-%d %H:%M:%S").to_string()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn formats_duration() {
let s = format_duration_basic(Duration::from_secs(5));
assert_eq!(s, "5s");
let s = format_duration_basic(Duration::from_secs(23 * 60 + 10));
assert_eq!(s, "23m 10s");
let s = format_duration_basic(Duration::from_secs(9 * 60 * 60 + 35 * 60 + 45));
assert_eq!(s, "9h 35m 45s");
}
}
|
// Copyright 2019
// by Centrality Investments Ltd.
// and Parity Technologies (UK) Ltd.
//
// 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 proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::parse::Result;
use crate::{type_def, type_id};
pub fn generate(input: TokenStream2) -> TokenStream2 {
match generate_impl(input) {
Ok(output) => output,
Err(err) => err.to_compile_error(),
}
}
pub fn generate_impl(input: TokenStream2) -> Result<TokenStream2> {
let mut tokens = quote! {};
tokens.extend(type_id::generate_impl(input.clone())?);
tokens.extend(type_def::generate_impl(input)?);
Ok(tokens)
}
|
use super::{sprite_constants::*, FilesystemPath, ResourceVersion, Tags};
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use smart_default::SmartDefault;
create_guarded_uuid!(FrameId);
create_guarded_uuid!(LayerId);
#[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Frame {
/// This is the actual image you'll see in the game.
/// It's a composite of the images below. It's LayerID will
/// always be UUID::default, or 0000...0000, but it's
/// FrameID will always == Self.Id.
pub composite_image: Image,
/// These are the images which compose the composite image.
/// At the minimum, there will be one Image. It's LayerID will
/// correspond to the LayerId of a Sprite above.
pub images: Vec<Image>,
/// This is the path to the sprite parent. It will always have the name
/// of the Sprite name, and the path to the sprite `.yy` file.
pub parent: FilesystemPath,
/// The version of this particular resource.
pub resource_version: ResourceVersion,
/// This is the name of the Frame, which will always be a UUID.
pub name: FrameId,
/// These are the tags affixed to this frame, which is not possible.
#[default(vec![])]
pub tags: Tags,
/// This is the type of Resource.
pub resource_type: ConstGmSpriteFrame,
}
#[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Image {
/// Although named FrameId, this is actually the path to the the parent
/// frame resource. The `name` field will correspond to the `Frame.name`
/// field.
#[serde(rename = "FrameId")]
pub frame_id: FilesystemPath,
/// This always corresponds to the LayerId which this SpriteImage
/// corresponds to. It will be `None` in the case of the
/// `composite_image` field -- otherwise, it will contain a valid path
/// to the parent layer.
#[serde(rename = "LayerId")]
pub layer_id: Option<FilesystemPath>,
/// The version of the resource.
pub resource_version: ResourceVersion,
/// This appears to only ever be two values:
///
/// - `None` for normal images
/// - `Some("composite")` for the composite image.
///
/// It may have other purposes.
pub name: Option<String>,
/// The tags assigned to each image. You can apparently tag an image.
pub tags: Tags,
/// The resource name of the GM Image.
pub resource_type: ConstGmImage,
}
#[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Layer {
/// Defines the visibility of the layer. It will default to true on
/// import. It is changed in the GMS2 Sprite Editor.
pub visible: bool,
/// Defines if the layer is locked to editing. Only has an effect on the
/// GMS2 Sprite Editor.
pub is_locked: bool,
/// Defines the blendmode in the GMS2 editor. @todo Must be typed at a later
/// date.
pub blend_mode: usize,
/// Between 0-100
pub opacity: f64,
/// This is the actual name shown in the GMS2 Sprite Editor.
pub display_name: String,
/// Currently "1.0"
pub resource_version: ResourceVersion,
/// The legacy name of the LayerId.
pub name: LayerId,
/// The tags assigned to each layer.
pub tags: Tags,
/// The name of the Resource Type, which is always "GMImageLayer".
pub resource_type: ConstGmImageLayer,
}
#[derive(
Serialize_repr,
Deserialize_repr,
PartialEq,
Debug,
SmartDefault,
Copy,
Clone,
Eq,
Ord,
PartialOrd,
)]
#[repr(u8)]
pub enum BlendMode {
#[default]
Normal,
Add,
Subtract,
Multiply,
}
|
use aoc2018::*;
fn main() -> Result<(), Error> {
let mut records = Vec::new();
for line in BufReader::new(input!("day4.txt")).lines() {
let line = line?;
let (date, rest) = line.split_at(18);
let date = chrono::NaiveDateTime::parse_from_str(date, "[%Y-%m-%d %H:%M]")?;
records.push((date, rest.trim().to_string()));
}
records.sort_by(|a, b| a.0.cmp(&b.0));
let mut current = 0u32;
let mut asleep = None;
let mut minutes_asleep = HashMap::<_, u32>::new();
let mut guard_asleep_at = HashMap::<_, HashMap<u32, u32>>::new();
let mut minute_asleep = HashMap::<_, HashMap<u32, u32>>::new();
for (date, rest) in records {
if rest.ends_with("begins shift") {
let guard_id = rest
.split(" ")
.nth(1)
.ok_or_else(|| format_err!("no guard id"))?
.trim_matches('#');
current = str::parse(guard_id)?;
asleep = None;
continue;
}
match rest.as_str() {
"falls asleep" => {
asleep = Some(date);
}
"wakes up" => {
let asleep = asleep.as_ref().unwrap();
let count = date.signed_duration_since(asleep.clone()).num_minutes() as u32;
*minutes_asleep.entry(current).or_default() += count;
let mut m = asleep.minute();
for _ in 0..count {
*guard_asleep_at
.entry(current)
.or_default()
.entry(m)
.or_default() += 1;
*minute_asleep
.entry(m)
.or_default()
.entry(current)
.or_default() += 1;
m += 1;
}
}
other => {
panic!("other: {}", other);
}
}
}
let max = minutes_asleep
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1))
.ok_or_else(|| format_err!("no solution found"))?;
let pair = guard_asleep_at
.remove(&max.0)
.unwrap_or_default()
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1))
.ok_or_else(|| format_err!("no solution found"))?;
let mut sleep_min = None;
for (ts, guards) in minute_asleep {
if let Some((guard, times)) = guards.into_iter().max_by(|a, b| a.1.cmp(&b.1)) {
sleep_min = match sleep_min {
Some((ts, guard, max)) if max > times => Some((ts, guard, max)),
Some(_) | None => Some((ts, guard, times)),
};
}
}
let sleep_min = sleep_min.expect("no result found");
assert_eq!(pair.0 * max.0, 19830);
assert_eq!(sleep_min.0 * sleep_min.1, 43695);
Ok(())
}
|
use std::path::Path;
pub const RUST_LINE_COMMENT_TOKEN: &str = "//";
pub const RUST_MULTI_LINE_COMMENT_TOKEN_PAIR: [&str; 2] = ["/*", "*/"];
pub const RUST_LANGUAGE_SERVER: &str = "rust-analyzer";
pub const RUST_FILE_EXTENSIONS: [&str; 1] = ["rs"];
pub const RUST_IDENTIFIER: &str = "rust";
pub const RUST_INDENT_CHARS: [u8; 3] = [b'{', b'(', b'['];
pub const CPP_LINE_COMMENT_TOKEN: &str = "//";
pub const CPP_MULTI_LINE_COMMENT_TOKEN_PAIR: [&str; 2] = ["/*", "*/"];
pub const CPP_LANGUAGE_SERVER: &str = "clangd";
pub const CPP_FILE_EXTENSIONS: [&str; 6] = ["c", "h", "cpp", "hpp", "cc", "cxx"];
pub const CPP_IDENTIFIER: &str = "cpp";
pub const CPP_INDENT_WORDS: [&str; 6] = ["if", "else", "while", "do", "for", "switch"];
pub const CPP_INDENT_CHARS: [u8; 3] = [b'{', b'(', b'['];
pub const PYTHON_LINE_COMMENT_TOKEN: &str = "#";
pub const PYTHON_FILE_EXTENSIONS: [&str; 1] = ["py"];
pub const PYTHON_IDENTIFIER: &str = "python";
pub const PYTHON_INDENT_CHARS: [u8; 1] = [b':'];
pub struct Language {
pub identifier: &'static str,
pub lsp_executable: Option<&'static str>,
pub line_comment_token: Option<&'static str>,
pub multi_line_comment_token_pair: Option<[&'static str; 2]>,
pub indent_words: Option<&'static [&'static str]>,
pub indent_chars: Option<&'static [u8]>,
}
pub const CPP_LANGUAGE: Language = Language {
identifier: CPP_IDENTIFIER,
lsp_executable: Some(CPP_LANGUAGE_SERVER),
line_comment_token: Some(CPP_LINE_COMMENT_TOKEN),
multi_line_comment_token_pair: Some(CPP_MULTI_LINE_COMMENT_TOKEN_PAIR),
indent_words: Some(&CPP_INDENT_WORDS),
indent_chars: Some(&CPP_INDENT_CHARS),
};
pub const RUST_LANGUAGE: Language = Language {
identifier: RUST_IDENTIFIER,
lsp_executable: Some(RUST_LANGUAGE_SERVER),
line_comment_token: Some(RUST_LINE_COMMENT_TOKEN),
multi_line_comment_token_pair: Some(RUST_MULTI_LINE_COMMENT_TOKEN_PAIR),
indent_words: None,
indent_chars: Some(&RUST_INDENT_CHARS),
};
pub const PYTHON_LANGUAGE: Language = Language {
identifier: PYTHON_IDENTIFIER,
lsp_executable: None,
line_comment_token: Some(PYTHON_LINE_COMMENT_TOKEN),
multi_line_comment_token_pair: None,
indent_words: None,
indent_chars: Some(&PYTHON_INDENT_CHARS),
};
pub fn language_from_path(path: &str) -> Option<&'static Language> {
if let Some(os_str) = Path::new(path).extension() {
if let Some(extension) = os_str.to_str() {
if CPP_FILE_EXTENSIONS.contains(&extension) {
return Some(&CPP_LANGUAGE);
} else if RUST_FILE_EXTENSIONS.contains(&extension) {
return Some(&RUST_LANGUAGE);
} else if PYTHON_FILE_EXTENSIONS.contains(&extension) {
return Some(&PYTHON_LANGUAGE);
}
}
}
None
}
|
extern crate bootstrap_rs as bootstrap;
extern crate gl_util as gl;
extern crate parse_obj;
use bootstrap::window::*;
use gl::*;
use gl::context::Context;
use parse_obj::Obj;
fn main() {
// Load mesh file and normalize indices for OpenGL.
let obj = Obj::from_file("examples/epps_head.obj").unwrap();
let mut raw_indices = Vec::new();
for face in obj.position_indices() {
for index in face {
raw_indices.push(*index as u32);
}
}
let mut window = Window::new("gl-util - wireframe example").unwrap();
let context = Context::from_window(&window).unwrap();
let mut vertex_array = VertexArray::with_index_buffer(&context, obj.raw_positions(), &*raw_indices);
vertex_array.set_attrib(
AttributeLocation::from_index(0),
AttribLayout { elements: 4, offset: 0, stride: 0 },
);
'outer: loop {
while let Some(message) = window.next_message() {
match message {
Message::Close => break 'outer,
_ => {},
}
}
context.clear();
DrawBuilder::new(&context, &vertex_array, DrawMode::Triangles)
.polygon_mode(PolygonMode::Line)
.draw();
context.swap_buffers();
}
}
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Since we mark some ABIs as "nounwind" to LLVM, we must make sure that
// we never unwind through them.
// ignore-cloudabi no env and process
// ignore-emscripten no processes
#![feature(unwind_attributes)]
use std::{env, panic};
use std::io::prelude::*;
use std::io;
use std::process::{Command, Stdio};
#[unwind(aborts)]
extern "C" fn panic_in_ffi() {
panic!("Test");
}
fn test() {
let _ = panic::catch_unwind(|| { panic_in_ffi(); });
// The process should have aborted by now.
io::stdout().write(b"This should never be printed.\n");
let _ = io::stdout().flush();
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() > 1 && args[1] == "test" {
return test();
}
let mut p = Command::new(&args[0])
.stdout(Stdio::piped())
.stdin(Stdio::piped())
.arg("test").spawn().unwrap();
assert!(!p.wait().unwrap().success());
}
|
//! A writfield1 buffer, with one or more snapshots.
use arrow::record_batch::RecordBatch;
use data_types::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::{state_machine::persisting::Persisting, traits::Queryable},
query::projection::OwnedProjection,
};
/// An immutable, queryable FSM state containing at least one buffer snapshot.
#[derive(Debug)]
pub(crate) struct Snapshot {
/// Snapshots generated from previous buffer contents.
///
/// 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 Snapshot {
pub(super) fn new(snapshots: Vec<RecordBatch>) -> Self {
assert!(!snapshots.is_empty());
// Compute some summary statistics for query pruning/reuse later.
let row_count = snapshots.iter().map(|v| v.num_rows()).sum();
let timestamp_stats = compute_timenanosecond_min_max(snapshots.iter())
.expect("non-empty batch must contain timestamps");
let schema = merge_record_batch_schemas(&snapshots);
Self {
snapshots,
row_count,
timestamp_stats,
schema,
}
}
}
impl Queryable for Snapshot {
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<Snapshot> {
pub(crate) fn into_persisting(self) -> BufferState<Persisting> {
assert!(!self.state.snapshots.is_empty());
BufferState {
state: Persisting::new(
self.state.snapshots,
self.state.row_count,
self.state.timestamp_stats,
self.state.schema,
),
sequence_numbers: self.sequence_numbers,
}
}
}
|
use std::io::BufferedReader;
use std::io::File;
use std::io::IoError;
use std::collections::HashSet;
#[deriving(Show, Clone)]
pub struct SpeciesProbability {
species: String,
lambda: f64,
}
#[deriving(Show)]
pub struct DecayScenario {
t: i64,
lambdas: Vec<SpeciesProbability>,
}
impl DecayScenario {
pub fn from_file(fpath: &str) -> DecayScenario {
let path = Path::new(fpath);
let mut file = BufferedReader::new(File::open(&path));
let lines: Vec<String> = file.lines().map(clean_string).collect();
let t = from_str(lines[0].as_slice()).unwrap();
let mut lambdas = Vec::new();
let mut decay_chain = lines[1].as_slice().split_str("->");
let mut chain_species_set: HashSet<String> = HashSet::new();
let mut lambda_species_set: HashSet<String> = HashSet::new();
for species in decay_chain {
let trimmed = species.trim_chars(|c: char| c.is_whitespace());
chain_species_set.insert(String::from_str(trimmed));
}
for line in lines.slice(2, lines.len()).iter() {
let line_frags: Vec<&str> = line.as_slice().split_str(":")
.collect();
let specie: String = line_frags[0].trim_chars(
|c: char| c.is_whitespace()).to_string();
let lambda: f64 = from_str(line_frags[1].trim_chars(
|c: char| c.is_whitespace())).unwrap();
lambdas.push(SpeciesProbability { species: specie.clone(), lambda: lambda});
lambda_species_set.insert(specie.clone());
}
if chain_species_set != lambda_species_set {
fail!("Decay chain does not contain the same species as the \
decay probabilities");
}
DecayScenario{t: t, lambdas: lambdas}
}
pub fn simulate(&self) -> Vec<SpeciesProbability>{
let mut accum = self.lambdas.clone();
// initialize simulation structure
for (i, spec_accum) in accum.iter_mut().enumerate() {
spec_accum.lambda = match i {
0 => 1.0,
_ => 0.0,
}
}
for _ in range(0, self.t) {
let mut delta = 0_f64;
for (spec, spec_accum) in self.lambdas.iter().zip(accum.iter_mut()) {
let delta_0 = spec_accum.lambda * spec.lambda;
spec_accum.lambda -= delta_0;
spec_accum.lambda += delta;
delta = delta_0;
}
}
accum
}
}
fn clean_string(s: Result<String, IoError>) -> String {
let string = s.unwrap();
let stripped = string.as_slice().trim_chars(|c: char| c.is_whitespace());
String::from_str(stripped)
}
|
// 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::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct ProgressValues {
pub rows: usize,
pub bytes: usize,
}
#[derive(Debug)]
pub struct Progress {
rows: AtomicUsize,
bytes: AtomicUsize,
}
impl Progress {
pub fn create() -> Self {
Self {
rows: AtomicUsize::new(0),
bytes: AtomicUsize::new(0),
}
}
pub fn incr(&self, progress_values: &ProgressValues) {
self.rows.fetch_add(progress_values.rows, Ordering::Relaxed);
self.bytes
.fetch_add(progress_values.bytes, Ordering::Relaxed);
}
pub fn fetch(&self) -> ProgressValues {
let rows = self.rows.fetch_min(0, Ordering::SeqCst);
let bytes = self.bytes.fetch_min(0, Ordering::SeqCst);
ProgressValues { rows, bytes }
}
pub fn get_values(&self) -> ProgressValues {
let rows = self.rows.load(Ordering::Relaxed);
let bytes = self.bytes.load(Ordering::Relaxed);
ProgressValues { rows, bytes }
}
}
|
extern crate llio;
use llio::{Buff,EventType,Token};
use ::reactor::Handle;
use ::{Context,EventSource,Service};
use std::net::SocketAddrV4;
use std::io::{Result,Read,Write};
use std::marker::PhantomData;
pub struct TcpListener {
inner: llio::TcpListener,
}
impl TcpListener {
pub fn new(addr: SocketAddrV4) -> Result<Self> {
let listener = try!(llio::TcpListener::new(addr));
Ok(TcpListener{inner: listener})
}
}
//FIXME: should we have a transport trait
pub struct TcpStream {
stream: llio::TcpStream,
addr: SocketAddrV4
}
pub struct Connect {
stream: Option<TcpStream>,
token: Token,
handle: Handle,
fd: llio::RawFd
}
pub struct TcpClient<S> {
token: Token,
handle: Handle,
buff: Buff,
fd: llio::RawFd,
service: S
}
pub struct Chain<F,S> {
connect: Connect,
factory: F,
fd: llio::RawFd,
_service: PhantomData<S>
}
impl TcpStream {
pub fn connect(addr: SocketAddrV4, handle: Handle) -> Result<Connect> {
let stream = try!(llio::TcpStream::new());
let _ = try!(stream.nonblock());
let _ = try!(stream.connect(&addr));
let token = try!(handle.new_token());
let fd = stream.fd();
let stream = TcpStream {
stream: stream,
addr: addr
};
let connect = Connect {
stream: Some(stream),
token: token,
handle: handle,
fd: fd
};
Ok(connect)
}
fn has_sock_error(&self) -> Result<()> {
//FIXME: Handle EWOULDBLOCK
self.stream.has_sock_error()
}
}
impl Read for TcpStream {
fn read(&mut self, buff: &mut [u8]) -> Result<usize> {
self.stream.read(buff)
}
}
impl Write for TcpStream {
fn write(&mut self, buff: &[u8]) -> Result<usize> {
self.stream.write(buff)
}
fn flush(&mut self) -> Result<()> {
self.stream.flush()
}
}
impl Connect {
fn process(&mut self, _: &mut Context) -> Result<TcpStream> {
if let Some(ref stream) = self.stream {
stream.has_sock_error()?
};
Ok(self.stream.take().unwrap())
}
pub fn with_service<F,S>(self, factory: F) -> Result<()>
where F: 'static + Fn(TcpStream) -> S
, S: 'static + Service
{
let handle = self.handle.clone();
let token = self.token.clone();
let fd = self.fd;
//Fixme: Should we really be storing the fd in the chain.
// what if the fd has been closed for some reason.
let chain = Chain{ connect: self
, factory: factory
, fd: fd
, _service: PhantomData
};
handle.register(token, EventType::Write, chain)?;
Ok(())
}
}
impl <F,S> EventSource for Chain<F,S>
where F: 'static + Fn(TcpStream) -> S
, S: 'static + Service {
fn process(&mut self, ctx:&mut Context) -> Result<()> {
//Fixme: Notify service if we failed to connect
let stream = try!(self.connect.process(ctx));
let service = (self.factory)(stream);
//FIXME: handle EWOULDBLOCK
let mut handle = self.connect.handle.clone();
let mut client = TcpClient {
token: self.connect.token.clone(),
handle: self.connect.handle.clone(),
buff: Buff::with_capacity(64),
service: service,
fd: self.fd
};
try!(client.service.on_connect());
try!(handle.modify(client.token, EventType::Read, client));
Ok(())
}
fn fd(&self) -> llio::RawFd {
self.fd
}
}
impl <S> EventSource for TcpClient<S>
where S: Service
{
fn process(&mut self, _: &mut Context) -> Result<()> {
use std::io::Read;
let nread = {
let mut transport = self.service.get_transport();
let nread = try!(transport.read(self.buff.as_mut_slice()));
self.buff.advance_write(nread);
nread
};
if nread == 0 {
self.service.on_disconnect();
try!(self.handle.unregister(self.token.clone()));
return Ok(());
}
let len = try!(self.service.process(self.buff.as_slice()));
self.buff.advance_read(len);
Ok(())
}
fn fd(&self) -> llio::RawFd {
self.fd
}
}
|
use std::{fs::File, io::Write, path::PathBuf};
use clap::arg_enum;
use eyre::Result;
use items::Item;
use structopt::StructOpt;
mod items;
mod renderer;
arg_enum! {
#[derive(Debug)]
pub enum CallNumber {
LCC,
Dewey
}
}
#[derive(Debug, StructOpt)]
#[structopt(
name = "librarything_to_barcode_label",
about = "Generate barcode labels from a LibraryThing collection"
)]
pub struct Opt {
#[structopt(
short, long,
possible_values = &CallNumber::variants(),
case_insensitive = true,
default_value = "LCC"
)]
call_number: CallNumber,
#[structopt(parse(from_os_str))]
input: PathBuf,
#[structopt(short, long, parse(from_os_str))]
output: Option<PathBuf>,
#[structopt(short, long)]
start: Option<usize>,
#[structopt(short, long)]
end: Option<usize>,
#[structopt(short, long, default_value = "JetBrains Mono")]
font: String,
}
impl Opt {
pub fn font_url(&self) -> String {
let replaced = self.font.replace(" ", "+");
format!(
"https://fonts.googleapis.com/css2?family={}&display=swap",
replaced
)
}
}
fn main() -> Result<()> {
let opt = Opt::from_args_safe()?;
let item_iter = items::read_items(&opt.input)?;
let items = item_iter.map(Result::unwrap).filter(|item: &Item| {
if let Some(start) = opt.start {
if item.barcode.parse::<usize>().unwrap() < start {
return false;
}
}
if let Some(end) = opt.end {
if item.barcode.parse::<usize>().unwrap() > end {
return false;
}
}
if item.collections.contains("Coming Soon") {
return false;
}
true
});
let rendered = renderer::render_page(items, &opt)?;
if let Some(output) = &opt.output {
let mut file = File::create(output)?;
file.write_all(rendered.as_bytes())?;
} else {
print!("{}", rendered);
}
Ok(())
}
|
use lupo::errors::*;
use std::fs::OpenOptions;
use std::io::prelude::*;
//use pretty_assertions::{assert_eq, assert_ne};
use tempfile::tempdir;
// Can't create this as a standard function because 'store' borrows 'home'
macro_rules! temp_store {
($var:ident, $home:ident, $force:expr) => {
let $home = tempdir().chain_err(|| "Can't create temporary dir")?;
let $var = lupo::Store::new($home.as_ref(), $force)?;
};
}
#[test]
fn can_init_not_existing_store() -> Result<()> {
temp_store!(store, home, false);
let (ct, cs) = store.check()?;
assert_eq!(0, ct);
assert_eq!(0, cs);
Ok(())
}
#[test]
fn can_init_existing_store() -> Result<()> {
temp_store!(_store, home, false);
// add trade
let new_trade = "IB 2015/04/27 TrIn CashIB 1335387 1 0 1 1";
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(home.path().join("trades.tsv"))
.chain_err(|| "Can't open trade file")?;
writeln!(file, "{}", new_trade).chain_err(|| "Can't print to trade file")?;
let (ct, cs) = _store.check()?;
assert_eq!(1, ct);
assert_eq!(0, cs);
let store = lupo::Store::new(home.as_ref(), false)?;
let (ct, cs) = store.check()?;
assert_eq!(1, ct);
assert_eq!(0, cs);
Ok(())
}
#[test]
fn can_init_forcefully_existing_store() -> Result<()> {
temp_store!(_store, home, false);
// add trade
let new_trade = "IB 2015/04/27 TrIn CashIB 1335387 1 0 1 1";
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(home.path().join("trades.tsv"))
.chain_err(|| "Can't open trade file")?;
writeln!(file, "{}", new_trade).chain_err(|| "Can't print to trade file")?;
let (ct, cs) = _store.check()?;
assert_eq!(1, ct);
assert_eq!(0, cs);
// open the store forcefully, should reset the trades
let store = lupo::Store::new(home.as_ref(), true)?;
let (ct, cs) = store.check()?;
assert_eq!(0, ct);
assert_eq!(0, cs);
Ok(())
}
#[test]
fn check_err_if_invalid_trade() -> Result<()> {
temp_store!(_store, home, false);
// add trade
let new_trade = "IB 2015/04/27 XTrIn CashIB 1335387 1 0 1 1";
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(home.path().join("trades.tsv"))
.chain_err(|| "Can't open trade file")?;
writeln!(file, "{}", new_trade).chain_err(|| "Can't print to trade file")?;
let r = _store.check();
assert_eq!(true, r.is_err());
Ok(())
}
|
pub struct Solution;
impl Solution {
pub fn contains_nearby_duplicate(nums: Vec<i32>, k: i32) -> bool {
let k = k as usize;
let mut pairs = nums
.into_iter()
.enumerate()
.map(|(i, v)| (v, i))
.collect::<Vec<_>>();
pairs.sort_unstable();
for i in 1..pairs.len() {
if pairs[i - 1].0 == pairs[i].0 && pairs[i].1 - pairs[i - 1].1 <= k {
return true;
}
}
return false;
}
}
#[test]
fn test0219() {
fn case(nums: Vec<i32>, k: i32, want: bool) {
let got = Solution::contains_nearby_duplicate(nums, k);
assert_eq!(got, want);
}
case(vec![1, 2, 3, 1], 3, true);
case(vec![1, 0, 1, 1], 1, true);
case(vec![1, 2, 3, 1, 2, 3], 2, false);
}
|
//! Defines the operations and data definitions for a top bar program.
use std::ops::Deref;
use rustwlc::WlcView;
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Bar {
view: WlcView
}
impl Bar {
pub fn new(view: WlcView) -> Self {
Bar { view: view }
}
/// Gets the view that is associated with the bar.
pub fn view(&self) -> WlcView {
self.view
}
}
impl Deref for Bar {
type Target = WlcView;
fn deref(&self) -> &Self::Target {
&self.view
}
}
|
use rustc_serialize::json;
use rustc_serialize::json::{Json, Object, Array};
use token::{TokenData, Reserved, Exp, CharCase, Sign, NumberLiteral, Radix, Name};
use ast::*;
use track::*;
macro_rules! right {
( $l:expr, $r:expr ) => { $r }
}
macro_rules! tuplify {
( $v:expr, ( $($dummy:tt),* ) ) => {
{
let mut t = $v.into_iter();
($(
right!($dummy, t.next().unwrap())
),*)
}
};
}
#[derive(Debug)]
pub enum DeserializeError {
WrongJsonType(&'static str, JsonType),
WrongNodeType(&'static str, String),
MissingField(&'static str),
InvalidString(&'static str, String),
InvalidArray(&'static str, json::Array),
InvalidObject(&'static str, json::Object),
InvalidLHS(&'static str),
UninitializedPattern(CompoundPatt),
UnexpectedInitializer(Expr)
}
fn type_error<T>(expected: &'static str, actual: JsonType) -> Deserialize<T> {
Err(DeserializeError::WrongJsonType(expected, actual))
}
fn node_error<T>(expected: &'static str, actual: String) -> Deserialize<T> {
Err(DeserializeError::WrongNodeType(expected, actual))
}
fn string_error<T>(expected: &'static str, actual: String) -> Deserialize<T> {
Err(DeserializeError::InvalidString(expected, actual))
}
fn array_error<T>(expected: &'static str, actual: json::Array) -> Deserialize<T> {
Err(DeserializeError::InvalidArray(expected, actual))
}
fn object_error<T>(expected: &'static str, actual: json::Object) -> Deserialize<T> {
Err(DeserializeError::InvalidObject(expected, actual))
}
pub type Deserialize<T> = Result<T, DeserializeError>;
pub trait MatchJson {
fn into_array(self) -> Deserialize<json::Array>;
fn into_string(self) -> Deserialize<String>;
fn into_string_opt(self) -> Deserialize<Option<String>>;
fn into_name(self) -> Deserialize<Name>;
fn into_object(self) -> Deserialize<Object>;
fn into_object_opt(self) -> Deserialize<Option<Object>>;
fn into_bool(self) -> Deserialize<bool>;
}
pub trait IntoToken {
fn into_char_case(self) -> Deserialize<CharCase>;
fn into_char_case_opt(self) -> Deserialize<Option<CharCase>>;
fn into_exp_opt(self) -> Deserialize<Option<Exp>>;
fn into_token(self) -> Deserialize<TokenData>;
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum JsonType {
Null,
Boolean,
String,
Number,
Object,
Array
}
fn json_typeof(data: &Json) -> JsonType {
match *data {
Json::Null => JsonType::Null,
Json::String(_) => JsonType::String,
Json::Object(_) => JsonType::Object,
Json::I64(_) => JsonType::Number,
Json::U64(_) => JsonType::Number,
Json::F64(_) => JsonType::Number,
Json::Array(_) => JsonType::Array,
Json::Boolean(_) => JsonType::Boolean
}
}
impl MatchJson for Json {
fn into_array(self) -> Deserialize<json::Array> {
match self {
Json::Array(array) => Ok(array),
_ => type_error("array", json_typeof(&self))
}
}
fn into_string(self) -> Deserialize<String> {
match self {
Json::String(string) => Ok(string),
_ => type_error("string", json_typeof(&self))
}
}
fn into_string_opt(self) -> Deserialize<Option<String>> {
match self {
Json::Null => Ok(None),
Json::String(string) => Ok(Some(string)),
_ => type_error("string or null", json_typeof(&self))
}
}
fn into_name(self) -> Deserialize<Name> {
Ok(Name::new(try!(self.into_string())))
}
fn into_object(self) -> Deserialize<json::Object> {
match self {
Json::Object(object) => Ok(object),
_ => type_error("object", json_typeof(&self))
}
}
fn into_object_opt(self) -> Deserialize<Option<Object>> {
match self {
Json::Object(object) => Ok(Some(object)),
Json::Null => Ok(None),
_ => type_error("object or null", json_typeof(&self))
}
}
fn into_bool(self) -> Deserialize<bool> {
match self {
Json::Boolean(val) => Ok(val),
_ => type_error("boolean", json_typeof(&self))
}
}
}
fn validate_token(arr: json::Array) -> Deserialize<json::Array> {
if arr.len() == 0 {
return array_error("array of length > 0", arr);
}
let one = (1, "array of length 1");
let two = (2, "array of length 2");
let three = (3, "array of length 3");
let four = (4, "array of length 4");
let (expected_len, expected_msg) = {
let elt = arr.iter().next().unwrap();
let ty = match elt.as_string() {
None => { return type_error("string", json_typeof(&elt)); },
Some(str) => str
};
match ty {
"Reserved" => two,
"DecimalInt" => three,
"BinaryInt" => three,
"OctalInt" => three,
"HexInt" => three,
"Float" => four,
"String" => two,
"RegExp" => three,
"Identifier" => two,
_ => one
}
};
if arr.len() != expected_len {
return array_error(expected_msg, arr);
}
Ok(arr)
}
impl IntoToken for Json {
fn into_char_case(self) -> Deserialize<CharCase> {
let s = try!(self.into_string());
if s.len() == 0 {
return string_error("lowercase or uppercase letter", s);
}
let ch = s.chars().next().unwrap();
if ch.is_lowercase() {
Ok(CharCase::LowerCase)
} else if ch.is_uppercase() {
Ok(CharCase::UpperCase)
} else {
string_error("lowercase or uppercase letter", s)
}
}
fn into_char_case_opt(self) -> Deserialize<Option<CharCase>> {
match self {
Json::Null => Ok(None),
_ => self.into_char_case().map(Some)
}
}
fn into_exp_opt(self) -> Deserialize<Option<Exp>> {
match self {
Json::Null => Ok(None),
_ => {
let arr = try!(self.into_array());
if arr.len() != 3 {
return array_error("array of length 3", arr);
}
let (e, sign, value) = tuplify!(arr, ((), (), ()));
Ok(Some(Exp {
e: try!(e.into_char_case()),
sign: match try!(sign.into_string_opt()) {
None => None,
Some(s) => {
if s.len() != 1 {
return string_error("'+' or '-'", s);
}
match s.chars().next().unwrap() {
'+' => Some(Sign::Plus),
'-' => Some(Sign::Minus),
_ => { return string_error("'+' or '-'", s); }
}
}
},
value: try!(value.into_string())
}))
}
}
}
fn into_token(self) -> Deserialize<TokenData> {
let mut arr = try!(self.into_array());
// Check the array lengths in an external validation helper.
// This lets us modularize the validation and avoids having to patch
// the array back up to return in the error struct.
arr = try!(validate_token(arr));
let ty = try!(arr.remove(0).into_string());
Ok(match &ty[..] {
"Reserved" => {
let word = try!(arr.remove(0).into_string().and_then(|str| str.into_reserved()));
TokenData::Reserved(word)
}
"LBrace" => TokenData::LBrace,
"RBrace" => TokenData::RBrace,
"LParen" => TokenData::LParen,
"RParen" => TokenData::RParen,
"LBrack" => TokenData::LBrack,
"RBrack" => TokenData::RBrack,
"Dot" => TokenData::Dot,
//"Ellipsis" => TokenData::Ellipsis,
"Semi" => TokenData::Semi,
"Comma" => TokenData::Comma,
"LAngle" => TokenData::LAngle,
"RAngle" => TokenData::RAngle,
"LEq" => TokenData::LEq,
"GEq" => TokenData::GEq,
"Eq" => TokenData::Eq,
"NEq" => TokenData::NEq,
"StrictEq" => TokenData::StrictEq,
"StrictNEq" => TokenData::StrictNEq,
"Plus" => TokenData::Plus,
"Minus" => TokenData::Minus,
"Star" => TokenData::Star,
"Mod" => TokenData::Mod,
"Slash" => TokenData::Slash,
"Inc" => TokenData::Inc,
"Dec" => TokenData::Dec,
"LShift" => TokenData::LShift,
"RShift" => TokenData::RShift,
"URShift" => TokenData::URShift,
"BitAnd" => TokenData::BitAnd,
"BitOr" => TokenData::BitOr,
"BitXor" => TokenData::BitXor,
"Bang" => TokenData::Bang,
"Tilde" => TokenData::Tilde,
"LogicalAnd" => TokenData::LogicalAnd,
"LogicalOr" => TokenData::LogicalOr,
"Question" => TokenData::Question,
"Colon" => TokenData::Colon,
"Assign" => TokenData::Assign,
"PlusAssign" => TokenData::PlusAssign,
"MinusAssign" => TokenData::MinusAssign,
"StarAssign" => TokenData::StarAssign,
"SlashAssign" => TokenData::SlashAssign,
"ModAssign" => TokenData::ModAssign,
"LShiftAssign" => TokenData::LShiftAssign,
"RShiftAssign" => TokenData::RShiftAssign,
"URShiftAssign" => TokenData::URShiftAssign,
"BitAndAssign" => TokenData::BitAndAssign,
"BitOrAssign" => TokenData::BitOrAssign,
"BitXorAssign" => TokenData::BitXorAssign,
"Arrow" => TokenData::Arrow,
"EOF" => TokenData::EOF,
"DecimalInt" => {
let (value, exp) = tuplify!(arr, ((), ()));
let value = try!(value.into_string());
let exp = try!(exp.into_exp_opt());
TokenData::Number(NumberLiteral::DecimalInt(value, exp))
}
"BinaryInt" => {
let (flag, value) = tuplify!(arr, ((), ()));
let flag = try!(flag.into_char_case());
let value = try!(value.into_string());
TokenData::Number(NumberLiteral::RadixInt(Radix::Bin(flag), value))
}
"OctalInt" => {
let (flag, value) = tuplify!(arr, ((), ()));
let flag = try!(flag.into_char_case_opt());
let value = try!(value.into_string());
TokenData::Number(NumberLiteral::RadixInt(Radix::Oct(flag), value))
}
"HexInt" => {
let (flag, value) = tuplify!(arr, ((), ()));
let flag = try!(flag.into_char_case());
let value = try!(value.into_string());
TokenData::Number(NumberLiteral::RadixInt(Radix::Hex(flag), value))
}
"Float" => {
let (int, frac, exp) = tuplify!(arr, ((), (), ()));
let int = try!(int.into_string_opt());
let frac = try!(frac.into_string_opt());
let exp = try!(exp.into_exp_opt());
TokenData::Number(NumberLiteral::Float(int, frac, exp))
}
"String" => TokenData::String(try!(arr.remove(0).into_string())),
"RegExp" => {
let (pattern, flags) = tuplify!(arr, ((), ()));
let pattern = try!(pattern.into_string());
let flags = try!(flags.into_string()).chars().collect();
TokenData::RegExp(pattern, flags)
}
"Identifier" => TokenData::Identifier(try!(arr.remove(0).into_name())),
_ => { return array_error("token", arr); }
})
}
}
pub trait IntoOperator {
fn into_unop(self) -> Deserialize<Unop>;
fn into_binop(self) -> Deserialize<Binop>;
fn into_assop(self) -> Deserialize<Assop>;
fn into_logop(self) -> Deserialize<Logop>;
}
impl IntoOperator for String {
fn into_unop(self) -> Deserialize<Unop> {
Ok((match &self[..] {
"-" => UnopTag::Minus,
"+" => UnopTag::Plus,
"!" => UnopTag::Not,
"~" => UnopTag::BitNot,
"typeof" => UnopTag::Typeof,
"void" => UnopTag::Void,
"delete" => UnopTag::Delete,
_ => { return string_error("unop", self); }
}).tracked(None))
}
fn into_binop(self) -> Deserialize<Binop> {
Ok((match &self[..] {
"==" => BinopTag::Eq,
"!=" => BinopTag::NEq,
"===" => BinopTag::StrictEq,
"!==" => BinopTag::StrictNEq,
"<" => BinopTag::Lt,
"<=" => BinopTag::LEq,
">" => BinopTag::Gt,
">=" => BinopTag::GEq,
"<<" => BinopTag::LShift,
">>" => BinopTag::RShift,
">>>" => BinopTag::URShift,
"+" => BinopTag::Plus,
"-" => BinopTag::Minus,
"*" => BinopTag::Times,
"/" => BinopTag::Div,
"%" => BinopTag::Mod,
"|" => BinopTag::BitOr,
"^" => BinopTag::BitXor,
"&" => BinopTag::BitAnd,
"in" => BinopTag::In,
"instanceof" => BinopTag::Instanceof,
_ => { return string_error("binop", self); }
}).tracked(None))
}
fn into_assop(self) -> Deserialize<Assop> {
Ok((match &self[..] {
"=" => AssopTag::Eq,
"+=" => AssopTag::PlusEq,
"-=" => AssopTag::MinusEq,
"*=" => AssopTag::TimesEq,
"/=" => AssopTag::DivEq,
"%=" => AssopTag::ModEq,
"<<=" => AssopTag::LShiftEq,
">>=" => AssopTag::RShiftEq,
">>>=" => AssopTag::URShiftEq,
"|=" => AssopTag::BitOrEq,
"^=" => AssopTag::BitXorEq,
"&=" => AssopTag::BitAndEq,
_ => { return string_error("assop", self); }
}).tracked(None))
}
fn into_logop(self) -> Deserialize<Logop> {
Ok((match &self[..] {
"||" => LogopTag::Or,
"&&" => LogopTag::And,
_ => { return string_error("logop", self); }
}).tracked(None))
}
}
pub trait IntoReserved {
fn into_reserved(self) -> Deserialize<Reserved>;
}
impl IntoReserved for String {
fn into_reserved(self) -> Deserialize<Reserved> {
Ok(match &self[..] {
"Null" => Reserved::Null,
"True" => Reserved::True,
"False" => Reserved::False,
"Break" => Reserved::Break,
"Case" => Reserved::Case,
"Catch" => Reserved::Catch,
"Class" => Reserved::Class,
"Const" => Reserved::Const,
"Continue" => Reserved::Continue,
"Debugger" => Reserved::Debugger,
"Default" => Reserved::Default,
"Delete" => Reserved::Delete,
"Do" => Reserved::Do,
"Else" => Reserved::Else,
"Export" => Reserved::Export,
"Extends" => Reserved::Extends,
"Finally" => Reserved::Finally,
"For" => Reserved::For,
"Function" => Reserved::Function,
"If" => Reserved::If,
"Import" => Reserved::Import,
"In" => Reserved::In,
"Instanceof" => Reserved::Instanceof,
"New" => Reserved::New,
"Return" => Reserved::Return,
"Super" => Reserved::Super,
"Switch" => Reserved::Switch,
"This" => Reserved::This,
"Throw" => Reserved::Throw,
"Try" => Reserved::Try,
"Typeof" => Reserved::Typeof,
"Var" => Reserved::Var,
"Void" => Reserved::Void,
"While" => Reserved::While,
"With" => Reserved::With,
"Enum" => Reserved::Enum,
_ => { return string_error("keyword", self); }
})
}
}
pub trait IntoNode {
fn into_program(self) -> Deserialize<Script>;
fn into_statement_list_item(self) -> Deserialize<StmtListItem>;
fn into_declarator(self) -> Deserialize<Dtor>;
fn into_statement(self) -> Deserialize<Stmt>;
fn into_expression(self) -> Deserialize<Expr>;
fn into_binary_expression(self) -> Deserialize<Expr>;
fn into_assignment_expression(self) -> Deserialize<Expr>;
fn into_logical_expression(self) -> Deserialize<Expr>;
fn into_unary_expression(self) -> Deserialize<Expr>;
fn into_update_expression(self) -> Deserialize<Expr>;
fn into_member_expression(self) -> Deserialize<Expr>;
fn into_call_expression(self) -> Deserialize<Expr>;
fn into_new_expression(self) -> Deserialize<Expr>;
fn into_array_expression(self) -> Deserialize<Expr>;
fn into_function_expression(self) -> Deserialize<Expr>;
fn into_sequence_expression(self) -> Deserialize<Expr>;
fn into_object_expression(self) -> Deserialize<Expr>;
fn into_conditional_expression(self) -> Deserialize<Expr>;
fn into_identifier(self) -> Deserialize<Id>;
fn into_property(self) -> Deserialize<Prop>;
fn into_property_key(self) -> Deserialize<PropKey>;
fn into_literal(self) -> Deserialize<Expr>;
fn into_function(self) -> Deserialize<Fun>;
fn into_pattern(self) -> Deserialize<Patt>;
fn into_case(self) -> Deserialize<Case>;
fn into_catch(self) -> Deserialize<Catch>;
}
impl IntoNode for Object {
fn into_program(mut self) -> Deserialize<Script> {
Ok((ScriptData { body: try!(self.extract_statement_list("body")) }).tracked(None))
}
fn into_statement_list_item(self) -> Deserialize<StmtListItem> {
let is_fun = match &(try!(self.peek_type()))[..] {
"FunctionDeclaration" => true,
_ => false
};
if is_fun {
Ok(StmtListItem::Decl(DeclData::Fun(try!(self.into_function())).tracked(None)))
} else {
Ok(StmtListItem::Stmt(try!(self.into_statement())))
}
}
fn into_declarator(mut self) -> Deserialize<Dtor> {
let lhs = try!(self.extract_pattern("id"));
let init = try!(self.extract_expression_opt("init"));
Dtor::from_init_opt(lhs, init).map_err(DeserializeError::UninitializedPattern)
}
fn into_statement(mut self) -> Deserialize<Stmt> {
let ty = try!(self.extract_string("type"));
match &ty[..] {
"VariableDeclaration" => {
let dtors = try!(self.extract_declarator_list("declarations"));
Ok(StmtData::Var(dtors, Semi::Explicit(None)).tracked(None))
}
"EmptyStatement" => {
Ok(StmtData::Empty.tracked(None))
}
"ExpressionStatement" => {
let expr = try!(self.extract_expression("expression"));
Ok(StmtData::Expr(expr, Semi::Explicit(None)).tracked(None))
}
"IfStatement" => {
let test = try!(self.extract_expression("test"));
let cons = Box::new(try!(self.extract_statement("consequent")));
let alt = try!(self.extract_statement_opt("alternate")).map(Box::new);
Ok(StmtData::If(test, cons, alt).tracked(None))
}
"DoWhileStatement" => {
let body = Box::new(try!(self.extract_statement("body")));
let test = try!(self.extract_expression("test"));
Ok(StmtData::DoWhile(body, test, Semi::Explicit(None)).tracked(None))
}
"WhileStatement" => {
let test = try!(self.extract_expression("test"));
let body = Box::new(try!(self.extract_statement("body")));
Ok(StmtData::While(test, body).tracked(None))
}
"ForStatement" => {
let init0 = try!(self.extract_object_opt("init"));
let init = match init0 {
None => None,
Some(mut obj) => {
match &(try!(obj.peek_type()))[..] {
"VariableDeclaration" => {
let dtors = try!(obj.extract_declarator_list("declarations"));
let kind = try!(obj.extract_string("kind"));
let head = (match &kind[..] {
"var" => ForHeadData::Var(dtors),
"let" => ForHeadData::Let(dtors),
_ => { return string_error("var or let", kind); }
}).tracked(None);
Some(Box::new(head))
}
_ => Some(Box::new(ForHeadData::Expr(try!(obj.into_expression())).tracked(None)))
}
}
};
let test = try!(self.extract_expression_opt("test"));
let update = try!(self.extract_expression_opt("update"));
let body = Box::new(try!(self.extract_statement("body")));
Ok(StmtData::For(init, test, update, body).tracked(None))
}
"ForInStatement" => {
let mut left0 = try!(self.extract_object("left"));
let left = Box::new((match &(try!(left0.peek_type()))[..] {
"VariableDeclaration" => {
let mut dtors = try!(left0.extract_array("declarations"));
let kind = try!(left0.extract_string("kind"));
if dtors.len() != 1 {
return array_error("array of length 1", dtors);
}
let mut obj = try!(dtors.remove(0).into_object());
let lhs = try!(obj.extract_pattern("id"));
let init = try!(obj.extract_expression_opt("init"));
match &kind[..] {
"var" => match lhs {
Patt::Simple(id) => {
match init {
None => ForInHeadData::Var(Patt::Simple(id)),
Some(expr) => ForInHeadData::VarInit(id, expr)
}
}
Patt::Compound(patt) => {
match init {
None => ForInHeadData::Var(Patt::Compound(patt)),
Some(expr) => { return Err(DeserializeError::UnexpectedInitializer(expr)); }
}
}
},
"let" => {
match init {
None => ForInHeadData::Let(lhs),
Some(expr) => { return Err(DeserializeError::UnexpectedInitializer(expr)); }
}
}
_ => { return string_error("var or let", kind); }
}
}
_ => ForInHeadData::Expr(try!(left0.into_expression()))
}).tracked(None));
let right = try!(self.extract_expression("right"));
let body = try!(self.extract_statement("body"));
Ok(StmtData::ForIn(left, right, Box::new(body)).tracked(None))
}
"ForOfStatement" => {
let left0 = try!(self.extract_object("left"));
let left = Box::new((match &(try!(left0.peek_type()))[..] {
"VariableDeclaration" => {
let mut dtors = try!(self.extract_array("declarations"));
let kind = try!(self.extract_string("kind"));
if dtors.len() != 1 {
return array_error("array of length 1", dtors);
}
let mut obj = try!(dtors.remove(0).into_object());
let lhs = try!(obj.extract_pattern("id"));
match &kind[..] {
"var" => ForOfHeadData::Var(lhs),
"let" => ForOfHeadData::Let(lhs),
_ => { return string_error("var or let", kind); }
}
},
_ => ForOfHeadData::Expr(try!(left0.into_expression()))
}).tracked(None));
let right = try!(self.extract_expression("right"));
let body = try!(self.extract_statement("body"));
Ok(StmtData::ForOf(left, right, Box::new(body)).tracked(None))
}
"BlockStatement" => {
let body = try!(self.extract_statement_list("body"));
Ok(StmtData::Block(body).tracked(None))
}
"ReturnStatement" => {
let arg = try!(self.extract_expression_opt("argument"));
Ok(StmtData::Return(arg, Semi::Explicit(None)).tracked(None))
}
"LabeledStatement" => {
let label = try!(self.extract_id("label"));
let body = Box::new(try!(self.extract_statement("body")));
Ok(StmtData::Label(label, body).tracked(None))
}
"BreakStatement" => {
let label = try!(self.extract_id_opt("label"));
Ok(StmtData::Break(label, Semi::Explicit(None)).tracked(None))
}
"ContinueStatement" => {
let label = try!(self.extract_id_opt("label"));
Ok(StmtData::Cont(label, Semi::Explicit(None)).tracked(None))
}
"SwitchStatement" => {
let disc = try!(self.extract_expression("discriminant"));
let cases = try!(self.extract_case_list("cases"));
Ok(StmtData::Switch(disc, cases).tracked(None))
}
"WithStatement" => {
let obj = try!(self.extract_expression("object"));
let body = Box::new(try!(self.extract_statement("body")));
Ok(StmtData::With(obj, body).tracked(None))
}
"ThrowStatement" => {
let arg = try!(self.extract_expression("argument"));
Ok(StmtData::Throw(arg, Semi::Explicit(None)).tracked(None))
}
"DebuggerStatement" => {
Ok(StmtData::Debugger(Semi::Explicit(None)).tracked(None))
}
"TryStatement" => {
let mut block = try!(self.extract_object("block"));
let body = try!(block.extract_statement_list("body"));
let catch = try!(self.extract_catch_opt("handler")).map(Box::new);
let mut finally = match try!(self.extract_object_opt("finalizer")) {
Some(mut finalizer) => Some(try!(finalizer.extract_statement_list("body"))),
None => None
};
Ok(StmtData::Try(body, catch, finally).tracked(None))
}
// FIXME: remaining statement cases
_ => string_error("statement type", ty)
}
}
fn into_expression(self) -> Deserialize<Expr> {
match &(try!(self.peek_type()))[..] {
"Identifier" => self.into_identifier().map(|id| id.into_expr()),
"Literal" => self.into_literal(),
"BinaryExpression" => self.into_binary_expression(),
"AssignmentExpression" => self.into_assignment_expression(),
"LogicalExpression" => self.into_logical_expression(),
"UnaryExpression" => self.into_unary_expression(),
"UpdateExpression" => self.into_update_expression(),
"MemberExpression" => self.into_member_expression(),
"CallExpression" => self.into_call_expression(),
"NewExpression" => self.into_new_expression(),
"ArrayExpression" => self.into_array_expression(),
"FunctionExpression" => self.into_function_expression(),
"SequenceExpression" => self.into_sequence_expression(),
"ObjectExpression" => self.into_object_expression(),
"ConditionalExpression" => self.into_conditional_expression(),
"ThisExpression" => Ok(ExprData::This.tracked(None)),
_ => { return object_error("expression", self); }
}
}
fn into_unary_expression(mut self) -> Deserialize<Expr> {
let op = try!(try!(self.extract_string("operator")).into_unop());
let arg = try!(self.extract_expression("argument"));
Ok(ExprData::Unop(op, Box::new(arg)).tracked(None))
}
fn into_update_expression(mut self) -> Deserialize<Expr> {
let op = try!(self.extract_string("operator"));
let arg = Box::new(try!(self.extract_expression("argument")));
let prefix = try!(self.extract_bool("prefix"));
Ok((match (&op[..], prefix) {
("++", true) => ExprData::PreInc(arg),
("++", false) => ExprData::PostInc(arg),
("--", true) => ExprData::PreDec(arg),
("--", false) => ExprData::PostDec(arg),
_ => { return string_error("'++' or '--'", op); }
}).tracked(None))
}
fn into_member_expression(mut self) -> Deserialize<Expr> {
let obj = Box::new(try!(self.extract_expression("object")));
if try!(self.extract_bool("computed")) {
let prop = Box::new(try!(self.extract_expression("property")));
Ok(ExprData::Brack(obj, prop).tracked(None))
} else {
let prop = try!(self.extract_id("property"));
Ok(ExprData::Dot(obj, prop).tracked(None))
}
}
fn into_call_expression(mut self) -> Deserialize<Expr> {
let callee = Box::new(try!(self.extract_expression("callee")));
let args = try!(try!(self.extract_object_array("arguments")).map(|obj| obj.into_expression()));
Ok(ExprData::Call(callee, args).tracked(None))
}
fn into_new_expression(mut self) -> Deserialize<Expr> {
let callee = Box::new(try!(self.extract_expression("callee")));
let args = try!(try!(self.extract_object_array("arguments")).map(|obj| obj.into_expression()));
Ok(ExprData::New(callee, Some(args)).tracked(None))
}
fn into_array_expression(mut self) -> Deserialize<Expr> {
let elts = try!(try!(self.extract_object_opt_array("elements")).map(|opt| match opt {
None => Ok(None),
Some(obj) => obj.into_expression().map(Some)
}));
Ok(ExprData::Arr(elts).tracked(None))
}
fn into_function_expression(mut self) -> Deserialize<Expr> {
let fun = try!(self.into_function());
Ok(ExprData::Fun(fun).tracked(None))
}
fn into_sequence_expression(mut self) -> Deserialize<Expr> {
let elts = try!(try!(self.extract_object_array("expressions")).map(|obj| obj.into_expression()));
Ok(ExprData::Seq(elts).tracked(None))
}
fn into_object_expression(mut self) -> Deserialize<Expr> {
let props = try!(try!(self.extract_object_array("properties")).map(|obj| obj.into_property()));
Ok(ExprData::Obj(props).tracked(None))
}
fn into_conditional_expression(mut self) -> Deserialize<Expr> {
let test = Box::new(try!(self.extract_expression("test")));
let cons = Box::new(try!(self.extract_expression("consequent")));
let alt = Box::new(try!(self.extract_expression("alternate")));
Ok(ExprData::Cond(test, cons, alt).tracked(None))
}
fn into_binary_expression(mut self) -> Deserialize<Expr> {
let op = try!(try!(self.extract_string("operator")).into_binop());
let left = try!(self.extract_expression("left"));
let right = try!(self.extract_expression("right"));
Ok(ExprData::Binop(op, Box::new(left), Box::new(right)).tracked(None))
}
fn into_assignment_expression(mut self) -> Deserialize<Expr> {
let op = try!(try!(self.extract_string("operator")).into_assop());
let left = try!(self.extract_assignment_pattern("left"));
let right = try!(self.extract_expression("right"));
Ok(ExprData::Assign(op, left, Box::new(right)).tracked(None))
}
fn into_logical_expression(mut self) -> Deserialize<Expr> {
let op = try!(try!(self.extract_string("operator")).into_logop());
let left = try!(self.extract_expression("left"));
let right = try!(self.extract_expression("right"));
Ok(ExprData::Logop(op, Box::new(left), Box::new(right)).tracked(None))
}
fn into_identifier(mut self) -> Deserialize<Id> {
Ok((IdData { name: Name::new(try!(self.extract_string("name"))) }).tracked(None))
}
fn into_property(mut self) -> Deserialize<Prop> {
let key = try!(try!(self.extract_object("key")).into_property_key());
let mut val = try!(self.extract_object("value"));
let kind = try!(self.extract_string("kind"));
let val = (match &kind[..] {
"init" => PropValData::Init(try!(val.into_expression())),
"get" => PropValData::Get(try!(try!(val.extract_object("body")).extract_statement_list("body"))),
"set" => {
unimplemented!()
}
_ => { return type_error("'init', 'get', or 'set'", JsonType::String); }
}).tracked(None);
Ok((PropData { key: key, val: val }).tracked(None))
}
fn into_property_key(mut self) -> Deserialize<PropKey> {
if &(try!(self.peek_type()))[..] == "Identifier" {
let id = try!(self.into_identifier());
return Ok(PropKeyData::Id(id.value.name.into_string()).tracked(None));
}
match try!(self.into_literal()).value {
ExprData::Number(lit) => Ok(PropKeyData::Number(lit).tracked(None)),
ExprData::String(val) => Ok(PropKeyData::String(val).tracked(None)),
_ => { return type_error("identifier, number literal, or string literal", JsonType::Object); }
}
}
fn into_literal(mut self) -> Deserialize<Expr> {
let json = try!(self.extract("value"));
Ok((match json {
Json::Null => ExprData::Null,
Json::Boolean(val) => if val { ExprData::True } else { ExprData::False },
Json::String(val) => ExprData::String(val),
Json::I64(val) => ExprData::Number(NumberLiteral::DecimalInt(format!("{}", val), None)),
Json::U64(val) => ExprData::Number(NumberLiteral::DecimalInt(format!("{}", val), None)),
Json::F64(val) => {
let s = format!("{}", val);
let v: Vec<&str> = s.split('.').collect();
let int_part = Some(v[0].to_owned());
let fract_part = if v.len() > 1 { Some(v[1].to_owned()) } else { None };
ExprData::Number(NumberLiteral::Float(int_part, fract_part, None))
}
Json::Object(_) => {
let mut regex = try!(self.extract_object("regex"));
let pattern = try!(regex.extract_string("pattern"));
let flags = try!(regex.extract_string("flags"));
ExprData::RegExp(pattern, flags.chars().collect())
}
_ => { return type_error("null, number, boolean, string, or object", json_typeof(&json)); }
}).tracked(None))
}
fn into_function(mut self) -> Deserialize<Fun> {
let id = try!(self.extract_id_opt("id"));
let params = (ParamsData {
list: try!(try!(self.extract_object_array("params")).map(|obj| obj.into_pattern()))
}).tracked(None);
let body = match try!(self.extract_statement("body")).value {
StmtData::Block(items) => items,
node => { return node_error("BlockStatement", format!("{:?}", node)); }
};
Ok((FunData { id: id, params: params, body: body }).tracked(None))
}
fn into_pattern(self) -> Deserialize<Patt> {
self.into_identifier().map(|id| id.into_patt())
}
fn into_case(mut self) -> Deserialize<Case> {
let test = try!(self.extract_expression_opt("test"));
let body = try!(self.extract_statement_list("consequent"));
Ok((CaseData { test: test, body: body }).tracked(None))
}
fn into_catch(mut self) -> Deserialize<Catch> {
let param = try!(self.extract_pattern("param"));
let mut body = try!(self.extract_object("body"));
let body = try!(body.extract_statement_list("body"));
Ok((CatchData { param: param, body: body }).tracked(None))
}
}
trait DeserializeMap<T, U> {
fn map<F: Fn(T) -> Deserialize<U>>(self, F) -> Deserialize<Vec<U>>;
}
impl<T, U> DeserializeMap<T, U> for Vec<T> {
fn map<F: Fn(T) -> Deserialize<U>>(self, f: F) -> Deserialize<Vec<U>> {
let mut list = Vec::with_capacity(self.len());
for data in self {
list.push(try!(f(data)));
}
Ok(list)
}
}
pub trait ExtractField {
fn extract(&mut self, &'static str) -> Deserialize<Json>;
fn extract_string(&mut self, &'static str) -> Deserialize<String>;
fn extract_array(&mut self, &'static str) -> Deserialize<json::Array>;
fn extract_object_array(&mut self, &'static str) -> Deserialize<Vec<Object>>;
fn extract_object_opt_array(&mut self, &'static str) -> Deserialize<Vec<Option<Object>>>;
fn extract_object(&mut self, &'static str) -> Deserialize<Object>;
fn extract_object_opt(&mut self, &'static str) -> Deserialize<Option<Object>>;
fn extract_bool(&mut self, &'static str) -> Deserialize<bool>;
fn extract_id(&mut self, &'static str) -> Deserialize<Id>;
fn extract_id_opt(&mut self, &'static str) -> Deserialize<Option<Id>>;
fn extract_assignment_pattern(&mut self, &'static str) -> Deserialize<APatt>;
fn peek_type(&self) -> Deserialize<&String>;
}
impl ExtractField for json::Object {
fn extract(&mut self, name: &'static str) -> Deserialize<Json> {
match self.remove(name) {
Some(json) => Ok(json),
None => Err(DeserializeError::MissingField(name))
}
}
fn extract_string(&mut self, name: &'static str) -> Deserialize<String> {
self.extract(name).and_then(|data| data.into_string())
}
fn extract_array(&mut self, name: &'static str) -> Deserialize<json::Array> {
self.extract(name).and_then(|data| data.into_array())
}
fn extract_object_array(&mut self, name: &'static str) -> Deserialize<Vec<Object>> {
self.extract(name).and_then(|data| data.into_array())
.and_then(|arr| arr.map(|elt| elt.into_object()))
}
fn extract_object_opt_array(&mut self, name: &'static str) -> Deserialize<Vec<Option<Object>>> {
self.extract(name).and_then(|data| data.into_array())
.and_then(|arr| arr.map(|elt| elt.into_object_opt()))
}
fn extract_object(&mut self, name: &'static str) -> Deserialize<Object> {
self.extract(name).and_then(|data| data.into_object())
}
fn extract_object_opt(&mut self, name: &'static str) -> Deserialize<Option<Object>> {
self.extract(name).and_then(|data| data.into_object_opt())
}
fn extract_bool(&mut self, name: &'static str) -> Deserialize<bool> {
self.extract(name).and_then(|data| data.into_bool())
}
fn extract_id(&mut self, name: &'static str) -> Deserialize<Id> {
self.extract_object(name).and_then(|data| data.into_identifier())
}
fn extract_id_opt(&mut self, name: &'static str) -> Deserialize<Option<Id>> {
Ok(match try!(self.extract_object_opt(name)) {
None => None,
Some(obj) => Some(try!(obj.into_identifier()))
})
}
fn extract_assignment_pattern(&mut self, name: &'static str) -> Deserialize<APatt> {
let expr = try!(self.extract_expression(name));
match expr.into_assignment_pattern() {
Ok(patt) => Ok(patt),
_ => Err(DeserializeError::InvalidLHS(name))
}
}
fn peek_type(&self) -> Deserialize<&String> {
match self.get("type") {
None => Err(DeserializeError::MissingField("type")),
Some(&Json::String(ref s)) => { Ok(s) },
Some(data) => type_error("string", json_typeof(&data))
}
}
}
pub trait ExtractNode {
fn extract_statement(&mut self, &'static str) -> Deserialize<Stmt>;
fn extract_expression(&mut self, &'static str) -> Deserialize<Expr>;
fn extract_expression_opt(&mut self, &'static str) -> Deserialize<Option<Expr>>;
fn extract_statement_opt(&mut self, &'static str) -> Deserialize<Option<Stmt>>;
fn extract_statement_list(&mut self, &'static str) -> Deserialize<Vec<StmtListItem>>;
fn extract_pattern(&mut self, &'static str) -> Deserialize<Patt>;
fn extract_declarator_list(&mut self, &'static str) -> Deserialize<Vec<Dtor>>;
fn extract_case_list(&mut self, &'static str) -> Deserialize<Vec<Case>>;
fn extract_catch_opt(&mut self, &'static str) -> Deserialize<Option<Catch>>;
}
impl ExtractNode for Object {
fn extract_statement(&mut self, name: &'static str) -> Deserialize<Stmt> {
try!(self.extract_object(name)).into_statement()
}
fn extract_expression(&mut self, name: &'static str) -> Deserialize<Expr> {
try!(self.extract_object(name)).into_expression()
}
fn extract_expression_opt(&mut self, name: &'static str) -> Deserialize<Option<Expr>> {
match try!(self.extract_object_opt(name)) {
None => Ok(None),
Some(obj) => Ok(Some(try!(obj.into_expression())))
}
}
fn extract_statement_opt(&mut self, name: &'static str) -> Deserialize<Option<Stmt>> {
match try!(self.extract_object_opt(name)) {
None => Ok(None),
Some(obj) => Ok(Some(try!(obj.into_statement())))
}
}
fn extract_statement_list(&mut self, name: &'static str) -> Deserialize<Vec<StmtListItem>> {
try!(self.extract_object_array(name)).map(|obj| obj.into_statement_list_item())
}
fn extract_pattern(&mut self, name: &'static str) -> Deserialize<Patt> {
try!(self.extract_object(name)).into_pattern()
}
fn extract_declarator_list(&mut self, name: &'static str) -> Deserialize<Vec<Dtor>> {
try!(self.extract_object_array(name)).map(|obj| obj.into_declarator())
}
fn extract_case_list(&mut self, name: &'static str) -> Deserialize<Vec<Case>> {
try!(self.extract_object_array(name)).map(|obj| obj.into_case())
}
fn extract_catch_opt(&mut self, name: &'static str) -> Deserialize<Option<Catch>> {
Ok(match try!(self.extract_object_opt(name)) {
Some(obj) => Some(try!(obj.into_catch())),
None => None
})
}
}
|
use crate::naia_server::Timestamp;
use std::net::SocketAddr;
#[allow(missing_docs)]
#[allow(unused_doc_comments)]
pub mod user_key {
// The Key used to get a reference of a User
new_key_type! { pub struct UserKey; }
}
#[derive(Clone)]
pub struct User {
pub address: SocketAddr,
pub timestamp: Timestamp,
}
impl User {
pub fn new(address: SocketAddr, timestamp: Timestamp) -> User {
User { address, timestamp }
}
}
|
use crate::game::Coord;
#[derive(Default)]
pub struct Othello {
player: bool,
board: [[Option<bool>; 8]; 8],
game_over: bool,
}
impl Othello {
pub fn new() -> Self {
let mut board: [[Option<bool>; 8]; 8] = Default::default();
board[3][3] = Some(true);
board[3][4] = Some(false);
board[4][3] = Some(false);
board[4][4] = Some(true);
Self {
player: false,
board,
game_over: false,
}
}
pub fn get_current_player(&self) -> bool {
self.player
}
pub fn is_game_over(&self) -> bool {
self.game_over
}
pub fn get_score(&self) -> (u32, u32) {
let mut scores = [0, 0];
for row in self.board.iter() {
for i in row {
if let Some(i) = *i {
scores[i as usize] += 1;
}
}
}
(scores[0], scores[1])
}
pub fn iter_row(&self, row: usize) -> impl Iterator<Item=&Option<bool>> {
self.board[row].iter()
}
const DIRECTIONS: [(i32, i32); 8] = [
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
];
fn find_anchor(&self, coord: (i32, i32), direction: (i32, i32), player: bool) -> Option<(i32, i32)> {
let mut anchor = coord;
let mut valid = false;
loop {
anchor.0 += direction.0;
anchor.1 += direction.1;
if anchor.0 < 0 || anchor.0 >= 8 || anchor.1 < 0 || anchor.1 >= 8 {
return None;
}
match self.board[anchor.0 as usize][anchor.1 as usize] {
None => { return None; }
Some(p) => {
if p == player {
break;
} else {
valid = true;
}
}
}
}
return if valid { Some(anchor) } else { None };
}
fn capture(&mut self, coord: (i32, i32), direction: (i32, i32)) -> bool {
let anchor = self.find_anchor(coord, direction, self.player);
if let Some(mut anchor) = anchor {
loop {
anchor.0 -= direction.0;
anchor.1 -= direction.1;
if anchor == coord { break; }
self.board[anchor.0 as usize][anchor.1 as usize] = Some(self.player);
}
true
} else {
false
}
}
fn has_move(&self, player: bool) -> bool {
for i in 0..8 {
for j in 0..8 {
if self.board[i as usize][j as usize] == None {
for direction in Self::DIRECTIONS.iter() {
if self.find_anchor((i, j), *direction, player).is_some() {
return true;
}
}
}
}
}
false
}
pub fn play(&mut self, coord: Coord) -> bool {
let coord_i32 = (coord.0 as i32, coord.1 as i32);
let mut valid = false;
for direction in Self::DIRECTIONS.iter() {
valid |= self.capture(coord_i32, *direction)
}
if valid {
self.board[coord.0][coord.1] = Some(self.player);
if self.has_move(!self.player) {
self.player = !self.player;
} else if !self.has_move(self.player) {
self.game_over = true;
}
}
valid
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qmargins.h
// dst-file: /src/core/qmargins.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use std::ops::Deref;
// use super::qmargins::QMargins; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QMarginsF_Class_Size() -> c_int;
// proto: QMargins QMarginsF::toMargins();
fn C_ZNK9QMarginsF9toMarginsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: qreal QMarginsF::right();
fn C_ZNK9QMarginsF5rightEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: bool QMarginsF::isNull();
fn C_ZNK9QMarginsF6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QMarginsF::setRight(qreal right);
fn C_ZN9QMarginsF8setRightEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QMarginsF::setTop(qreal top);
fn C_ZN9QMarginsF6setTopEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: qreal QMarginsF::left();
fn C_ZNK9QMarginsF4leftEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QMarginsF::QMarginsF();
fn C_ZN9QMarginsFC2Ev() -> u64;
// proto: void QMarginsF::QMarginsF(qreal left, qreal top, qreal right, qreal bottom);
fn C_ZN9QMarginsFC2Edddd(arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double) -> u64;
// proto: qreal QMarginsF::bottom();
fn C_ZNK9QMarginsF6bottomEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QMarginsF::QMarginsF(const QMargins & margins);
fn C_ZN9QMarginsFC2ERK8QMargins(arg0: *mut c_void) -> u64;
// proto: void QMarginsF::setBottom(qreal bottom);
fn C_ZN9QMarginsF9setBottomEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: qreal QMarginsF::top();
fn C_ZNK9QMarginsF3topEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QMarginsF::setLeft(qreal left);
fn C_ZN9QMarginsF7setLeftEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
fn QMargins_Class_Size() -> c_int;
// proto: void QMargins::setLeft(int left);
fn C_ZN8QMargins7setLeftEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QMargins::setRight(int right);
fn C_ZN8QMargins8setRightEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QMargins::left();
fn C_ZNK8QMargins4leftEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMargins::top();
fn C_ZNK8QMargins3topEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QMargins::setTop(int top);
fn C_ZN8QMargins6setTopEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QMargins::setBottom(int bottom);
fn C_ZN8QMargins9setBottomEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QMargins::right();
fn C_ZNK8QMargins5rightEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMargins::bottom();
fn C_ZNK8QMargins6bottomEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: bool QMargins::isNull();
fn C_ZNK8QMargins6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QMargins::QMargins();
fn C_ZN8QMarginsC2Ev() -> u64;
// proto: void QMargins::QMargins(int left, int top, int right, int bottom);
fn C_ZN8QMarginsC2Eiiii(arg0: c_int, arg1: c_int, arg2: c_int, arg3: c_int) -> u64;
} // <= ext block end
// body block begin =>
// class sizeof(QMarginsF)=32
#[derive(Default)]
pub struct QMarginsF {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QMargins)=16
#[derive(Default)]
pub struct QMargins {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QMarginsF {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMarginsF {
return QMarginsF{qclsinst: qthis, ..Default::default()};
}
}
// proto: QMargins QMarginsF::toMargins();
impl /*struct*/ QMarginsF {
pub fn toMargins<RetType, T: QMarginsF_toMargins<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.toMargins(self);
// return 1;
}
}
pub trait QMarginsF_toMargins<RetType> {
fn toMargins(self , rsthis: & QMarginsF) -> RetType;
}
// proto: QMargins QMarginsF::toMargins();
impl<'a> /*trait*/ QMarginsF_toMargins<QMargins> for () {
fn toMargins(self , rsthis: & QMarginsF) -> QMargins {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMarginsF9toMarginsEv()};
let mut ret = unsafe {C_ZNK9QMarginsF9toMarginsEv(rsthis.qclsinst)};
let mut ret1 = QMargins::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QMarginsF::right();
impl /*struct*/ QMarginsF {
pub fn right<RetType, T: QMarginsF_right<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.right(self);
// return 1;
}
}
pub trait QMarginsF_right<RetType> {
fn right(self , rsthis: & QMarginsF) -> RetType;
}
// proto: qreal QMarginsF::right();
impl<'a> /*trait*/ QMarginsF_right<f64> for () {
fn right(self , rsthis: & QMarginsF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMarginsF5rightEv()};
let mut ret = unsafe {C_ZNK9QMarginsF5rightEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: bool QMarginsF::isNull();
impl /*struct*/ QMarginsF {
pub fn isNull<RetType, T: QMarginsF_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QMarginsF_isNull<RetType> {
fn isNull(self , rsthis: & QMarginsF) -> RetType;
}
// proto: bool QMarginsF::isNull();
impl<'a> /*trait*/ QMarginsF_isNull<i8> for () {
fn isNull(self , rsthis: & QMarginsF) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMarginsF6isNullEv()};
let mut ret = unsafe {C_ZNK9QMarginsF6isNullEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QMarginsF::setRight(qreal right);
impl /*struct*/ QMarginsF {
pub fn setRight<RetType, T: QMarginsF_setRight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRight(self);
// return 1;
}
}
pub trait QMarginsF_setRight<RetType> {
fn setRight(self , rsthis: & QMarginsF) -> RetType;
}
// proto: void QMarginsF::setRight(qreal right);
impl<'a> /*trait*/ QMarginsF_setRight<()> for (f64) {
fn setRight(self , rsthis: & QMarginsF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMarginsF8setRightEd()};
let arg0 = self as c_double;
unsafe {C_ZN9QMarginsF8setRightEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QMarginsF::setTop(qreal top);
impl /*struct*/ QMarginsF {
pub fn setTop<RetType, T: QMarginsF_setTop<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTop(self);
// return 1;
}
}
pub trait QMarginsF_setTop<RetType> {
fn setTop(self , rsthis: & QMarginsF) -> RetType;
}
// proto: void QMarginsF::setTop(qreal top);
impl<'a> /*trait*/ QMarginsF_setTop<()> for (f64) {
fn setTop(self , rsthis: & QMarginsF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMarginsF6setTopEd()};
let arg0 = self as c_double;
unsafe {C_ZN9QMarginsF6setTopEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QMarginsF::left();
impl /*struct*/ QMarginsF {
pub fn left<RetType, T: QMarginsF_left<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.left(self);
// return 1;
}
}
pub trait QMarginsF_left<RetType> {
fn left(self , rsthis: & QMarginsF) -> RetType;
}
// proto: qreal QMarginsF::left();
impl<'a> /*trait*/ QMarginsF_left<f64> for () {
fn left(self , rsthis: & QMarginsF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMarginsF4leftEv()};
let mut ret = unsafe {C_ZNK9QMarginsF4leftEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QMarginsF::QMarginsF();
impl /*struct*/ QMarginsF {
pub fn new<T: QMarginsF_new>(value: T) -> QMarginsF {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMarginsF_new {
fn new(self) -> QMarginsF;
}
// proto: void QMarginsF::QMarginsF();
impl<'a> /*trait*/ QMarginsF_new for () {
fn new(self) -> QMarginsF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMarginsFC2Ev()};
let ctysz: c_int = unsafe{QMarginsF_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN9QMarginsFC2Ev()};
let rsthis = QMarginsF{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QMarginsF::QMarginsF(qreal left, qreal top, qreal right, qreal bottom);
impl<'a> /*trait*/ QMarginsF_new for (f64, f64, f64, f64) {
fn new(self) -> QMarginsF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMarginsFC2Edddd()};
let ctysz: c_int = unsafe{QMarginsF_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
let qthis: u64 = unsafe {C_ZN9QMarginsFC2Edddd(arg0, arg1, arg2, arg3)};
let rsthis = QMarginsF{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: qreal QMarginsF::bottom();
impl /*struct*/ QMarginsF {
pub fn bottom<RetType, T: QMarginsF_bottom<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bottom(self);
// return 1;
}
}
pub trait QMarginsF_bottom<RetType> {
fn bottom(self , rsthis: & QMarginsF) -> RetType;
}
// proto: qreal QMarginsF::bottom();
impl<'a> /*trait*/ QMarginsF_bottom<f64> for () {
fn bottom(self , rsthis: & QMarginsF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMarginsF6bottomEv()};
let mut ret = unsafe {C_ZNK9QMarginsF6bottomEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QMarginsF::QMarginsF(const QMargins & margins);
impl<'a> /*trait*/ QMarginsF_new for (&'a QMargins) {
fn new(self) -> QMarginsF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMarginsFC2ERK8QMargins()};
let ctysz: c_int = unsafe{QMarginsF_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
let qthis: u64 = unsafe {C_ZN9QMarginsFC2ERK8QMargins(arg0)};
let rsthis = QMarginsF{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QMarginsF::setBottom(qreal bottom);
impl /*struct*/ QMarginsF {
pub fn setBottom<RetType, T: QMarginsF_setBottom<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBottom(self);
// return 1;
}
}
pub trait QMarginsF_setBottom<RetType> {
fn setBottom(self , rsthis: & QMarginsF) -> RetType;
}
// proto: void QMarginsF::setBottom(qreal bottom);
impl<'a> /*trait*/ QMarginsF_setBottom<()> for (f64) {
fn setBottom(self , rsthis: & QMarginsF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMarginsF9setBottomEd()};
let arg0 = self as c_double;
unsafe {C_ZN9QMarginsF9setBottomEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QMarginsF::top();
impl /*struct*/ QMarginsF {
pub fn top<RetType, T: QMarginsF_top<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.top(self);
// return 1;
}
}
pub trait QMarginsF_top<RetType> {
fn top(self , rsthis: & QMarginsF) -> RetType;
}
// proto: qreal QMarginsF::top();
impl<'a> /*trait*/ QMarginsF_top<f64> for () {
fn top(self , rsthis: & QMarginsF) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK9QMarginsF3topEv()};
let mut ret = unsafe {C_ZNK9QMarginsF3topEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QMarginsF::setLeft(qreal left);
impl /*struct*/ QMarginsF {
pub fn setLeft<RetType, T: QMarginsF_setLeft<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLeft(self);
// return 1;
}
}
pub trait QMarginsF_setLeft<RetType> {
fn setLeft(self , rsthis: & QMarginsF) -> RetType;
}
// proto: void QMarginsF::setLeft(qreal left);
impl<'a> /*trait*/ QMarginsF_setLeft<()> for (f64) {
fn setLeft(self , rsthis: & QMarginsF) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN9QMarginsF7setLeftEd()};
let arg0 = self as c_double;
unsafe {C_ZN9QMarginsF7setLeftEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
impl /*struct*/ QMargins {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMargins {
return QMargins{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QMargins::setLeft(int left);
impl /*struct*/ QMargins {
pub fn setLeft<RetType, T: QMargins_setLeft<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setLeft(self);
// return 1;
}
}
pub trait QMargins_setLeft<RetType> {
fn setLeft(self , rsthis: & QMargins) -> RetType;
}
// proto: void QMargins::setLeft(int left);
impl<'a> /*trait*/ QMargins_setLeft<()> for (i32) {
fn setLeft(self , rsthis: & QMargins) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QMargins7setLeftEi()};
let arg0 = self as c_int;
unsafe {C_ZN8QMargins7setLeftEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QMargins::setRight(int right);
impl /*struct*/ QMargins {
pub fn setRight<RetType, T: QMargins_setRight<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setRight(self);
// return 1;
}
}
pub trait QMargins_setRight<RetType> {
fn setRight(self , rsthis: & QMargins) -> RetType;
}
// proto: void QMargins::setRight(int right);
impl<'a> /*trait*/ QMargins_setRight<()> for (i32) {
fn setRight(self , rsthis: & QMargins) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QMargins8setRightEi()};
let arg0 = self as c_int;
unsafe {C_ZN8QMargins8setRightEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QMargins::left();
impl /*struct*/ QMargins {
pub fn left<RetType, T: QMargins_left<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.left(self);
// return 1;
}
}
pub trait QMargins_left<RetType> {
fn left(self , rsthis: & QMargins) -> RetType;
}
// proto: int QMargins::left();
impl<'a> /*trait*/ QMargins_left<i32> for () {
fn left(self , rsthis: & QMargins) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QMargins4leftEv()};
let mut ret = unsafe {C_ZNK8QMargins4leftEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMargins::top();
impl /*struct*/ QMargins {
pub fn top<RetType, T: QMargins_top<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.top(self);
// return 1;
}
}
pub trait QMargins_top<RetType> {
fn top(self , rsthis: & QMargins) -> RetType;
}
// proto: int QMargins::top();
impl<'a> /*trait*/ QMargins_top<i32> for () {
fn top(self , rsthis: & QMargins) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QMargins3topEv()};
let mut ret = unsafe {C_ZNK8QMargins3topEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QMargins::setTop(int top);
impl /*struct*/ QMargins {
pub fn setTop<RetType, T: QMargins_setTop<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setTop(self);
// return 1;
}
}
pub trait QMargins_setTop<RetType> {
fn setTop(self , rsthis: & QMargins) -> RetType;
}
// proto: void QMargins::setTop(int top);
impl<'a> /*trait*/ QMargins_setTop<()> for (i32) {
fn setTop(self , rsthis: & QMargins) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QMargins6setTopEi()};
let arg0 = self as c_int;
unsafe {C_ZN8QMargins6setTopEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QMargins::setBottom(int bottom);
impl /*struct*/ QMargins {
pub fn setBottom<RetType, T: QMargins_setBottom<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBottom(self);
// return 1;
}
}
pub trait QMargins_setBottom<RetType> {
fn setBottom(self , rsthis: & QMargins) -> RetType;
}
// proto: void QMargins::setBottom(int bottom);
impl<'a> /*trait*/ QMargins_setBottom<()> for (i32) {
fn setBottom(self , rsthis: & QMargins) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QMargins9setBottomEi()};
let arg0 = self as c_int;
unsafe {C_ZN8QMargins9setBottomEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QMargins::right();
impl /*struct*/ QMargins {
pub fn right<RetType, T: QMargins_right<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.right(self);
// return 1;
}
}
pub trait QMargins_right<RetType> {
fn right(self , rsthis: & QMargins) -> RetType;
}
// proto: int QMargins::right();
impl<'a> /*trait*/ QMargins_right<i32> for () {
fn right(self , rsthis: & QMargins) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QMargins5rightEv()};
let mut ret = unsafe {C_ZNK8QMargins5rightEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMargins::bottom();
impl /*struct*/ QMargins {
pub fn bottom<RetType, T: QMargins_bottom<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bottom(self);
// return 1;
}
}
pub trait QMargins_bottom<RetType> {
fn bottom(self , rsthis: & QMargins) -> RetType;
}
// proto: int QMargins::bottom();
impl<'a> /*trait*/ QMargins_bottom<i32> for () {
fn bottom(self , rsthis: & QMargins) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QMargins6bottomEv()};
let mut ret = unsafe {C_ZNK8QMargins6bottomEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: bool QMargins::isNull();
impl /*struct*/ QMargins {
pub fn isNull<RetType, T: QMargins_isNull<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isNull(self);
// return 1;
}
}
pub trait QMargins_isNull<RetType> {
fn isNull(self , rsthis: & QMargins) -> RetType;
}
// proto: bool QMargins::isNull();
impl<'a> /*trait*/ QMargins_isNull<i8> for () {
fn isNull(self , rsthis: & QMargins) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK8QMargins6isNullEv()};
let mut ret = unsafe {C_ZNK8QMargins6isNullEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QMargins::QMargins();
impl /*struct*/ QMargins {
pub fn new<T: QMargins_new>(value: T) -> QMargins {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMargins_new {
fn new(self) -> QMargins;
}
// proto: void QMargins::QMargins();
impl<'a> /*trait*/ QMargins_new for () {
fn new(self) -> QMargins {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QMarginsC2Ev()};
let ctysz: c_int = unsafe{QMargins_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN8QMarginsC2Ev()};
let rsthis = QMargins{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QMargins::QMargins(int left, int top, int right, int bottom);
impl<'a> /*trait*/ QMargins_new for (i32, i32, i32, i32) {
fn new(self) -> QMargins {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN8QMarginsC2Eiiii()};
let ctysz: c_int = unsafe{QMargins_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_int;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as c_int;
let qthis: u64 = unsafe {C_ZN8QMarginsC2Eiiii(arg0, arg1, arg2, arg3)};
let rsthis = QMargins{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// <= body block end
|
use input_i_scanner::InputIScanner;
use std::collections::HashMap;
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 (n, x) = scan!((usize, u64));
let a: Vec<Vec<u64>> = (0..n)
.map(|_| {
let l = scan!(usize);
scan!(u64; l)
})
.collect();
let mut dp = HashMap::<u64, u64>::new();
dp.insert(1, 1);
for a in a {
let mut nxt = HashMap::new();
for (k, v) in dp {
for &a in &a {
nxt.entry(k.saturating_mul(a))
.and_modify(|e| *e += v)
.or_insert(v);
}
}
dp = nxt;
}
if let Some(ans) = dp.get(&x) {
println!("{}", ans);
} else {
println!("0");
}
}
|
#[cfg(test)]
mod v8facade_memory_tests {
use javascript_eval_native::{function_parameter::FunctionParameter, v8facade::V8Facade};
#[test]
#[ignore]
fn it_wont_leak_memory_like_crazy() {
let eval = V8Facade::new();
let _ = eval.run("function echo(val) { return val; }").unwrap();
let mut last_heap_stats = eval.get_heap_statistics().unwrap();
let mut allocation_increased = false;
let mut allocation_decreased = false;
for _ in 0..25000 {
let _ = eval
.call(
"echo",
vec![FunctionParameter::StringValue(String::from(
"The quick brown fox jumped over the lazy moon.",
))],
)
.unwrap();
let current_heap_stats = eval.get_heap_statistics().unwrap();
if last_heap_stats.total_heap_size > current_heap_stats.total_heap_size {
allocation_decreased = true;
}
if current_heap_stats.total_heap_size > last_heap_stats.total_heap_size {
allocation_increased = true;
}
last_heap_stats = current_heap_stats;
}
assert!(allocation_increased);
assert!(allocation_decreased);
}
}
|
use crate::stack::Stack;
use std::sync::{MutexGuard, Arc, RwLock};
use minifb::{Window, Key};
pub struct Display {
}
impl Display {
pub fn new() -> Self {
Display {
}
}
pub fn refresh(window: &Window) -> bool {
window.is_open() && !window.is_key_down(Key::Escape)
}
pub fn draw_sprite(buffer: &mut Arc<RwLock<Vec<u32>>>,
orig_x: u8,
orig_y: u8,
rows: u16,
stack: &mut MutexGuard<Stack>) -> Vec<u32> {
let mut mem = stack.i;
let mut x = orig_x as u32;
let mut y = orig_y as u32;
let mut buff: Vec<u32>;
{
let gotten_buffer = buffer.read().unwrap();
buff = gotten_buffer.clone();
}
for _ in 0..(rows as i32) {
if y > 32 {
break;
}
let sprite_data = stack.memory[mem as usize];
mem = mem + 1u16;
for pixel in (0..8).rev() {
if x > 64 {
break;
}
let pixel_data = Display::get_bit_at(sprite_data, pixel);
let index = x + (y * 64);
let cloned_buf = buff.clone();
let current_char = cloned_buf.get(index as usize);
if current_char == Some(&255u32) && pixel_data {
let _ = std::mem::replace(&mut buff[index as usize], 0);
stack.registers.set_register(0xf, 1);
}
if current_char == Some(&0u32) && pixel_data {
let _ = std::mem::replace(&mut buff[index as usize], 255);
}
x += 1;
}
x = orig_x as u32;
y += 1;
}
buff
}
fn get_bit_at(input: u8, n: u8) -> bool {
if n < 8 {
input & (1 << n) != 0
} else {
false
}
}
} |
use crate::module::Module;
pub mod method;
use crate::v02::method as v02_method;
/// Registers all methods for the v0.3 RPC API
pub fn register_methods(module: Module) -> anyhow::Result<Module> {
let module = module
// Reused from v0.2
.register_method(
"v0.3_starknet_addDeclareTransaction",
v02_method::add_declare_transaction,
)?
.register_method(
"v0.3_starknet_addDeployAccountTransaction",
v02_method::add_deploy_account_transaction,
)?
.register_method(
"v0.3_starknet_addInvokeTransaction",
v02_method::add_invoke_transaction,
)?
.register_method_with_no_input(
"v0.3_starknet_blockHashAndNumber",
v02_method::block_hash_and_number,
)?
.register_method_with_no_input("v0.3_starknet_blockNumber", v02_method::block_number)?
.register_method("v0.3_starknet_call", v02_method::call)?
.register_method_with_no_input("v0.3_starknet_chainId", v02_method::chain_id)?
.register_method("v0.3_starknet_estimateFee", method::estimate_fee)?
.register_method(
"v0.3_starknet_getBlockWithTxHashes",
v02_method::get_block_with_tx_hashes,
)?
.register_method(
"v0.3_starknet_getBlockWithTxs",
v02_method::get_block_with_txs,
)?
.register_method(
"v0.3_starknet_getBlockTransactionCount",
v02_method::get_block_transaction_count,
)?
.register_method("v0.3_starknet_getClass", v02_method::get_class)?
.register_method("v0.3_starknet_getClassAt", v02_method::get_class_at)?
.register_method(
"v0.3_starknet_getClassHashAt",
v02_method::get_class_hash_at,
)?
.register_method("v0.3_starknet_getNonce", v02_method::get_nonce)?
.register_method("v0.3_starknet_getStorageAt", v02_method::get_storage_at)?
.register_method(
"v0.3_starknet_getTransactionByBlockIdAndIndex",
v02_method::get_transaction_by_block_id_and_index,
)?
.register_method(
"v0.3_starknet_getTransactionByHash",
v02_method::get_transaction_by_hash,
)?
.register_method(
"v0.3_starknet_getTransactionReceipt",
v02_method::get_transaction_receipt,
)?
.register_method_with_no_input(
"v0.3_starknet_pendingTransactions",
v02_method::pending_transactions,
)?
.register_method_with_no_input("v0.3_starknet_syncing", v02_method::syncing)?
// Specific implementations for v0.3
.register_method("v0.3_starknet_getEvents", method::get_events)?
.register_method("v0.3_starknet_getStateUpdate", method::get_state_update)?
.register_method(
"v0.3_starknet_simulateTransaction",
method::simulate_transaction,
)?
.register_method(
"v0.3_starknet_estimateMessageFee",
method::estimate_message_fee,
)?
.register_method(
"v0.3_pathfinder_getProof",
crate::pathfinder::methods::get_proof,
)?
.register_method(
"v0.3_pathfinder_getTransactionStatus",
crate::pathfinder::methods::get_transaction_status,
)?;
Ok(module)
}
|
use failure::{Error, Fail};
pub fn print_error_and_exit(error: Error) -> ! {
for (i, cause) in error.causes().enumerate() {
if i == 0 {
eprintln!("Error: {}", cause);
} else {
let indentation = 4 * i;
eprintln!("{0:1$}Caused by: {2}", "", indentation, cause);
}
#[cfg(debug_assertions)]
{
if let Some(backtrace) = cause.backtrace() {
println!("{:#?}", backtrace);
}
}
}
eprintln!("\n...Sorry :(");
::std::process::exit(1);
}
pub fn format_error_with_causes<E: Fail>(error: E) -> String {
error
.causes()
.enumerate()
.map(|(i, cause)| {
#[cfg(debug_assertions)]
let backtrace = if let Some(backtrace) = cause.backtrace() {
format!("\n{:#?}\n", backtrace)
} else {
String::new()
};
#[cfg(not(debug_assertions))]
let backtrace = String::new();
if i == 0 {
format!("Error: {}{}", cause, backtrace)
} else {
let indentation = 4 * i;
format!(
"\n{0:1$}Caused by: {2}{3}",
"", indentation, cause, backtrace
)
}
})
.collect()
}
#[cfg(test)]
extern crate tui;
#[cfg(test)]
pub fn render_buffer(buf: &tui::buffer::Buffer) -> String {
let mut s = format!("Buffer area: {:?}\r\n", buf.area());
let width = buf.area().width;
for (i, cell) in buf.content().iter().enumerate() {
if i > 0 && i as u16 % width == 0 {
s.push_str("\r\n");
}
s.push(cell.symbol.chars().next().unwrap());
}
s
}
|
#[doc = "Reader of register ALTBASE"]
pub type R = crate::R<u32, super::ALTBASE>;
#[doc = "Reader of field `ADDR`"]
pub type ADDR_R = crate::R<u32, u32>;
impl R {
#[doc = "Bits 0:31 - Alternate Channel Address Pointer"]
#[inline(always)]
pub fn addr(&self) -> ADDR_R {
ADDR_R::new((self.bits & 0xffff_ffff) as u32)
}
}
|
use arrow::array::ArrayDataBuilder;
use arrow::array::StringArray;
use arrow::buffer::Buffer;
use arrow::buffer::NullBuffer;
use num_traits::{AsPrimitive, FromPrimitive, Zero};
use std::fmt::Debug;
use std::ops::Range;
/// A packed string array that stores start and end indexes into
/// a contiguous string slice.
///
/// The type parameter K alters the type used to store the offsets
#[derive(Debug, Clone)]
pub struct PackedStringArray<K> {
/// The start and end offsets of strings stored in storage
offsets: Vec<K>,
/// A contiguous array of string data
storage: String,
}
impl<K: Zero> Default for PackedStringArray<K> {
fn default() -> Self {
Self {
offsets: vec![K::zero()],
storage: String::new(),
}
}
}
impl<K: AsPrimitive<usize> + FromPrimitive + Zero> PackedStringArray<K> {
pub fn new() -> Self {
Self::default()
}
pub fn new_empty(len: usize) -> Self {
Self {
offsets: vec![K::zero(); len + 1],
storage: String::new(),
}
}
pub fn with_capacity(keys: usize, values: usize) -> Self {
let mut offsets = Vec::with_capacity(keys + 1);
offsets.push(K::zero());
Self {
offsets,
storage: String::with_capacity(values),
}
}
/// Append a value
///
/// Returns the index of the appended data
pub fn append(&mut self, data: &str) -> usize {
let id = self.offsets.len() - 1;
let offset = self.storage.len() + data.len();
let offset = K::from_usize(offset).expect("failed to fit into offset type");
self.offsets.push(offset);
self.storage.push_str(data);
id
}
/// Extends this [`PackedStringArray`] by the contents of `other`
pub fn extend_from(&mut self, other: &PackedStringArray<K>) {
let offset = self.storage.len();
self.storage.push_str(other.storage.as_str());
// Copy offsets skipping the first element as this string start delimiter is already
// provided by the end delimiter of the current offsets array
self.offsets.extend(
other
.offsets
.iter()
.skip(1)
.map(|x| K::from_usize(x.as_() + offset).expect("failed to fit into offset type")),
)
}
/// Extends this [`PackedStringArray`] by `range` elements from `other`
pub fn extend_from_range(&mut self, other: &PackedStringArray<K>, range: Range<usize>) {
let first_offset: usize = other.offsets[range.start].as_();
let end_offset: usize = other.offsets[range.end].as_();
let insert_offset = self.storage.len();
self.storage
.push_str(&other.storage[first_offset..end_offset]);
self.offsets.extend(
other.offsets[(range.start + 1)..(range.end + 1)]
.iter()
.map(|x| {
K::from_usize(x.as_() - first_offset + insert_offset)
.expect("failed to fit into offset type")
}),
)
}
/// Get the value at a given index
pub fn get(&self, index: usize) -> Option<&str> {
let start_offset = self.offsets.get(index)?.as_();
let end_offset = self.offsets.get(index + 1)?.as_();
Some(&self.storage[start_offset..end_offset])
}
/// Pads with empty strings to reach length
pub fn extend(&mut self, len: usize) {
let offset = K::from_usize(self.storage.len()).expect("failed to fit into offset type");
self.offsets.resize(self.offsets.len() + len, offset);
}
/// Truncates the array to the given length
pub fn truncate(&mut self, len: usize) {
self.offsets.truncate(len + 1);
let last_idx = self.offsets.last().expect("offsets empty");
self.storage.truncate(last_idx.as_());
}
/// Removes all elements from this array
pub fn clear(&mut self) {
self.offsets.truncate(1);
self.storage.clear();
}
pub fn iter(&self) -> PackedStringIterator<'_, K> {
PackedStringIterator {
array: self,
index: 0,
}
}
/// The number of strings in this array
pub fn len(&self) -> usize {
self.offsets.len() - 1
}
pub fn is_empty(&self) -> bool {
self.offsets.len() == 1
}
/// Return the amount of memory in bytes taken up by this array
pub fn size(&self) -> usize {
self.storage.capacity() + self.offsets.capacity() * std::mem::size_of::<K>()
}
pub fn inner(&self) -> (&[K], &str) {
(&self.offsets, &self.storage)
}
pub fn into_inner(self) -> (Vec<K>, String) {
(self.offsets, self.storage)
}
}
impl PackedStringArray<i32> {
/// Convert to an arrow with an optional null bitmask
pub fn to_arrow(&self, nulls: Option<NullBuffer>) -> StringArray {
let len = self.offsets.len() - 1;
let offsets = Buffer::from_slice_ref(&self.offsets);
let values = Buffer::from(self.storage.as_bytes());
let data = ArrayDataBuilder::new(arrow::datatypes::DataType::Utf8)
.len(len)
.add_buffer(offsets)
.add_buffer(values)
.nulls(nulls)
.build()
// TODO consider skipping the validation checks by using
// `new_unchecked`
.expect("Valid array data");
StringArray::from(data)
}
}
#[derive(Debug)]
pub struct PackedStringIterator<'a, K> {
array: &'a PackedStringArray<K>,
index: usize,
}
impl<'a, K: AsPrimitive<usize> + FromPrimitive + Zero> Iterator for PackedStringIterator<'a, K> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
let item = self.array.get(self.index)?;
self.index += 1;
Some(item)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.array.len() - self.index;
(len, Some(len))
}
}
#[cfg(test)]
mod tests {
use crate::string::PackedStringArray;
#[test]
fn test_storage() {
let mut array = PackedStringArray::<i32>::new();
array.append("hello");
array.append("world");
array.append("cupcake");
assert_eq!(array.get(0).unwrap(), "hello");
assert_eq!(array.get(1).unwrap(), "world");
assert_eq!(array.get(2).unwrap(), "cupcake");
assert!(array.get(-1_i32 as usize).is_none());
assert!(array.get(3).is_none());
array.extend(2);
assert_eq!(array.get(3).unwrap(), "");
assert_eq!(array.get(4).unwrap(), "");
assert!(array.get(5).is_none());
}
#[test]
fn test_empty() {
let array = PackedStringArray::<u8>::new_empty(20);
assert_eq!(array.get(12).unwrap(), "");
assert_eq!(array.get(9).unwrap(), "");
assert_eq!(array.get(3).unwrap(), "");
}
#[test]
fn test_truncate() {
let mut array = PackedStringArray::<i32>::new();
array.append("hello");
array.append("world");
array.append("cupcake");
array.truncate(1);
assert_eq!(array.len(), 1);
assert_eq!(array.get(0).unwrap(), "hello");
array.append("world");
assert_eq!(array.len(), 2);
assert_eq!(array.get(0).unwrap(), "hello");
assert_eq!(array.get(1).unwrap(), "world");
}
#[test]
fn test_extend_from() {
let mut a = PackedStringArray::<i32>::new();
a.append("hello");
a.append("world");
a.append("cupcake");
a.append("");
let mut b = PackedStringArray::<i32>::new();
b.append("foo");
b.append("bar");
a.extend_from(&b);
let a_content: Vec<_> = a.iter().collect();
assert_eq!(
a_content,
vec!["hello", "world", "cupcake", "", "foo", "bar"]
);
}
#[test]
fn test_extend_from_range() {
let mut a = PackedStringArray::<i32>::new();
a.append("hello");
a.append("world");
a.append("cupcake");
a.append("");
let mut b = PackedStringArray::<i32>::new();
b.append("foo");
b.append("bar");
b.append("");
b.append("fiz");
a.extend_from_range(&b, 1..3);
assert_eq!(a.len(), 6);
let a_content: Vec<_> = a.iter().collect();
assert_eq!(a_content, vec!["hello", "world", "cupcake", "", "bar", ""]);
// Should be a no-op
a.extend_from_range(&b, 0..0);
let a_content: Vec<_> = a.iter().collect();
assert_eq!(a_content, vec!["hello", "world", "cupcake", "", "bar", ""]);
a.extend_from_range(&b, 0..1);
let a_content: Vec<_> = a.iter().collect();
assert_eq!(
a_content,
vec!["hello", "world", "cupcake", "", "bar", "", "foo"]
);
a.extend_from_range(&b, 1..4);
let a_content: Vec<_> = a.iter().collect();
assert_eq!(
a_content,
vec!["hello", "world", "cupcake", "", "bar", "", "foo", "bar", "", "fiz"]
);
}
}
|
use super::log;
use super::model::{
ColumnHeader, ColumnType, CsvErrors, CsvError, StatementSelections, StatementSelection, StatementType, ColumnSelection, ColumnSource,
};
use csv::StringRecord;
use super::{DATETIME_FORMATS, DATE_FORMATS};
use chrono::{NaiveDate, NaiveDateTime};
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn generate_file(data: &str, statements: JsValue, corrections: JsValue, combine: bool) -> JsValue {
let combine_text = format!("combine: {}", combine);
log(&combine_text);
let statements: StatementSelections = match statements.into_serde() {
Ok(s) => s,
Err(_e) => {
return JsValue::from_str("Couldn't deserialize the statements, did the model change?");
}
};
let corrections: CsvErrors = match corrections.into_serde() {
Ok(c) => c,
Err(_) => {
return JsValue::from_str("Couldn't deserialize the Errors, did the model change?");
}
};
let results = match generate_statements(data, statements.value, corrections.value, combine) {
Ok(sql) => sql,
Err(e) => return JsValue::from_str(&e),
};
return JsValue::from_serde(&results).unwrap();
}
fn get_headers(reader: &mut csv::Reader<&[u8]>) -> Result<Vec<ColumnHeader>,String> {
let mut headers = Vec::new();
let header_value = match reader.headers() {
Ok(h) => h,
Err(_e) => {
return Err("Couldn't read the headers".to_string());
}
};
for (index, column) in header_value.iter().enumerate() {
let header = ColumnHeader {
name: column.to_string(),
index,
};
headers.push(header);
}
Ok(headers)
}
fn generate_statements(data: &str, statements: Vec<StatementSelection>, corrections: Vec<CsvError>, combine: bool) -> Result<Vec<String>, String> {
let mut reader = csv::ReaderBuilder::new()
.has_headers(true)
.from_reader(data.as_bytes());
let headers = get_headers(&mut reader)?;
let mut sql_by_rows = Vec::<(usize, String)>::new();
for(index, row) in reader.records().enumerate() {
let record = row
.map_err(|e|
format!("The .csv file could not be parsed. Internal Error: {}", e ))?;
if record.iter().all(|r| r.trim().is_empty()) {
continue;
}
for statement in &statements {
let sql = get_row_sql(statement, &record, index, &corrections, &headers);
sql_by_rows.push((statement.id, sql));
}
}
let mut files = Vec::new();
if combine {
let num_statements = statements.len();
let rows = sql_by_rows.chunks(num_statements);
let output = rows
.filter(|a| a.len() != 0)
.map(|row| row.iter().map(|(_, v)| v.to_string()).collect::<Vec<String>>().join("\n"))
.collect::<Vec<String>>()
.join("\n GO \n");
files.push(output);
} else {
for statement in &statements {
let output = sql_by_rows.iter()
.filter(|(k, _)| k == &statement.id)
.map(|(_, v)| v.to_string())
.collect::<Vec<String>>()
.join("\n");
files.push(output);
}
};
Ok(files)
}
fn get_row_sql(statement: &StatementSelection, record: &StringRecord, index: usize, corrections: &Vec<CsvError>, headers: &Vec<ColumnHeader>) -> String {
let mut outputs = Vec::new();
if let Some(selections) = &statement.column_selections {
for column in &selections.value {
match column.source {
ColumnSource::FreeText => {
let name: String = column.name.clone().unwrap();
let mut value: String = column.data.clone().unwrap();
value = format_value(column.r#type.clone(), &value);
outputs.push((name, value));
},
ColumnSource::CSV => {
outputs.push(get_column_value(statement.id, index, column, record, corrections, headers));
}
}
}
}
match statement.r#type {
StatementType::Insert => {
get_insert_statement(&outputs, statement)
},
StatementType::Update => {
get_update_statement(outputs, statement, record, index, corrections)
},
StatementType::Custom => {
statement.custom.clone().unwrap()
}
}
}
fn get_update_statement(values: Vec<(String, String)>, statement: &StatementSelection, record: &StringRecord, index: usize, corrections: &Vec<CsvError>) -> String{
let sets = values
.iter()
.map(|(c, v)| format!("{} = {}", c, v))
.collect::<Vec<String>>()
.join(", ");
let mut where_clause = String::new();
for (pos, condition) in statement.where_selections.iter().enumerate() {
let where_column_id = condition.value.unwrap();
let mut column_value = record[where_column_id].to_string();
if let Some(correction) = corrections.iter().find(|c| {
c.column_id == where_column_id
&& c.statement_id == statement.id
&& c.rows.iter().any(|&r| r == index)
}) {
column_value = correction.error_text.clone();
}
column_value = format_value(condition.r#type.clone().unwrap(), &mut column_value);
let condition_text = if pos == 0 { "" } else { "AND "};
let compare_text = if column_value == "NULL" { "IS" } else { "="};
where_clause = format!("{} {} {} {} {}", where_clause, condition_text, condition.key, compare_text, column_value);
}
format!(
"UPDATE {} SET {} WHERE {};",
statement.table, sets, where_clause
)
}
fn get_insert_statement(values: &Vec<(String, String)>, statement: &StatementSelection) -> String{
let column_names = values
.iter()
.map(|(c, _)| c.clone())
.collect::<Vec<String>>()
.join(", ");
let values = values
.iter()
.map(|(_, v)| v.clone())
.collect::<Vec<String>>()
.join(", ");
format!(
"INSERT INTO {} ({}) VALUES ({});",
statement.table, column_names, values
)
}
fn get_column_value(statement_id: usize, index: usize, column: &ColumnSelection, record: &StringRecord, corrections: &Vec<CsvError>, headers: &Vec<ColumnHeader> ) -> (String, String) {
let id = column.column.unwrap();
let mut value: String = record[id].to_string();
if let Some(correction) = corrections.iter().find(|c| {
c.column_id == id
&& c.statement_id == statement_id
&& c.rows.iter().any(|&r| r == index)
}) {
value = correction.error_text.clone();
}
let name = match column.use_source {
true => headers.iter().find(|h| h.index == id).unwrap().name.clone(),
false => column.name.clone().unwrap(),
};
value = format_value(column.r#type.clone(), &value);
(name, value.to_string())
}
fn parse_datetime(value: &str) -> Result<NaiveDateTime, String> {
let value = value.trim();
for format in &DATETIME_FORMATS {
let parsed = NaiveDateTime::parse_from_str(value, format);
if parsed.is_ok() {
return Ok(parsed.unwrap());
}
}
for format in &DATE_FORMATS {
let parsed = NaiveDate::parse_from_str(value, format);
if parsed.is_ok() {
return Ok(parsed.unwrap().and_hms(0, 0, 0));
}
}
log("No Formats Match");
Err("No Formats Match".to_string())
}
fn is_null(value: &str) -> bool {
let value = value.trim();
value.to_lowercase() == "null"
}
fn format_value(column_type: ColumnType, value: &str) -> String{
let mut new_value = value.to_string();
match column_type {
ColumnType::VarChar => {
if !is_null(&value) {
new_value = str::replace(&value, "'", "''");
new_value = format!("'{}'", new_value);
} else {
new_value = "NULL".to_string();
}
}
ColumnType::Date => {
if !is_null(&value) {
let date = parse_datetime(&value);
if date.is_ok() {
new_value = date.unwrap().format("%Y-%m-%d").to_string();
}
new_value = format!("'{}'", new_value);
} else {
new_value = "NULL".to_string();
}
}
ColumnType::DateTime => {
if !is_null(&value) {
let date = parse_datetime(&value);
if date.is_ok() {
new_value = date.unwrap().format("%Y-%m-%d %H:%M:%S").to_string();
}
new_value = format!("'{}'", new_value);
} else {
new_value = "NULL".to_string();
}
}
_ => {}
}
new_value
} |
use ed25519_dalek::{
Keypair,
PublicKey,
Signature,
Signer,
};
use types::{
SecretKey,
};
pub fn sign(secret_key: SecretKey, message_bytes: [u8;32]) -> String {
match secret_key {
SecretKey::Ed25519(secret_key) => {
let pub_key: PublicKey = (&secret_key).into();
let pair = Keypair{
secret: secret_key,
public: pub_key,
};
let signature: Signature = pair.sign(&message_bytes);
hex::encode(signature.to_bytes())
},
_ => panic!("secret key should be a Ed25519"),
}
} |
//! Easier handling of mouse events.
//!
//! Handling the various permutations and combinations of mouse events is messy,
//! repetitive, and error prone.
//!
//! This module implements a state machine that handles the raw event processing,
//! identifying important events and transitions.
//!
//! # Use
//!
//! The state machine itself is exposed via the [`Mouse`] struct. You are
//! responsible for instantiating this struct, and it is expected to persist
//! between mouse events.
//!
//! To react to state changes, you must implement the [`MouseDelegate`] trait;
//! you only need to implement the methods you are interested in.
//!
//! When a mouse event arrives, you pass the event along with your delegate to
//! the [`Mouse`] struct; if that event causes a state change, the corresponding
//! method on your delegate will be called.
//!
//! # Example
//! ```
//! use runebender_lib::mouse::{Mouse, MouseDelegate};
//! use druid::{Modifiers, MouseEvent, MouseButton, MouseButtons, Point, Vec2};
//!
//! struct SimpleDelegate(usize);
//!
//! impl MouseDelegate<()> for SimpleDelegate {
//! fn left_click(&mut self, _event: &MouseEvent, _data: &mut ()) {
//! self.0 += 1;
//! }
//!
//! fn cancel(&mut self, _: &mut ()) {}
//! }
//!
//! let event = MouseEvent {
//! pos: Point::new(20., 20.,),
//! window_pos: Point::new(20., 20.,),
//! mods: Modifiers::empty(),
//! count: 1,
//! button: MouseButton::Left,
//! buttons: MouseButtons::new().with(MouseButton::Left),
//! focus: false,
//! wheel_delta: Vec2::ZERO,
//! };
//!
//! let mut mouse = Mouse::default();
//! let mut delegate = SimpleDelegate(0);
//! mouse.mouse_down(event.clone(), &mut (), &mut delegate);
//! assert_eq!(delegate.0, 0);
//! mouse.mouse_up(event.clone(), &mut (), &mut delegate);
//! assert_eq!(delegate.0, 1);
//! ```
use druid::kurbo::Point;
use druid::{Modifiers, MouseButton, MouseButtons, MouseEvent};
use std::mem;
const DEFAULT_MIN_DRAG_DISTANCE: f64 = 2.0;
/// Handles raw mouse events, parsing them into gestures that it forwards
/// to a delegate.
#[derive(Debug, Clone)]
pub struct Mouse {
state: MouseState,
/// The distance the mouse must travel with a button down for it to
/// be considered a drag gesture.
pub min_drag_distance: f64,
}
/// A convenience type for passing around mouse events while keeping track
/// of the event type.
#[derive(Debug, Clone)]
pub enum TaggedEvent {
Down(MouseEvent),
Up(MouseEvent),
Moved(MouseEvent),
}
#[derive(Debug, Clone)]
enum MouseState {
/// No mouse buttons are active.
Up(MouseEvent),
/// A mouse button has been pressed.
Down(MouseEvent),
/// The mouse has been moved some threshold distance with a button pressed.
Drag {
start: MouseEvent,
current: MouseEvent,
},
/// A state only used as a placeholder during event handling.
#[doc(hidden)]
Transition,
}
/// The state of an in-progress drag gesture.
#[derive(Debug, Clone, Copy)]
#[allow(unused)]
pub struct Drag<'a> {
/// The event that started this drag
pub start: &'a MouseEvent,
/// The previous event in this drag
pub prev: &'a MouseEvent,
/// The current event in this drag
pub current: &'a MouseEvent,
}
/// A trait for types that want fine grained information about mouse events.
pub trait MouseDelegate<T> {
/// Called on any mouse movement.
#[allow(unused)]
fn mouse_moved(&mut self, _event: &MouseEvent, _data: &mut T) {}
/// Called when the left mouse button is pressed.
#[allow(unused)]
fn left_down(&mut self, _event: &MouseEvent, _data: &mut T) {}
/// Called when the left mouse button is released.
#[allow(unused)]
fn left_up(&mut self, _event: &MouseEvent, _data: &mut T) {}
/// Called when the left mouse button is released, if there has not already
/// been a drag event.
#[allow(unused)]
fn left_click(&mut self, _event: &MouseEvent, _data: &mut T) {}
/// Called when the mouse moves a minimum distance with the left mouse
/// button pressed.
#[allow(unused)]
fn left_drag_began(&mut self, _drag: Drag, _data: &mut T) {}
/// Called when the mouse moves after a drag gesture has been recognized.
#[allow(unused)]
fn left_drag_changed(&mut self, _drag: Drag, _data: &mut T) {}
/// Called when the left mouse button is released, after a drag gesture
/// has been recognized.
#[allow(unused)]
fn left_drag_ended(&mut self, _drag: Drag, _data: &mut T) {}
/// Called when the right mouse button is pressed.
#[allow(unused)]
fn right_down(&mut self, _event: &MouseEvent, _data: &mut T) {}
/// Called when the right mouse button is released.
#[allow(unused)]
fn right_up(&mut self, _event: &MouseEvent, _data: &mut T) {}
/// Called when the right mouse button is released, if there has not already
/// been a drag event.
#[allow(unused)]
fn right_click(&mut self, _event: &MouseEvent, _data: &mut T) {}
/// Called when the mouse moves a minimum distance with the right mouse
/// button pressed.
#[allow(unused)]
fn right_drag_began(&mut self, _drag: Drag, _data: &mut T) {}
/// Called when the mouse moves after a drag gesture has been recognized.
#[allow(unused)]
fn right_drag_changed(&mut self, _drag: Drag, _data: &mut T) {}
/// Called when the right mouse button is released, after a drag gesture
/// has been recognized.
#[allow(unused)]
fn right_drag_ended(&mut self, _drag: Drag, _data: &mut T) {}
#[allow(unused)]
fn other_down(&mut self, _event: &MouseEvent, _data: &mut T) {}
#[allow(unused)]
fn other_up(&mut self, _event: &MouseEvent, _data: &mut T) {}
#[allow(unused)]
fn other_click(&mut self, _event: &MouseEvent, _data: &mut T) {}
#[allow(unused)]
fn other_drag_began(&mut self, _drag: Drag, _data: &mut T) {}
#[allow(unused)]
fn other_drag_changed(&mut self, _drag: Drag, _data: &mut T) {}
#[allow(unused)]
fn other_drag_ended(&mut self, _drag: Drag, _data: &mut T) {}
#[allow(unused)]
fn cancel(&mut self, data: &mut T);
}
impl std::default::Default for Mouse {
fn default() -> Mouse {
Mouse {
min_drag_distance: DEFAULT_MIN_DRAG_DISTANCE,
state: MouseState::Up(MouseEvent {
pos: Point::ZERO,
window_pos: Point::ZERO,
mods: Modifiers::default(),
count: 0,
button: MouseButton::None,
buttons: MouseButtons::default(),
focus: false,
wheel_delta: Default::default(),
}),
}
}
}
impl TaggedEvent {
pub fn inner(&self) -> &MouseEvent {
match self {
TaggedEvent::Down(m) => m,
TaggedEvent::Up(m) => m,
TaggedEvent::Moved(m) => m,
}
}
}
impl Mouse {
/// reset any settable internal state to its default value.
pub fn reset(&mut self) {
self.min_drag_distance = DEFAULT_MIN_DRAG_DISTANCE;
}
/// The current position of the mouse.
#[allow(dead_code)]
pub fn pos(&self) -> Point {
match &self.state {
MouseState::Up(e) => e.pos,
MouseState::Down(e) => e.pos,
MouseState::Drag { current, .. } => current.pos,
_ => panic!("transition is not an actual state :/"),
}
}
pub fn mouse_event<T>(
&mut self,
event: TaggedEvent,
data: &mut T,
delegate: &mut dyn MouseDelegate<T>,
) {
match event {
TaggedEvent::Up(event) => self.mouse_up(event, data, delegate),
TaggedEvent::Down(event) => self.mouse_down(event, data, delegate),
TaggedEvent::Moved(event) => self.mouse_moved(event, data, delegate),
}
}
pub fn mouse_moved<T>(
&mut self,
event: MouseEvent,
data: &mut T,
delegate: &mut dyn MouseDelegate<T>,
) {
let prev_state = mem::replace(&mut self.state, MouseState::Transition);
self.state = match prev_state {
MouseState::Up(_) => {
delegate.mouse_moved(&event, data);
MouseState::Up(event)
}
MouseState::Down(prev) => {
if prev.pos.distance(event.pos) > self.min_drag_distance {
let drag = Drag::new(&prev, &prev, &event);
if prev.button.is_left() {
delegate.left_drag_began(drag, data)
} else if prev.button.is_right() {
delegate.right_drag_began(drag, data)
} else {
delegate.other_drag_began(drag, data)
};
MouseState::Drag {
start: prev,
current: event,
}
} else {
MouseState::Down(prev)
}
}
MouseState::Drag { start, current } => {
let drag = Drag::new(&start, ¤t, &event);
if start.button.is_left() {
delegate.left_drag_changed(drag, data)
} else if start.button.is_right() {
delegate.right_drag_changed(drag, data)
} else {
delegate.other_drag_changed(drag, data)
};
MouseState::Drag {
start,
current: event,
}
}
MouseState::Transition => panic!("ahhhhhhh"),
};
}
pub fn mouse_down<T>(
&mut self,
event: MouseEvent,
data: &mut T,
delegate: &mut dyn MouseDelegate<T>,
) {
let prev_state = mem::replace(&mut self.state, MouseState::Transition);
self.state = match prev_state {
MouseState::Up(_) => {
if event.button.is_left() {
delegate.left_down(&event, data)
} else if event.button.is_right() {
delegate.right_down(&event, data)
} else {
delegate.other_down(&event, data)
};
MouseState::Down(event)
}
MouseState::Down(prev) => {
assert!(prev.button != event.button);
// if a second button is pressed while we're handling an event
// we just ignore it. At some point we could consider an event for this.
MouseState::Down(prev)
}
MouseState::Drag { start, .. } => {
if start.button != event.button {
log::warn!("mouse click while drag in progress; not correctly receiving mouse up events?");
}
MouseState::Drag {
start,
current: event,
}
}
MouseState::Transition => panic!("ahhhhhhh"),
};
}
pub fn mouse_up<T>(
&mut self,
event: MouseEvent,
data: &mut T,
delegate: &mut dyn MouseDelegate<T>,
) {
let prev_state = mem::replace(&mut self.state, MouseState::Transition);
self.state = match prev_state {
MouseState::Up(_) => MouseState::Up(event),
MouseState::Down(prev) => {
if event.button == prev.button {
if prev.button.is_left() {
delegate.left_click(&event, data);
delegate.left_up(&event, data);
} else if prev.button.is_right() {
delegate.right_click(&event, data);
delegate.right_up(&event, data);
} else {
delegate.other_click(&event, data);
delegate.other_up(&event, data);
};
MouseState::Up(event)
} else {
MouseState::Down(prev)
}
}
MouseState::Drag { start, current } => {
if event.button == start.button {
let drag = Drag {
start: &start,
current: &event,
prev: ¤t,
};
if start.button.is_left() {
delegate.left_drag_ended(drag, data);
delegate.left_up(&event, data);
} else if start.button.is_right() {
delegate.right_drag_ended(drag, data);
delegate.right_up(&event, data);
} else {
delegate.other_drag_ended(drag, data);
delegate.other_up(&event, data);
};
MouseState::Up(event)
} else {
MouseState::Drag { start, current }
}
}
MouseState::Transition => panic!("ahhhhhhh"),
};
}
pub fn cancel<T>(&mut self, data: &mut T, delegate: &mut dyn MouseDelegate<T>) {
let prev_state = mem::replace(&mut self.state, MouseState::Transition);
let last_event = match prev_state {
MouseState::Down(event) => event,
MouseState::Up(event) => event,
MouseState::Drag { current, .. } => current,
MouseState::Transition => panic!("ahhhhhhh"),
};
delegate.cancel(data);
self.state = MouseState::Up(last_event);
}
}
impl<'a> Drag<'a> {
fn new(start: &'a MouseEvent, prev: &'a MouseEvent, current: &'a MouseEvent) -> Drag<'a> {
Drag {
start,
prev,
current,
}
}
}
|
use std::collections::{HashMap, HashSet};
use parser::types::{Statement, ProgramError, Pass, StatementType, SourceCodeLocation, ExpressionType, Expression, StatementFactory, ExpressionFactory, TokenType};
pub fn leak_reference<'a, T>(s: T) -> &'a T {
Box::leak(Box::new(s))
}
pub struct LambdaLifting<'a> {
change_name: bool,
changes: HashMap<usize, ExpressionType<'a>>,
class_counter: usize,
class_scope: Option<usize>,
current_location: Option<SourceCodeLocation<'a>>,
expression_factory: ExpressionFactory,
function_counter: usize,
locals: HashMap<usize, usize>,
missed_locals: Vec<HashSet<&'a str>>,
module_counter: usize,
output: Vec<Statement<'a>>,
scopes: Vec<HashMap<&'a str, &'a str>>,
statement_factory: StatementFactory,
statement_changes: HashMap<usize, StatementType<'a>>,
trait_counter: usize,
}
impl<'a> LambdaLifting<'a> {
pub fn new(
locals: HashMap<usize, usize>,
statement_factory: StatementFactory,
expression_factory: ExpressionFactory,
) -> LambdaLifting<'a> {
LambdaLifting {
change_name: true,
changes: HashMap::default(),
class_counter: 0,
class_scope: None,
current_location: None,
function_counter: 0,
missed_locals: Vec::default(),
module_counter: 0,
output: Vec::default(),
scopes: vec![HashMap::default()],
statement_changes: HashMap::default(),
trait_counter: 0,
expression_factory,
locals,
statement_factory,
}
}
fn create_new_function(
&mut self,
arguments: Option<&'a [&'a str]>,
body: Vec<Box<Statement<'a>>>,
) -> Result<&'static str, Vec<ProgramError<'a>>> {
let new_function_name = leak_reference(format!("@function{}", self.function_counter));
self.function_counter += 1;
let function_definition = self.statement_factory.new_statement(
self.current_location.clone().unwrap(),
StatementType::FunctionDeclaration {
name: new_function_name,
arguments: arguments.map(|a| a.to_vec()).unwrap_or(vec![]),
context_variables: vec![],
body,
},
);
/*
* This is a bit of black magic. What is happening here:
* - We get the static, raw pointer to a leaked reference to function_definition.
* - We "pass" that pointer.
* - We then wrap it again into a Box to make sure it's properly cleaned after.
* Why we can't use references:
* - We cannot use a reference to `function-definition`, because is a scope lived and would
* not live for 'a.
* - We cannot use a reference to the last element in self.output because self does not live
* for 'a.
* - We cannot leak a Box, because we won't have any way to clean after: Since `pass` asks
* for the statement to live for 'a, and Box::from_raw requires a mutable reference, we won't
* be able to make the conversion.
* Why is this safe:
* The danger is that pass would store a reference to something inside function_definition
* that would later be dropped. However, this class does not do that and rather copies all
* values.
*/
let r = Box::into_raw(Box::new(function_definition));
self.change_name = false;
self.pass(unsafe { r.as_ref() }.unwrap())?;
let _ = unsafe { Box::from_raw(r) };
Ok(new_function_name)
}
fn class_methods_to_variable_accessors(&mut self, methods: &'a [Box<Statement<'a>>]) -> Result<Vec<Box<Statement<'a>>>, Vec<ProgramError<'a>>> {
methods.iter().map(|s| {
self.pass(s)?;
if let (StatementType::FunctionDeclaration { name, .. },
StatementType::FunctionDeclaration { name: new_name, .. }) =
(&s.statement_type, &self.output.last().unwrap().statement_type) {
let right = Box::new(self.expression_factory.new_expression(
ExpressionType::VariableLiteral { identifier: name },
s.location.clone(),
));
let left = Box::new(self.expression_factory.new_expression(
ExpressionType::VariableLiteral { identifier: new_name },
s.location.clone(),
));
let expression = self.expression_factory.new_expression(
ExpressionType::Binary { left, right, operator: TokenType::Comma, },
s.location.clone(),
);
Ok(Box::new(self.statement_factory.new_statement(
s.location.clone(),
StatementType::Expression { expression },
)))
} else {
panic!("Last statement should be a function!")
}
}).collect()
}
fn change_variable_literal(
&mut self,
identifier: &'a str,
expression: &'a Expression<'a>,
) -> Option<ExpressionType<'a>> {
let expression_id = expression.id();
if let Some(scope) = self.locals.get(&expression_id).cloned() {
if scope > 0 && scope < self.scopes.len() - 1 {
if self.class_scope.unwrap_or(0) == scope {
return Some(ExpressionType::Get {
callee: Box::new(self.expression_factory.new_expression(
ExpressionType::VariableLiteral {
identifier: "this",
},
expression.location.clone()
)),
property: identifier,
});
} else {
self.missed_locals.last_mut().unwrap().insert(identifier);
}
}
if let Some(new_identifier) = self.scopes.get(scope).map(|v| v.get(identifier)).flatten().cloned() {
Some(ExpressionType::VariableLiteral {
identifier: new_identifier,
})
} else {
None
}
} else {
None
}
}
}
type LambdaLiftingResult<'a> = (Vec<Statement<'a>>, HashMap<usize, ExpressionType<'a>>, HashMap<usize, StatementType<'a>>);
pub fn variable_or_module_name<'a>(expression: &'a Expression<'a>) -> Result<&'a str, Vec<ProgramError<'a>>> {
match expression.expression_type {
ExpressionType::VariableLiteral { identifier } => Ok(identifier),
_ => Err(vec![ProgramError {
location: expression.location.clone(),
message: "Expected variable literal".to_string()
}])?,
}
}
impl<'a> Pass<'a, LambdaLiftingResult<'a>> for LambdaLifting<'a> {
fn run(&mut self, ss: &'a [Statement<'a>]) -> Result<LambdaLiftingResult<'a>, Vec<ProgramError<'a>>> {
for s in ss {
self.current_location = Some(s.location.clone());
if self.scopes.len() == 1 && !s.is_function_declaration() &&
!s.is_class_declaration() && !s.is_trait_declaration() && !s.is_module_declaration() {
self.output.push(s.clone());
}
self.pass(s)?;
}
Ok((self.output.clone(), self.changes.clone(), self.statement_changes.clone()))
}
fn pass_block(
&mut self,
body: &'a [Box<Statement<'a>>],
statement_id: usize,
) -> Result<(), Vec<ProgramError<'a>>> {
let mut body = body.to_vec();
body.push(Box::new(self.statement_factory.new_statement(
self.current_location.clone().unwrap(),
StatementType::Return { value: None },
)));
let new_function_name = self.create_new_function(None, body)?;
let callee = Box::new(self.expression_factory.new_expression(
ExpressionType::VariableLiteral {
identifier: new_function_name,
},
self.current_location.clone().unwrap(),
));
let expression = ExpressionType::Binary {
left: Box::new(self.expression_factory.new_expression(
ExpressionType::UpliftFunctionVariables(new_function_name),
self.current_location.clone().unwrap(),
)),
operator: TokenType::Bar,
right: Box::new(self.expression_factory.new_expression(
ExpressionType::Call {
arguments: vec![],
callee,
},
self.current_location.clone().unwrap(),
)),
};
self.statement_changes.insert(statement_id, StatementType::Expression {
expression: self.expression_factory.new_expression(
expression,
self.current_location.clone().unwrap()
),
});
Ok(())
}
fn pass_class_declaration(
&mut self,
name: &'a str,
properties: &'a [Box<Statement<'a>>],
methods: &'a [Box<Statement<'a>>],
static_methods: &'a [Box<Statement<'a>>],
setters: &'a [Box<Statement<'a>>],
getters: &'a [Box<Statement<'a>>],
superclass: &'a Option<Expression<'a>>,
statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let new_class_name = leak_reference(format!("@class{}", self.class_counter));
self.class_counter += 1;
let scope = self.scopes.len()-1;
self.scopes[scope].insert(name, new_class_name);
self.scopes.push(HashMap::default());
self.class_scope = Some(scope+1);
let new_methods = self.class_methods_to_variable_accessors(methods)?;
let new_static_methods = self.class_methods_to_variable_accessors(static_methods)?;
let new_getters = self.class_methods_to_variable_accessors(getters)?;
let new_setters = self.class_methods_to_variable_accessors(setters)?;
let new_superclass = match superclass {
Some(s) => {
match &s.expression_type {
ExpressionType::VariableLiteral { identifier } => {
self.change_variable_literal(identifier, s)
.map(|et| {
self.expression_factory.new_expression(et, s.location.clone())
})
}
_ => None,
}
},
_ => None,
};
self.scopes.pop();
self.class_scope = None;
self.output.push(self.statement_factory.new_statement(
statement.location.clone(),
StatementType::ClassDeclaration {
name: new_class_name,
properties: properties.to_vec(),
superclass: new_superclass,
methods: new_methods,
static_methods: new_static_methods,
getters: new_getters,
setters: new_setters,
},
));
Ok(())
}
fn pass_trait_declaration(
&mut self,
name: &'a str,
statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let new_trait_name = leak_reference(format!("@trait{}", self.trait_counter));
self.trait_counter += 1;
let scope = self.scopes.len()-1;
self.scopes[scope].insert(name, new_trait_name);
if let StatementType::TraitDeclaration {
methods, getters, setters, static_methods, ..
} = &statement.statement_type {
self.output.push(self.statement_factory.new_statement(
statement.location.clone(),
StatementType::TraitDeclaration {
name: new_trait_name,
methods: methods.clone(),
getters: getters.clone(),
setters: setters.clone(),
static_methods: static_methods.clone()
}
));
}
Ok(())
}
fn pass_trait_implementation(
&mut self,
class_name: &'a Expression<'a>,
trait_name: &'a Expression<'a>,
methods: &'a [Box<Statement<'a>>],
static_methods: &'a [Box<Statement<'a>>],
setters: &'a [Box<Statement<'a>>],
getters: &'a [Box<Statement<'a>>],
statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
if let (Some(trait_scope), Some(class_scope)) =
(self.locals.get(&trait_name.id()).cloned(), self.locals.get(&class_name.id()).cloned()) {
let class_name_value = variable_or_module_name(class_name)?;
let trait_name_value = variable_or_module_name(trait_name)?;
if let (Some(new_class_name), Some(new_trait_name)) =
(self.scopes[class_scope].get(class_name_value).cloned(), self.scopes[trait_scope].get(trait_name_value).cloned()) {
self.scopes.push(HashMap::default());
let new_methods = self.class_methods_to_variable_accessors(methods)?;
let new_static_methods = self.class_methods_to_variable_accessors(static_methods)?;
let new_getters = self.class_methods_to_variable_accessors(getters)?;
let new_setters = self.class_methods_to_variable_accessors(setters)?;
self.scopes.pop();
self.statement_changes.insert(statement.id(), StatementType::TraitImplementation {
class_name: self.expression_factory.new_expression(
ExpressionType::VariableLiteral { identifier: new_class_name },
class_name.location.clone(),
),
trait_name: self.expression_factory.new_expression(
ExpressionType::VariableLiteral { identifier: new_trait_name },
trait_name.location.clone(),
),
methods: new_methods,
static_methods: new_static_methods,
getters: new_getters,
setters: new_setters,
});
}
if trait_scope > 0 && trait_scope < self.scopes.len() - 1 {
self.missed_locals.last_mut().unwrap().insert(trait_name_value);
}
if class_scope > 0 && class_scope < self.scopes.len() - 1 {
self.missed_locals.last_mut().unwrap().insert(class_name_value);
}
}
Ok(())
}
fn pass_function_declaration(
&mut self,
name: &'a str,
arguments: &'a [&'a str],
body: &'a [Box<Statement<'a>>],
statement: &'a Statement<'a>,
_context_variables: &'a [&'a str],
) -> Result<(), Vec<ProgramError<'a>>> {
let new_function_name = if self.change_name {
let new_function_name = leak_reference(format!("@function{}", self.function_counter));
self.function_counter += 1;
let scope = self.scopes.len()-1;
self.scopes[scope].insert(name, new_function_name);
new_function_name
} else {
name
};
self.change_name = true;
self.scopes.push(HashMap::default());
self.missed_locals.push(HashSet::default());
let mut new_body = vec![];
for s in body.iter() {
self.pass(s)?;
let statement = match &s.statement_type {
StatementType::FunctionDeclaration { name, .. } =>
Box::new(self.statement_factory.new_statement(
s.location.clone(),
StatementType::Expression {
expression: self.expression_factory.new_expression(
ExpressionType::UpliftFunctionVariables(self.scopes[self.scopes.len()-1][name]),
s.location.clone(),
)
},
)),
StatementType::ClassDeclaration { name, .. } =>
Box::new(self.statement_factory.new_statement(
s.location.clone(),
StatementType::Expression {
expression: self.expression_factory.new_expression(
ExpressionType::UpliftClassVariables(self.scopes[self.scopes.len()-1][name]),
s.location.clone(),
)
},
)),
_ => s.clone(),
};
new_body.push(statement);
}
self.scopes.pop();
let missed_locals = self.missed_locals.pop().unwrap().iter().cloned().collect::<Vec<&str>>();
self.output.push(self.statement_factory.new_statement(
statement.location.clone(),
StatementType::FunctionDeclaration {
name: new_function_name,
arguments: arguments.to_vec(),
body: new_body,
context_variables: missed_locals,
},
));
Ok(())
}
fn pass_variable_literal(
&mut self,
identifier: &'a str,
expression: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let expression_id = expression.id();
match self.change_variable_literal(identifier, expression) {
Some(new_expression_type) => {
self.changes.insert(expression_id, new_expression_type);
}
_ => {}
}
Ok(())
}
fn pass_variable_assignment(
&mut self,
identifier: &'a str,
value: &'a Expression<'a>,
expression: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let expression_id = expression.id();
if let Some(scope) = self.locals.get(&expression_id).cloned() {
if scope > 0 && scope < self.scopes.len() - 1 {
if self.class_scope.unwrap_or(0) == scope {
self.changes.insert(
expression_id,
ExpressionType::Set {
callee: Box::new(self.expression_factory.new_expression(
ExpressionType::VariableLiteral {
identifier: "this",
},
expression.location.clone()
)),
property: identifier,
value: Box::new(value.clone()),
}
);
} else {
self.missed_locals.last_mut().unwrap().insert(identifier);
}
}
}
self.pass_expression(value)?;
Ok(())
}
fn pass_anonymous_function(
&mut self,
arguments: &'a [&'a str],
body: &'a [Statement<'a>],
expression: &'a Expression<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let new_function_name = self.create_new_function(
Some(arguments),
body.iter().cloned().map(Box::new).collect()
)?;
self.changes.insert(expression.id(), ExpressionType::VariableLiteral {
identifier: new_function_name,
});
Ok(())
}
fn pass_module(
&mut self,
name: &'a str,
statements: &'a [Box<Statement<'a>>],
statement: &'a Statement<'a>,
) -> Result<(), Vec<ProgramError<'a>>> {
let new_module_name = leak_reference(format!("@module{}", self.module_counter));
self.module_counter += 1;
let scope = self.scopes.len()-1;
self.scopes[scope].insert(name, new_module_name);
self.scopes.push(HashMap::default());
self.scopes.pop();
self.output.push(self.statement_factory.new_statement(
statement.location.clone(),
StatementType::Module {
name: new_module_name,
statements: statements.to_vec(),
},
));
Ok(())
}
}
|
extern crate time;
use std::default::Default;
use sat::{PartialResult, TotalResult, Solver};
use sat::formula::{Var, Lit, LitMap};
use sat::formula::clause::*;
use sat::formula::assignment::*;
use self::clause_db::*;
use self::conflict::{AnalyzeContext, Seen, Conflict};
pub use self::conflict::CCMinMode;
use self::decision_heuristic::{DecisionHeuristicSettings, DecisionHeuristic};
pub use self::decision_heuristic::PhaseSaving;
mod budget;
mod clause_db;
mod conflict;
mod decision_heuristic;
pub mod simp;
mod util;
mod watches;
pub struct Settings {
pub heur : DecisionHeuristicSettings,
pub db : ClauseDBSettings,
pub ccmin_mode : CCMinMode,
pub restart : RestartStrategy,
pub learnt : LearningStrategySettings,
pub core : CoreSettings
}
impl Default for Settings {
fn default() -> Settings {
Settings { heur : Default::default()
, db : Default::default()
, ccmin_mode : CCMinMode::Deep
, restart : Default::default()
, learnt : Default::default()
, core : Default::default()
}
}
}
pub struct RestartStrategy {
pub luby_restart : bool,
pub restart_first : f64, // The initial restart limit.
pub restart_inc : f64 // The factor with which the restart limit is multiplied in each restart.
}
impl RestartStrategy {
pub fn conflictsToGo(&self, restarts : u32) -> u64 {
let rest_base =
if self.luby_restart {
util::luby(self.restart_inc, restarts)
} else {
self.restart_inc.powi(restarts as i32)
};
(rest_base * self.restart_first) as u64
}
}
impl Default for RestartStrategy {
fn default() -> RestartStrategy {
RestartStrategy { luby_restart : true
, restart_first : 100.0
, restart_inc : 2.0
}
}
}
pub struct LearningStrategySettings {
pub min_learnts_lim : i32, // Minimum number to set the learnts limit to.
pub size_factor : f64, // The intitial limit for learnt clauses is a factor of the original clauses.
pub size_inc : f64, // The limit for learnt clauses is multiplied with this factor each restart.
pub size_adjust_start_confl : i32,
pub size_adjust_inc : f64
}
impl Default for LearningStrategySettings {
fn default() -> LearningStrategySettings {
LearningStrategySettings { min_learnts_lim : 0
, size_factor : 1.0 / 3.0
, size_inc : 1.1
, size_adjust_start_confl : 100
, size_adjust_inc : 1.5
}
}
}
pub struct LearningStrategy {
settings : LearningStrategySettings,
max_learnts : f64,
size_adjust_confl : f64,
size_adjust_cnt : i32
}
impl LearningStrategy {
pub fn new(settings : LearningStrategySettings) -> LearningStrategy {
LearningStrategy { settings : settings
, max_learnts : 0.0
, size_adjust_confl : 0.0
, size_adjust_cnt : 0
}
}
pub fn reset(&mut self, clauses : usize) {
self.max_learnts = ((clauses as f64) * self.settings.size_factor).max(self.settings.min_learnts_lim as f64);
self.size_adjust_confl = self.settings.size_adjust_start_confl as f64;
self.size_adjust_cnt = self.settings.size_adjust_start_confl;
}
pub fn bump(&mut self) -> bool {
self.size_adjust_cnt -= 1;
if self.size_adjust_cnt == 0 {
self.size_adjust_confl *= self.settings.size_adjust_inc;
self.size_adjust_cnt = self.size_adjust_confl as i32;
self.max_learnts *= self.settings.size_inc;
true
} else {
false
}
}
pub fn border(&self) -> usize {
self.max_learnts as usize
}
}
struct SimplifyGuard {
simpDB_assigns : Option<usize>, // Number of top-level assignments since last execution of 'simplify()'.
simpDB_props : u64
}
impl SimplifyGuard {
pub fn new() -> SimplifyGuard {
SimplifyGuard { simpDB_assigns : None
, simpDB_props : 0
}
}
pub fn skip(&self, assigns : usize, propagations : u64) -> bool {
Some(assigns) == self.simpDB_assigns || propagations < self.simpDB_props
}
pub fn setNext(&mut self, assigns : usize, propagations : u64, prop_limit : u64) {
self.simpDB_assigns = Some(assigns);
self.simpDB_props = propagations + prop_limit;
}
}
enum SearchResult { UnSAT, SAT, Interrupted(f64), AssumpsConfl(LitMap<()>) }
pub struct CoreSettings {
pub garbage_frac : f64, // The fraction of wasted memory allowed before a garbage collection is triggered.
pub use_rcheck : bool, // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
}
impl Default for CoreSettings {
fn default() -> CoreSettings {
CoreSettings { garbage_frac : 0.20
, use_rcheck : false
}
}
}
#[derive(Default)]
struct Stats {
solves : u64,
starts : u64,
decisions : u64,
conflicts : u64,
start_time : f64
}
impl Stats {
pub fn new() -> Stats {
Stats { start_time : time::precise_time_s(), ..Default::default() }
}
}
pub struct CoreSolver {
settings : CoreSettings,
restart : RestartStrategy,
stats : Stats, // Statistics: (read-only member variable)
db : ClauseDB,
assigns : Assignment, // The current assignments.
watches : watches::Watches, // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
heur : DecisionHeuristic,
ok : bool, // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used!
simp : SimplifyGuard,
released_vars : Vec<Var>,
analyze : AnalyzeContext,
learnt : LearningStrategy,
budget : budget::Budget
}
impl Solver for CoreSolver {
fn nVars(&self) -> usize {
self.assigns.numberOfVars()
}
fn nClauses(&self) -> usize {
self.db.num_clauses
}
fn newVar(&mut self, upol : Option<bool>, dvar : bool) -> Var {
let v = self.assigns.newVar();
self.watches.initVar(v);
self.heur.initVar(v, upol, dvar);
self.analyze.initVar(v);
v
}
fn addClause(&mut self, clause : &[Lit]) -> bool {
match self.addClause_(clause) {
AddClause::UnSAT => { false }
_ => { true }
}
}
fn preprocess(&mut self) -> bool {
self.simplify()
}
fn solve(&mut self) -> TotalResult {
self.budget.off();
match self.solveLimited(&[]) {
PartialResult::UnSAT => { TotalResult::UnSAT }
PartialResult::SAT(model) => { TotalResult::SAT(model) }
PartialResult::Interrupted(_) => { TotalResult::Interrupted }
// _ => { panic!("Impossible happened") }
}
}
fn printStats(&self) {
let cpu_time = time::precise_time_s() - self.stats.start_time;
info!("restarts : {:<12}", self.stats.starts);
info!("conflicts : {:<12} ({:.0} /sec)",
self.stats.conflicts,
(self.stats.conflicts as f64) / cpu_time);
info!("decisions : {:<12} ({:4.2} % random) ({:.0} /sec)",
self.stats.decisions,
(self.heur.rnd_decisions as f64) * 100.0 / (self.stats.decisions as f64),
(self.stats.decisions as f64) / cpu_time);
info!("propagations : {:<12} ({:.0} /sec)",
self.watches.propagations,
(self.watches.propagations as f64) / cpu_time);
info!("conflict literals : {:<12} ({:4.2} % deleted)",
self.analyze.tot_literals,
((self.analyze.max_literals - self.analyze.tot_literals) as f64) * 100.0 / (self.analyze.max_literals as f64));
info!("Memory used : {:.2} MB", 0.0);
info!("CPU time : {} s", cpu_time);
info!("");
}
}
enum AddClause { UnSAT, Consumed, Added(ClauseRef) }
impl CoreSolver {
pub fn new(settings : Settings) -> CoreSolver {
CoreSolver { settings : settings.core
, restart : settings.restart
, stats : Stats::new()
, db : ClauseDB::new(settings.db)
, assigns : Assignment::new()
, watches : watches::Watches::new()
, heur : DecisionHeuristic::new(settings.heur)
, simp : SimplifyGuard::new()
, ok : true
, released_vars : Vec::new()
, analyze : AnalyzeContext::new(settings.ccmin_mode)
, learnt : LearningStrategy::new(settings.learnt)
, budget : budget::Budget::new()
}
}
fn addClause_(&mut self, clause : &[Lit]) -> AddClause {
assert!(self.assigns.isGroundLevel());
if !self.ok { return AddClause::UnSAT; }
// TODO: it should be here to work identical to original MiniSat. Probably not the best place.
if self.settings.use_rcheck && isImplied(self, &clause) {
return AddClause::Consumed;
}
let ps = {
let mut ps = clause.to_vec();
// Check if clause is satisfied and remove false/duplicate literals:
ps.sort();
ps.dedup();
ps.retain(|&lit| { !self.assigns.isUnsat(lit) });
{
let mut prev = None;
for &lit in ps.iter() {
if self.assigns.isSat(lit) || prev == Some(!lit) {
return AddClause::Consumed;
}
prev = Some(lit);
}
}
ps.into_boxed_slice()
};
match ps.len() {
0 => {
self.ok = false;
AddClause::UnSAT
}
1 => {
self.assigns.assignLit(ps[0], None);
match self.watches.propagate(&mut self.db.ca, &mut self.assigns) {
None => { AddClause::Consumed }
Some(_) => { self.ok = false; AddClause::UnSAT }
}
}
_ => {
let (c, cr) = self.db.addClause(ps);
self.watches.watchClause(c, cr);
AddClause::Added(cr)
}
}
}
// Description:
// Simplify the clause database according to the current top-level assigment. Currently, the only
// thing done here is the removal of satisfied clauses, but more things can be put here.
pub fn simplify(&mut self) -> bool {
assert!(self.assigns.isGroundLevel());
if !self.ok { return false; }
if let Some(_) = self.watches.propagate(&mut self.db.ca, &mut self.assigns) {
self.ok = false;
return false;
}
if self.simp.skip(self.assigns.numberOfAssigns(), self.watches.propagations) {
return true;
}
self.db.removeSatisfied(&mut self.assigns, &mut self.watches);
// TODO: why if?
if self.db.settings.remove_satisfied {
// Remove all released variables from the trail:
for v in self.released_vars.iter() {
assert!(self.analyze.seen[v] == Seen::Undef);
self.analyze.seen[v] = Seen::Source;
}
{
let seen = &self.analyze.seen;
self.assigns.retainAssignments(|l| { seen[&l.var()] == Seen::Undef });
}
for v in self.released_vars.iter() {
self.analyze.seen[v] = Seen::Undef;
}
// Released variables are now ready to be reused:
for &v in self.released_vars.iter() {
self.assigns.freeVar(v);
}
self.released_vars.clear();
}
if self.db.ca.checkGarbage(self.settings.garbage_frac) {
self.garbageCollect();
}
self.heur.rebuildOrderHeap(&self.assigns);
self.simp.setNext(self.assigns.numberOfAssigns(), self.watches.propagations, self.db.clauses_literals + self.db.learnts_literals); // (shouldn't depend on stats really, but it will do for now)
true
}
// Revert to the state at given level (keeping all assignment at 'level' but not beyond).
fn cancelUntil(&mut self, target_level : DecisionLevel) {
let ref mut heur = self.heur;
let top_level = self.assigns.decisionLevel();
self.assigns.rewindUntilLevel(target_level, |level, lit| { heur.cancel(lit, level == top_level); });
}
pub fn solveLimited(&mut self, assumptions : &[Lit]) -> PartialResult {
if !self.ok { return PartialResult::UnSAT; }
self.stats.solves += 1;
self.learnt.reset(self.db.num_clauses);
info!("============================[ Search Statistics ]==============================");
info!("| Conflicts | ORIGINAL | LEARNT | Progress |");
info!("| | Vars Clauses Literals | Limit Clauses Lit/Cl | |");
info!("===============================================================================");
let result = self.searchLoop(assumptions);
self.cancelUntil(GroundLevel);
info!("===============================================================================");
result
}
fn searchLoop(&mut self, assumptions : &[Lit]) -> PartialResult {
let mut curr_restarts = 0;
loop {
let conflicts_to_go = self.restart.conflictsToGo(curr_restarts);
curr_restarts += 1;
match self.search(conflicts_to_go, assumptions) {
SearchResult::SAT => {
return PartialResult::SAT(extractModel(&self.assigns));
}
SearchResult::UnSAT => {
self.ok = false;
return PartialResult::UnSAT;
}
SearchResult::AssumpsConfl(_) => { // TODO: implement
return PartialResult::UnSAT;
}
SearchResult::Interrupted(c) => {
if !self.budget.within(self.stats.conflicts, self.watches.propagations) {
return PartialResult::Interrupted(c);
}
}
}
}
}
// Description:
// Search for a model the specified number of conflicts.
// NOTE! Use negative value for 'nof_conflicts' indicate infinity.
//
// Output:
// 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If
// all variables are decision variables, this means that the clause set is satisfiable. 'l_False'
// if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached.
fn search(&mut self, nof_conflicts : u64, assumptions : &[Lit]) -> SearchResult {
assert!(self.ok);
self.stats.starts += 1;
let mut conflictC = 0;
loop {
match self.watches.propagate(&mut self.db.ca, &mut self.assigns) {
Some(confl) => {
self.stats.conflicts += 1;
conflictC += 1;
match self.analyze.analyze(&mut self.db, &mut self.heur, &self.assigns, confl) {
Conflict::Ground => {
return SearchResult::UnSAT;
}
Conflict::Unit(level, unit) => {
self.cancelUntil(level);
self.assigns.assignLit(unit, None);
}
Conflict::Learned(level, lit, clause) => {
self.cancelUntil(level);
let (c, cr) = self.db.learnClause(clause);
self.watches.watchClause(c, cr);
self.assigns.assignLit(lit, Some(cr));
}
}
self.heur.decayActivity();
self.db.decayActivity();
if self.learnt.bump() {
info!("| {:9} | {:7} {:8} {:8} | {:8} {:8} {:6.0} | {:6.3} % |",
self.stats.conflicts,
self.heur.dec_vars - self.assigns.numberOfGroundAssigns(),
self.nClauses(),
self.db.clauses_literals,
self.learnt.border(),
self.db.num_learnts,
(self.db.learnts_literals as f64) / (self.db.num_learnts as f64),
progressEstimate(&self.assigns) * 100.0);
}
}
None => {
if conflictC >= nof_conflicts || !self.budget.within(self.stats.conflicts, self.watches.propagations) {
// Reached bound on number of conflicts:
let progress_estimate = progressEstimate(&self.assigns);
self.cancelUntil(GroundLevel);
return SearchResult::Interrupted(progress_estimate);
}
// Simplify the set of problem clauses:
if self.assigns.isGroundLevel() && !self.simplify() {
return SearchResult::UnSAT;
}
if self.db.needReduce(self.assigns.numberOfAssigns() + self.learnt.border()) {
// Reduce the set of learnt clauses:
self.db.reduce(&mut self.assigns, &mut self.watches);
if self.db.ca.checkGarbage(self.settings.garbage_frac) {
self.garbageCollect();
}
}
let mut next = None;
while self.assigns.decisionLevel().offset() < assumptions.len() {
// Perform user provided assumption:
let p = assumptions[self.assigns.decisionLevel().offset()];
match self.assigns.ofLit(p) {
LitVal::True => {
// Dummy decision level:
self.assigns.newDecisionLevel();
}
LitVal::False => {
let conflict = self.analyze.analyzeFinal(&self.db.ca, &self.assigns, !p);
return SearchResult::AssumpsConfl(conflict);
}
LitVal::Undef => {
next = Some(p);
break;
}
}
}
if let None = next {
// New variable decision:
self.stats.decisions += 1;
match self.heur.pickBranchLit(&self.assigns) {
Some(n) => { next = Some(n) }
None => { return SearchResult::SAT; } // Model found:
};
}
// Increase decision level and enqueue 'next'
self.assigns.newDecisionLevel();
self.assigns.assignLit(next.unwrap(), None);
}
}
}
}
fn garbageCollect(&mut self) {
// Initialize the next region to a size corresponding to the estimated utilization degree. This
// is not precise but should avoid some unnecessary reallocations for the new region:
let to = ClauseAllocator::newForGC(&self.db.ca);
self.relocAll(to);
}
fn relocAll(&mut self, mut to : ClauseAllocator) {
self.watches.relocGC(&mut self.db.ca, &mut to);
self.assigns.relocGC(&mut self.db.ca, &mut to);
self.db.relocGC(to);
}
}
fn isImplied(core : &mut CoreSolver, c : &[Lit]) -> bool {
assert!(core.assigns.isGroundLevel());
core.assigns.newDecisionLevel();
for &lit in c.iter() {
match core.assigns.ofLit(lit) {
LitVal::True => { core.cancelUntil(GroundLevel); return true; }
LitVal::Undef => { core.assigns.assignLit(!lit, None); }
LitVal::False => {}
}
}
let result = core.watches.propagate(&mut core.db.ca, &mut core.assigns).is_some();
core.cancelUntil(GroundLevel);
return result;
}
|
#[cfg(test)]
mod test {
use crate::data_structures::linked_list_persistent::{LinkedListPersistent};
#[test]
fn basics() {
let list = LinkedListPersistent::new();
assert_eq!(list.head(), None);
let list = list.append(1).append(2).append(3);
assert_eq!(list.head(), Some(&3));
let list = list.tail();
assert_eq!(list.head(), Some(&2));
let list = list.tail();
assert_eq!(list.head(), Some(&1));
let list = list.tail();
assert_eq!(list.head(), None);
// Make sure empty tail works
let list = list.tail();
assert_eq!(list.head(), None);
}
#[test]
fn iter() {
let list = LinkedListPersistent::new().append(1).append(2).append(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
}
} |
#[path = "with_link_in_options_list/with_arity_zero.rs"]
mod with_arity_zero;
test_stdout!(without_arity_zero_returns_pid_to_parent_and_child_process_exits_badarity_which_exits_linked_parent, "{parent, badarity}\n");
|
/// HTTP Server handlers for serving static files
pub mod serve_static;
/// HTTP Server handlers for printing logs
pub mod print_log;
|
import vec::len;
import vec::slice;
import ilen = ivec::len;
import islice = ivec::slice;
export ivector;
export lteq;
export merge_sort;
export quick_sort;
export quick_sort3;
type lteq[T] = fn(&T, &T) -> bool ;
fn merge_sort[@T](le: lteq[T], v: vec[T]) -> vec[T] {
fn merge[@T](le: lteq[T], a: vec[T], b: vec[T]) -> vec[T] {
let rs: vec[T] = [];
let a_len: uint = len[T](a);
let a_ix: uint = 0u;
let b_len: uint = len[T](b);
let b_ix: uint = 0u;
while a_ix < a_len && b_ix < b_len {
if le(a.(a_ix), b.(b_ix)) {
rs += [a.(a_ix)];
a_ix += 1u;
} else { rs += [b.(b_ix)]; b_ix += 1u; }
}
rs += slice[T](a, a_ix, a_len);
rs += slice[T](b, b_ix, b_len);
ret rs;
}
let v_len: uint = len[T](v);
if v_len <= 1u { ret v; }
let mid: uint = v_len / 2u;
let a: vec[T] = slice[T](v, 0u, mid);
let b: vec[T] = slice[T](v, mid, v_len);
ret merge[T](le, merge_sort[T](le, a), merge_sort[T](le, b));
}
fn swap[@T](arr: vec[mutable T], x: uint, y: uint) {
let a = arr.(x);
arr.(x) = arr.(y);
arr.(y) = a;
}
fn part[@T](compare_func: lteq[T], arr: vec[mutable T], left: uint,
right: uint, pivot: uint) -> uint {
let pivot_value = arr.(pivot);
swap[T](arr, pivot, right);
let storage_index: uint = left;
let i: uint = left;
while i < right {
if compare_func({ arr.(i) }, pivot_value) {
swap[T](arr, i, storage_index);
storage_index += 1u;
}
i += 1u;
}
swap[T](arr, storage_index, right);
ret storage_index;
}
fn qsort[@T](compare_func: lteq[T], arr: vec[mutable T], left: uint,
right: uint) {
if right > left {
let pivot = (left + right) / 2u;
let new_pivot = part[T](compare_func, arr, left, right, pivot);
if new_pivot != 0u {
// Need to do this check before recursing due to overflow
qsort[T](compare_func, arr, left, new_pivot - 1u);
}
qsort[T](compare_func, arr, new_pivot + 1u, right);
}
}
fn quick_sort[@T](compare_func: lteq[T], arr: vec[mutable T]) {
if len[T](arr) == 0u { ret; }
qsort[T](compare_func, arr, 0u, len[T](arr) - 1u);
}
// Based on algorithm presented by Sedgewick and Bentley here:
// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
// According to these slides this is the algorithm of choice for
// 'randomly ordered keys, abstract compare' & 'small number of key values'
fn qsort3[@T](compare_func_lt: lteq[T], compare_func_eq: lteq[T],
arr: vec[mutable T], left: int, right: int) {
if right <= left { ret; }
let v: T = arr.(right);
let i: int = left - 1;
let j: int = right;
let p: int = i;
let q: int = j;
while true {
i += 1;
while compare_func_lt({ arr.(i) }, v) { i += 1; }
j -= 1;
while compare_func_lt(v, { arr.(j) }) {
if j == left { break; }
j -= 1;
}
if i >= j { break; }
swap[T](arr, i as uint, j as uint);
if compare_func_eq({ arr.(i) }, v) {
p += 1;
swap[T](arr, p as uint, i as uint);
}
if compare_func_eq(v, { arr.(j) }) {
q -= 1;
swap[T](arr, j as uint, q as uint);
}
}
swap[T](arr, i as uint, right as uint);
j = i - 1;
i += 1;
let k: int = left;
while k < p {
swap[T](arr, k as uint, j as uint);
k += 1;
j -= 1;
if k == vec::len[T](arr) as int { break; }
}
k = right - 1;
while k > q {
swap[T](arr, i as uint, k as uint);
k -= 1;
i += 1;
if k == 0 { break; }
}
qsort3[T](compare_func_lt, compare_func_eq, arr, left, j);
qsort3[T](compare_func_lt, compare_func_eq, arr, i, right);
}
fn quick_sort3[@T](compare_func_lt: lteq[T], compare_func_eq: lteq[T],
arr: vec[mutable T]) {
if vec::len[T](arr) == 0u { ret; }
qsort3[T](compare_func_lt, compare_func_eq, arr, 0,
(vec::len[T](arr) as int) - 1);
}
mod ivector {
export merge_sort;
export quick_sort;
export quick_sort3;
type lteq[T] = fn(&T, &T) -> bool ;
fn merge_sort[@T](le: lteq[T], v: &T[]) -> T[] {
fn merge[@T](le: lteq[T], a: &T[], b: &T[]) -> T[] {
let rs: T[] = ~[];
let a_len: uint = ilen[T](a);
let a_ix: uint = 0u;
let b_len: uint = ilen[T](b);
let b_ix: uint = 0u;
while a_ix < a_len && b_ix < b_len {
if le(a.(a_ix), b.(b_ix)) {
rs += ~[a.(a_ix)];
a_ix += 1u;
} else { rs += ~[b.(b_ix)]; b_ix += 1u; }
}
rs += islice[T](a, a_ix, a_len);
rs += islice[T](b, b_ix, b_len);
ret rs;
}
let v_len: uint = ilen[T](v);
if v_len <= 1u { ret v; }
let mid: uint = v_len / 2u;
let a: T[] = islice[T](v, 0u, mid);
let b: T[] = islice[T](v, mid, v_len);
ret merge[T](le, merge_sort[T](le, a), merge_sort[T](le, b));
}
fn swap[@T](arr: &T[mutable ], x: uint, y: uint) {
let a = arr.(x);
arr.(x) = arr.(y);
arr.(y) = a;
}
fn part[@T](compare_func: lteq[T], arr: &T[mutable ], left: uint,
right: uint, pivot: uint) -> uint {
let pivot_value = arr.(pivot);
swap[T](arr, pivot, right);
let storage_index: uint = left;
let i: uint = left;
while i < right {
if compare_func({ arr.(i) }, pivot_value) {
swap[T](arr, i, storage_index);
storage_index += 1u;
}
i += 1u;
}
swap[T](arr, storage_index, right);
ret storage_index;
}
fn qsort[@T](compare_func: lteq[T], arr: &T[mutable ], left: uint,
right: uint) {
if right > left {
let pivot = (left + right) / 2u;
let new_pivot = part[T](compare_func, arr, left, right, pivot);
if new_pivot != 0u {
// Need to do this check before recursing due to overflow
qsort[T](compare_func, arr, left, new_pivot - 1u);
}
qsort[T](compare_func, arr, new_pivot + 1u, right);
}
}
fn quick_sort[@T](compare_func: lteq[T], arr: &T[mutable ]) {
if ilen[T](arr) == 0u { ret; }
qsort[T](compare_func, arr, 0u, ilen[T](arr) - 1u);
}
// Based on algorithm presented by Sedgewick and Bentley here:
// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
// According to these slides this is the algorithm of choice for
// 'randomly ordered keys, abstract compare' & 'small number of key
// values'
fn qsort3[@T](compare_func_lt: lteq[T], compare_func_eq: lteq[T],
arr: &T[mutable ], left: int, right: int) {
if right <= left { ret; }
let v: T = arr.(right);
let i: int = left - 1;
let j: int = right;
let p: int = i;
let q: int = j;
while true {
i += 1;
while compare_func_lt({ arr.(i) }, v) { i += 1; }
j -= 1;
while compare_func_lt(v, { arr.(j) }) {
if j == left { break; }
j -= 1;
}
if i >= j { break; }
swap[T](arr, i as uint, j as uint);
if compare_func_eq({ arr.(i) }, v) {
p += 1;
swap[T](arr, p as uint, i as uint);
}
if compare_func_eq(v, { arr.(j) }) {
q -= 1;
swap[T](arr, j as uint, q as uint);
}
}
swap[T](arr, i as uint, right as uint);
j = i - 1;
i += 1;
let k: int = left;
while k < p {
swap[T](arr, k as uint, j as uint);
k += 1;
j -= 1;
if k == ilen[T](arr) as int { break; }
}
k = right - 1;
while k > q {
swap[T](arr, i as uint, k as uint);
k -= 1;
i += 1;
if k == 0 { break; }
}
qsort3[T](compare_func_lt, compare_func_eq, arr, left, j);
qsort3[T](compare_func_lt, compare_func_eq, arr, i, right);
}
fn quick_sort3[@T](compare_func_lt: lteq[T], compare_func_eq: lteq[T],
arr: &T[mutable ]) {
if ilen[T](arr) == 0u { ret; }
qsort3[T](compare_func_lt, compare_func_eq, arr, 0,
(ilen[T](arr) as int) - 1);
}
}
// 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:
|
use proconio::{input};
fn main() {
input! {
n: i64,
};
let m: i64= 998244353;
let mut x = n % m;
if x < 0 {
x += m;
}
assert!(0 <= x && x < m);
println!("{}", x);
} |
use super::data::*;
pub fn find_s(entries: Vec<Data>) -> Hypothesis{
let len = entries[0].len;
let mut hypothesis = Hypothesis::most_specific(len);
for entry in entries {
if entry.result {
for i in 0..entry.len {
if entry.values[i] {
let next = match hypothesis.values[i] {
Value::NONE | Value::TRUE => Value::TRUE,
_ => Value::ANY
};
hypothesis.values[i] = next;
} else {
let next = match hypothesis.values[i] {
Value::NONE | Value::FALSE => Value::FALSE,
_ => Value::ANY
};
hypothesis.values[i] = next;
}
}
}
}
return hypothesis;
} |
/// Construct a [`CloudEvent`] according to spec version 1.0.
///
/// # Errors
///
/// If some of the required fields are missing, or if some of the fields
/// have invalid content an error is returned.
///
/// # Example
///
/// ```
/// #[macro_use]
/// use cloudevents::cloudevent_v1_0;
/// use cloudevents::Data;
///
/// let event = cloudevent_v1_0!(
/// event_type: "test type",
/// source: "http://www.google.com",
/// event_id: "id",
/// datacontenttype: "application/json",
/// data: Data::from_string("\"test\""),
/// ).unwrap();
/// ```
///
/// ## Date now
///
/// ```
/// #[macro_use]
/// use cloudevents::{cloudevent_v1_0, Data};
///
/// let event = cloudevent_v1_0!(
/// event_type: "test type",
/// source: "http://www.google.com",
/// event_id: "id",
/// datacontenttype: "application/json",
/// time: "now",
/// data: Data::from_string("\"test\""),
/// ).unwrap();
/// ```
///
/// [`CloudEvent`]: struct.CloudEventV1_0.html
#[macro_export]
macro_rules! cloudevent_v1_0 {
($( $name:ident: $value:expr $(,)* )+) => {
$crate::v1_0::CloudEventV1_0Builder::default()
$(
.$name($value)
)*
.build()
};
}
|
use super::prelude::*;
#[command]
pub async fn info(ctx: &Context, msg: &Message) -> CommandResult {
let guilds = ctx.cache.guild_count().await;
let channels = ctx.cache.guild_channel_count().await;
let users = ctx.cache.user_count().await;
let bot = ctx.cache.current_user().await;
let avatar_url = bot.avatar_url();
let username = bot.name;
msg.channel_id.send_message(ctx, |m| {
m.embed(|e| {
e.title(format!("Info about {}", username));
if let Some(url) = avatar_url {
e.thumbnail(&url);
}
e
.field("Lib", "[serenity](https://github.com/serenity-rs/serenity)", true)
.field("Code Source", "[repo](https://github.com/acdenisSK/kitty-rs)", true)
.field("Owner", "<@110372470472613888>", true)
.field("Guilds", guilds, true)
.field("Channels", channels, true)
.field("Users", users, true)
})
}).await?;
Ok(())
}
|
use crate::errors::EvalErr;
use crate::object::Number::{Float, Integer};
use crate::object::Object::Boolean;
use crate::object::{Number, Object};
use crate::service::{expect_1_arg, expect_2_args};
use std::rc::Rc;
pub fn is_number(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let arg = expect_1_arg(args, "number?")?;
Ok(Rc::new(Boolean(matches!(arg.as_ref(), Object::Number(_)))))
}
pub fn is_integer(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let arg = expect_1_arg(args, "integer?")?;
Ok(Rc::new(Boolean(matches!(
arg.as_ref(),
Object::Number(Number::Integer(_))
))))
}
pub fn is_real(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
is_number(args)
}
fn get_float(num: &Number) -> f64 {
match num {
Integer(x) => *x as f64,
Float(x) => *x,
}
}
fn num_predicate(
vec: Vec<Rc<Object>>, name: &str, f: fn(&Number, &Number) -> bool,
) -> Result<Rc<Object>, EvalErr> {
if vec.len() < 2 {
Err(EvalErr::NeedAtLeastArgs(name.to_string(), 2, vec.len()))
} else {
if let Object::Number(first) = vec[0].as_ref() {
let mut last = first;
let mut result = true;
for x in &vec[1..] {
if let Object::Number(x) = x.as_ref() {
if !f(last, x) {
result = false;
break;
}
last = x;
} else {
return Err(EvalErr::NumericArgsRequiredFor(name.to_string()));
}
}
Ok(Rc::new(Boolean(result)))
} else {
Err(EvalErr::NumericArgsRequiredFor(name.to_string()))
}
}
}
pub fn num_equal(n1: &Number, n2: &Number) -> bool {
match (n1, n2) {
(Integer(a), Integer(b)) => a == b,
(a, b) => get_float(a) == get_float(b),
}
}
pub fn num_eqv(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
num_predicate(args, "=", num_equal)
}
pub fn num_less(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
num_predicate(args, "<", |x, y| get_float(x) < get_float(y))
}
pub fn num_greater(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
num_predicate(args, ">", |x, y| get_float(x) > get_float(y))
}
pub fn num_plus(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let mut acc = Integer(0);
for n in args {
if let Object::Number(n) = n.as_ref() {
acc = match (acc, n) {
(Integer(a), Integer(b)) => Integer(a + *b),
(a, b) => Float(get_float(&a) + get_float(b)),
}
} else {
return Err(EvalErr::NumericArgsRequiredFor("+".to_string()));
}
}
Ok(Rc::new(Object::Number(acc)))
}
pub fn num_mul(args: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let mut acc = Integer(1);
for n in args {
if let Object::Number(n) = n.as_ref() {
acc = match (acc, n) {
(Integer(a), Integer(b)) => Integer(a * *b),
(a, b) => Float(get_float(&a) * get_float(b)),
}
} else {
return Err(EvalErr::NumericArgsRequiredFor("*".to_string()));
}
}
Ok(Rc::new(Object::Number(acc)))
}
pub fn num_minus(vec: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let mut result = Integer(0);
for n in 0..vec.len() {
if let Object::Number(x) = vec.get(n).unwrap().as_ref() {
if n == 0 && vec.len() > 1 {
result = *x;
} else {
result = match (result, x) {
(Integer(a), Integer(b)) => Integer(a - *b),
(a, b) => Float(get_float(&a) - get_float(b)),
};
}
} else {
return Err(EvalErr::NumericArgsRequiredFor("-".to_string()));
}
}
Ok(Rc::new(Object::Number(result)))
}
pub fn num_div(vec: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let mut result = 1.0;
for n in 0..vec.len() {
if let Object::Number(x) = vec[n].as_ref() {
if n == 0 && vec.len() > 1 {
result = get_float(x);
} else {
let x = get_float(x);
if x == 0.0 {
return Err(EvalErr::DivisionByZero());
}
result /= x;
}
} else {
return Err(EvalErr::NumericArgsRequiredFor("/".to_string()));
}
}
Ok(Rc::new(Object::Number(Float(result))))
}
fn check_int_div(vec: Vec<Rc<Object>>, name: &str) -> Result<(i64, i64), EvalErr> {
let (n, d) = expect_2_args(vec, name)?;
if let (Object::Number(Integer(n)), Object::Number(Integer(d))) = (n.as_ref(), d.as_ref()) {
if *d == 0 {
return Err(EvalErr::DivisionByZero());
}
Ok((*n, *d))
} else {
Err(EvalErr::IntegerArgsRequiredFor(name.to_string()))
}
}
pub fn quotient(vec: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let (n, d) = check_int_div(vec, "quotient")?;
Ok(Rc::new(Object::Number(Integer(n / d))))
}
pub fn remainder(vec: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let (n, d) = check_int_div(vec, "remainder")?;
Ok(Rc::new(Object::Number(Integer(n - n / d * d))))
}
pub fn modulo(vec: Vec<Rc<Object>>) -> Result<Rc<Object>, EvalErr> {
let (n, d) = check_int_div(vec, "modulo")?;
let q = ((n as f64) / (d as f64)).floor() as i64;
let rem = n - d * q;
Ok(Rc::new(Object::Number(Integer(rem))))
}
|
use crate::core::random::RandomGenerator;
use crate::prefab::enemies::{ENEMY_STR_1, ENEMY_STR_2, ENEMY_STR_3};
use rand::seq::SliceRandom;
use serde_derive::{Deserialize, Serialize};
/// What kind of enemy should we spawn in infinite wave.
#[derive(Debug, Copy, Clone)]
pub struct WaveDifficulty {
level_1_enemies: f32,
level_2_enemies: f32,
level_3_enemies: f32,
}
impl Default for WaveDifficulty {
fn default() -> Self {
Self {
level_1_enemies: 1.0,
level_2_enemies: -1.0,
level_3_enemies: -5.0,
}
}
}
impl WaveDifficulty {
pub fn pick_prefabs(&self, random: &mut RandomGenerator) -> Vec<String> {
let lvl1 = self.level_1_enemies.max(0.0).floor() as usize;
let lvl2 = self.level_2_enemies.max(0.0).floor() as usize;
let lvl3 = self.level_3_enemies.max(0.0).floor() as usize;
let mut prefabs = Vec::with_capacity(lvl1 + lvl2 + lvl3);
for _ in 0..lvl1 {
prefabs.push(
ENEMY_STR_1
.choose(random.rng())
.map(|p| p.to_string())
.unwrap(),
);
}
for _ in 0..lvl2 {
prefabs.push(
ENEMY_STR_2
.choose(random.rng())
.map(|p| p.to_string())
.unwrap(),
);
}
for _ in 0..lvl3 {
prefabs.push(
ENEMY_STR_3
.choose(random.rng())
.map(|p| p.to_string())
.unwrap(),
);
}
prefabs
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum DifficultyCurve {
Linear(f32, f32),
Constant(f32),
}
impl DifficultyCurve {
pub fn y(&self, x: f32) -> f32 {
match self {
Self::Linear(origin, slope) => origin + slope * x,
Self::Constant(v) => *v,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DifficultyConfig {
level_1_curve: DifficultyCurve,
level_2_curve: DifficultyCurve,
level_3_curve: DifficultyCurve,
}
impl Default for DifficultyConfig {
fn default() -> Self {
Self {
level_1_curve: DifficultyCurve::Linear(0.0, 1.0),
level_2_curve: DifficultyCurve::Linear(-2.0, 0.5),
level_3_curve: DifficultyCurve::Linear(-5.0, 0.2),
}
}
}
impl DifficultyConfig {
pub fn difficulty(&self, wave_nb: usize) -> WaveDifficulty {
let next_level_1 = self.level_1_curve.y(wave_nb as f32);
let next_level_2 = self.level_2_curve.y(wave_nb as f32);
let next_level_3 = self.level_3_curve.y(wave_nb as f32);
WaveDifficulty {
level_1_enemies: next_level_1,
level_2_enemies: next_level_2,
level_3_enemies: next_level_3,
}
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub struct GameBar {}
impl GameBar {
#[cfg(feature = "Foundation")]
pub fn VisibilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<::windows::core::IInspectable>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
Self::IGameBarStatics(|this| unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn RemoveVisibilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> {
Self::IGameBarStatics(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() })
}
#[cfg(feature = "Foundation")]
pub fn IsInputRedirectedChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventHandler<::windows::core::IInspectable>>>(handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
Self::IGameBarStatics(|this| unsafe {
let mut result__: 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::Foundation::EventRegistrationToken>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn RemoveIsInputRedirectedChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(token: Param0) -> ::windows::core::Result<()> {
Self::IGameBarStatics(|this| unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() })
}
pub fn Visible() -> ::windows::core::Result<bool> {
Self::IGameBarStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IsInputRedirected() -> ::windows::core::Result<bool> {
Self::IGameBarStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IGameBarStatics<R, F: FnOnce(&IGameBarStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<GameBar, IGameBarStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for GameBar {
const NAME: &'static str = "Windows.Gaming.UI.GameBar";
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct GameChatMessageOrigin(pub i32);
impl GameChatMessageOrigin {
pub const Voice: GameChatMessageOrigin = GameChatMessageOrigin(0i32);
pub const Text: GameChatMessageOrigin = GameChatMessageOrigin(1i32);
}
impl ::core::convert::From<i32> for GameChatMessageOrigin {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for GameChatMessageOrigin {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for GameChatMessageOrigin {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Gaming.UI.GameChatMessageOrigin;i4)");
}
impl ::windows::core::DefaultType for GameChatMessageOrigin {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct GameChatMessageReceivedEventArgs(pub ::windows::core::IInspectable);
impl GameChatMessageReceivedEventArgs {
pub fn AppId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn AppDisplayName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SenderName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Message(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Origin(&self) -> ::windows::core::Result<GameChatMessageOrigin> {
let this = self;
unsafe {
let mut result__: GameChatMessageOrigin = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameChatMessageOrigin>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for GameChatMessageReceivedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.UI.GameChatMessageReceivedEventArgs;{a28201f1-3fb9-4e42-a403-7afce2023b1e})");
}
unsafe impl ::windows::core::Interface for GameChatMessageReceivedEventArgs {
type Vtable = IGameChatMessageReceivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa28201f1_3fb9_4e42_a403_7afce2023b1e);
}
impl ::windows::core::RuntimeName for GameChatMessageReceivedEventArgs {
const NAME: &'static str = "Windows.Gaming.UI.GameChatMessageReceivedEventArgs";
}
impl ::core::convert::From<GameChatMessageReceivedEventArgs> for ::windows::core::IUnknown {
fn from(value: GameChatMessageReceivedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&GameChatMessageReceivedEventArgs> for ::windows::core::IUnknown {
fn from(value: &GameChatMessageReceivedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameChatMessageReceivedEventArgs {
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 GameChatMessageReceivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<GameChatMessageReceivedEventArgs> for ::windows::core::IInspectable {
fn from(value: GameChatMessageReceivedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&GameChatMessageReceivedEventArgs> for ::windows::core::IInspectable {
fn from(value: &GameChatMessageReceivedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameChatMessageReceivedEventArgs {
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 GameChatMessageReceivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for GameChatMessageReceivedEventArgs {}
unsafe impl ::core::marker::Sync for GameChatMessageReceivedEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct GameChatOverlay(pub ::windows::core::IInspectable);
impl GameChatOverlay {
pub fn DesiredPosition(&self) -> ::windows::core::Result<GameChatOverlayPosition> {
let this = self;
unsafe {
let mut result__: GameChatOverlayPosition = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameChatOverlayPosition>(result__)
}
}
pub fn SetDesiredPosition(&self, value: GameChatOverlayPosition) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn AddMessage<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, sender: Param0, message: Param1, origin: GameChatMessageOrigin) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), sender.into_param().abi(), message.into_param().abi(), origin).ok() }
}
pub fn GetDefault() -> ::windows::core::Result<GameChatOverlay> {
Self::IGameChatOverlayStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<GameChatOverlay>(result__)
})
}
pub fn IGameChatOverlayStatics<R, F: FnOnce(&IGameChatOverlayStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<GameChatOverlay, IGameChatOverlayStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for GameChatOverlay {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.UI.GameChatOverlay;{fbc64865-f6fc-4a48-ae07-03ac6ed43704})");
}
unsafe impl ::windows::core::Interface for GameChatOverlay {
type Vtable = IGameChatOverlay_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfbc64865_f6fc_4a48_ae07_03ac6ed43704);
}
impl ::windows::core::RuntimeName for GameChatOverlay {
const NAME: &'static str = "Windows.Gaming.UI.GameChatOverlay";
}
impl ::core::convert::From<GameChatOverlay> for ::windows::core::IUnknown {
fn from(value: GameChatOverlay) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&GameChatOverlay> for ::windows::core::IUnknown {
fn from(value: &GameChatOverlay) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameChatOverlay {
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 GameChatOverlay {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<GameChatOverlay> for ::windows::core::IInspectable {
fn from(value: GameChatOverlay) -> Self {
value.0
}
}
impl ::core::convert::From<&GameChatOverlay> for ::windows::core::IInspectable {
fn from(value: &GameChatOverlay) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameChatOverlay {
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 GameChatOverlay {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for GameChatOverlay {}
unsafe impl ::core::marker::Sync for GameChatOverlay {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct GameChatOverlayMessageSource(pub ::windows::core::IInspectable);
impl GameChatOverlayMessageSource {
pub fn new() -> ::windows::core::Result<Self> {
Self::IActivationFactory(|f| f.activate_instance::<Self>())
}
fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<GameChatOverlayMessageSource, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Foundation")]
pub fn MessageReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<GameChatOverlayMessageSource, GameChatMessageReceivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveMessageReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn SetDelayBeforeClosingAfterMessageReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TimeSpan>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for GameChatOverlayMessageSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.UI.GameChatOverlayMessageSource;{1e177397-59fb-4f4f-8e9a-80acf817743c})");
}
unsafe impl ::windows::core::Interface for GameChatOverlayMessageSource {
type Vtable = IGameChatOverlayMessageSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e177397_59fb_4f4f_8e9a_80acf817743c);
}
impl ::windows::core::RuntimeName for GameChatOverlayMessageSource {
const NAME: &'static str = "Windows.Gaming.UI.GameChatOverlayMessageSource";
}
impl ::core::convert::From<GameChatOverlayMessageSource> for ::windows::core::IUnknown {
fn from(value: GameChatOverlayMessageSource) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&GameChatOverlayMessageSource> for ::windows::core::IUnknown {
fn from(value: &GameChatOverlayMessageSource) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameChatOverlayMessageSource {
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 GameChatOverlayMessageSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<GameChatOverlayMessageSource> for ::windows::core::IInspectable {
fn from(value: GameChatOverlayMessageSource) -> Self {
value.0
}
}
impl ::core::convert::From<&GameChatOverlayMessageSource> for ::windows::core::IInspectable {
fn from(value: &GameChatOverlayMessageSource) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameChatOverlayMessageSource {
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 GameChatOverlayMessageSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for GameChatOverlayMessageSource {}
unsafe impl ::core::marker::Sync for GameChatOverlayMessageSource {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct GameChatOverlayPosition(pub i32);
impl GameChatOverlayPosition {
pub const BottomCenter: GameChatOverlayPosition = GameChatOverlayPosition(0i32);
pub const BottomLeft: GameChatOverlayPosition = GameChatOverlayPosition(1i32);
pub const BottomRight: GameChatOverlayPosition = GameChatOverlayPosition(2i32);
pub const MiddleRight: GameChatOverlayPosition = GameChatOverlayPosition(3i32);
pub const MiddleLeft: GameChatOverlayPosition = GameChatOverlayPosition(4i32);
pub const TopCenter: GameChatOverlayPosition = GameChatOverlayPosition(5i32);
pub const TopLeft: GameChatOverlayPosition = GameChatOverlayPosition(6i32);
pub const TopRight: GameChatOverlayPosition = GameChatOverlayPosition(7i32);
}
impl ::core::convert::From<i32> for GameChatOverlayPosition {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for GameChatOverlayPosition {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for GameChatOverlayPosition {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Gaming.UI.GameChatOverlayPosition;i4)");
}
impl ::windows::core::DefaultType for GameChatOverlayPosition {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct GameUIProviderActivatedEventArgs(pub ::windows::core::IInspectable);
impl GameUIProviderActivatedEventArgs {
#[cfg(feature = "Foundation_Collections")]
pub fn GameUIArgs(&self) -> ::windows::core::Result<super::super::Foundation::Collections::ValueSet> {
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::Foundation::Collections::ValueSet>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn ReportCompleted<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::ValueSet>>(&self, results: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), results.into_param().abi()).ok() }
}
#[cfg(feature = "ApplicationModel_Activation")]
pub fn Kind(&self) -> ::windows::core::Result<super::super::ApplicationModel::Activation::ActivationKind> {
let this = &::windows::core::Interface::cast::<super::super::ApplicationModel::Activation::IActivatedEventArgs>(self)?;
unsafe {
let mut result__: super::super::ApplicationModel::Activation::ActivationKind = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::ApplicationModel::Activation::ActivationKind>(result__)
}
}
#[cfg(feature = "ApplicationModel_Activation")]
pub fn PreviousExecutionState(&self) -> ::windows::core::Result<super::super::ApplicationModel::Activation::ApplicationExecutionState> {
let this = &::windows::core::Interface::cast::<super::super::ApplicationModel::Activation::IActivatedEventArgs>(self)?;
unsafe {
let mut result__: super::super::ApplicationModel::Activation::ApplicationExecutionState = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::ApplicationModel::Activation::ApplicationExecutionState>(result__)
}
}
#[cfg(feature = "ApplicationModel_Activation")]
pub fn SplashScreen(&self) -> ::windows::core::Result<super::super::ApplicationModel::Activation::SplashScreen> {
let this = &::windows::core::Interface::cast::<super::super::ApplicationModel::Activation::IActivatedEventArgs>(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::ApplicationModel::Activation::SplashScreen>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for GameUIProviderActivatedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Gaming.UI.GameUIProviderActivatedEventArgs;{a7b3203e-caf7-4ded-bbd2-47de43bb6dd5})");
}
unsafe impl ::windows::core::Interface for GameUIProviderActivatedEventArgs {
type Vtable = IGameUIProviderActivatedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa7b3203e_caf7_4ded_bbd2_47de43bb6dd5);
}
impl ::windows::core::RuntimeName for GameUIProviderActivatedEventArgs {
const NAME: &'static str = "Windows.Gaming.UI.GameUIProviderActivatedEventArgs";
}
impl ::core::convert::From<GameUIProviderActivatedEventArgs> for ::windows::core::IUnknown {
fn from(value: GameUIProviderActivatedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&GameUIProviderActivatedEventArgs> for ::windows::core::IUnknown {
fn from(value: &GameUIProviderActivatedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for GameUIProviderActivatedEventArgs {
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 GameUIProviderActivatedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<GameUIProviderActivatedEventArgs> for ::windows::core::IInspectable {
fn from(value: GameUIProviderActivatedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&GameUIProviderActivatedEventArgs> for ::windows::core::IInspectable {
fn from(value: &GameUIProviderActivatedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for GameUIProviderActivatedEventArgs {
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 GameUIProviderActivatedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "ApplicationModel_Activation")]
impl ::core::convert::TryFrom<GameUIProviderActivatedEventArgs> for super::super::ApplicationModel::Activation::IActivatedEventArgs {
type Error = ::windows::core::Error;
fn try_from(value: GameUIProviderActivatedEventArgs) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "ApplicationModel_Activation")]
impl ::core::convert::TryFrom<&GameUIProviderActivatedEventArgs> for super::super::ApplicationModel::Activation::IActivatedEventArgs {
type Error = ::windows::core::Error;
fn try_from(value: &GameUIProviderActivatedEventArgs) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "ApplicationModel_Activation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::ApplicationModel::Activation::IActivatedEventArgs> for GameUIProviderActivatedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, super::super::ApplicationModel::Activation::IActivatedEventArgs> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "ApplicationModel_Activation")]
impl<'a> ::windows::core::IntoParam<'a, super::super::ApplicationModel::Activation::IActivatedEventArgs> for &GameUIProviderActivatedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, super::super::ApplicationModel::Activation::IActivatedEventArgs> {
::core::convert::TryInto::<super::super::ApplicationModel::Activation::IActivatedEventArgs>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for GameUIProviderActivatedEventArgs {}
unsafe impl ::core::marker::Sync for GameUIProviderActivatedEventArgs {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IGameBarStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGameBarStatics {
type Vtable = IGameBarStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1db9a292_cc78_4173_be45_b61e67283ea7);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGameBarStatics_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, handler: ::windows::core::RawPtr, result__: *mut 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::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut 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::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IGameChatMessageReceivedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGameChatMessageReceivedEventArgs {
type Vtable = IGameChatMessageReceivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa28201f1_3fb9_4e42_a403_7afce2023b1e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGameChatMessageReceivedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut GameChatMessageOrigin) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IGameChatOverlay(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGameChatOverlay {
type Vtable = IGameChatOverlay_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfbc64865_f6fc_4a48_ae07_03ac6ed43704);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGameChatOverlay_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 GameChatOverlayPosition) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: GameChatOverlayPosition) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, sender: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, message: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, origin: GameChatMessageOrigin) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IGameChatOverlayMessageSource(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGameChatOverlayMessageSource {
type Vtable = IGameChatOverlayMessageSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1e177397_59fb_4f4f_8e9a_80acf817743c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGameChatOverlayMessageSource_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, handler: ::windows::core::RawPtr, result__: *mut 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::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IGameChatOverlayStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGameChatOverlayStatics {
type Vtable = IGameChatOverlayStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x89acf614_7867_49f7_9687_25d9dbf444d1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGameChatOverlayStatics_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 IGameUIProviderActivatedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IGameUIProviderActivatedEventArgs {
type Vtable = IGameUIProviderActivatedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa7b3203e_caf7_4ded_bbd2_47de43bb6dd5);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGameUIProviderActivatedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, results: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
|
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct ExamDto {
pub id: i32,
pub name: String,
pub description: String,
pub questions: Vec<QuestionDto>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct QuestionDto {
pub id: i32,
pub content: String,
pub answers: Vec<AnswerDto>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct AnswerDto {
pub id: i32,
pub content: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StudentExamDto {
pub id: i32,
pub id_student: i32,
pub exam: ExamDto,
}
|
use crate::types::{Enemy, Game, Vec2, WIDTH, WeaponKind};
use crate::util;
use crate::objects::Graphics;
impl Enemy {
pub fn tick(mut self, game: &mut Game) -> Enemy {
let screen_x = game.enemies_x + self.position.x;
if screen_x > WIDTH as i32 {
return self;
}
if game.time % 4 == 0 {
self.anim_state = (self.anim_state + 1) % self.data.anim_count;
}
self.collision(game);
if screen_x > WIDTH as i32 / 4 * 3 - 10 {
return self;
}
self.oscillation();
if self.data.floats {
self.position.x += 1;
}
self
}
pub fn collision(&mut self, game: &mut Game) {
let screen_x = game.enemies_x + self.position.x;
let obj = game.load_object(self.data.model_id as u8);
if screen_x > -100 && screen_x < 940 {
let collission = util::intersect(
game.player.position.clone(),
Vec2 { x: 10, y: 7 },
Vec2 { x: screen_x, y: self.position.y },
obj.size.clone()
);
if collission {
self.object_collision(game);
}
game.shots = game.shots.clone().into_iter().map(|mut shot| {
let bullet = shot.weapon_kind.clone().model(game);
let collission = util::intersect(
shot.position.clone(),
bullet.size.clone(),
Vec2 { x: screen_x, y: self.position.y },
obj.size.clone()
);
if collission {
if self.is_bonus() {
} else {
shot.crash();
self.damage();
}
}
shot
}).collect();
if game.time % 2 == 0 {
self.die();
}
}
}
pub fn object_collision(&mut self, game: &mut Game) {
if self.is_bonus() {
self.delete();
let id: u8 = crate::random() % 4;
let wk: WeaponKind = id.into();
if game.weapon.kind == wk {
game.weapon.amount += wk.default_amount();
} else {
game.weapon.kind = id.into();
game.weapon.amount = wk.default_amount();
}
} else {
if !game.player.protected() {
game.player.lives -= 1;
game.player.protection = 50;
}
self.damage();
}
}
pub fn oscillation(&mut self) {
if self.dir == 1 {
if self.position.y < self.data.moves_between.y {
self.position.y += 1;
} else {
self.dir = if self.data.move_up { -1 } else { 0 };
}
}
if self.dir == -1 {
if self.position.y > self.data.moves_between.x {
self.position.y -= 1;
} else {
self.dir = if self.data.move_down { 1 } else { 0 };
}
}
}
pub fn render(self, game: &mut Game) {
let obj = game.load_object(self.data.model_id + self.anim_state);
let screen_x = game.enemies_x + self.position.x;
if self.alive() {
game.render_object(&obj, screen_x, self.position.y);
} else if self.explosion_frames > 0 {
let explosion = game.static_objects[Graphics::GExplosionA1 as usize - self.explosion_frames as usize + 2].clone();
game.render_object(&explosion, screen_x, self.position.y);
}
}
}
|
use id::Id;
/// Describes a player actively engaged in a duel.
#[derive(Debug, Clone)]
pub struct Player {
pub id: Id,
// TODO: Reference to some descriptor containing name?
// TODO: Life total
// TODO: Counters, like energy and poison
}
|
pub struct Gun {
is_loaded: bool,
latch_state: LatchState,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LatchState {
Closed,
Open,
}
pub enum ConsumeError {
LatchWasOpen,
NotLoaded,
}
impl Gun {
pub fn new() -> Self {
Self {
is_loaded: false,
latch_state: LatchState::Closed,
}
}
pub fn can_shoot(&self) -> bool {
self.is_loaded && self.latch_state == LatchState::Closed
}
pub fn set_latch_state(&mut self, state: LatchState) {
if self.latch_state == LatchState::Open && state == LatchState::Closed {
self.is_loaded = true;
}
self.latch_state = state;
println!("latch state: {:?}", self.latch_state);
}
pub fn try_consume(&mut self) -> Result<(), ConsumeError> {
match self.latch_state {
LatchState::Open => Err(ConsumeError::LatchWasOpen),
LatchState::Closed => match self.is_loaded {
true => {
self.is_loaded = false;
Ok(())
}
false => Err(ConsumeError::NotLoaded),
},
}
}
}
|
// 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(non_snake_case)]
use std::backtrace::Backtrace;
use std::backtrace::BacktraceStatus;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::sync::Arc;
use thiserror::Error;
use crate::span::pretty_print_error;
use crate::Span;
#[derive(Clone)]
pub enum ErrorCodeBacktrace {
Serialized(Arc<String>),
Origin(Arc<Backtrace>),
}
impl ToString for ErrorCodeBacktrace {
fn to_string(&self) -> String {
match self {
ErrorCodeBacktrace::Serialized(backtrace) => Arc::as_ref(backtrace).clone(),
ErrorCodeBacktrace::Origin(backtrace) => {
format!("{:?}", backtrace)
}
}
}
}
impl From<&str> for ErrorCodeBacktrace {
fn from(s: &str) -> Self {
Self::Serialized(Arc::new(s.to_string()))
}
}
impl From<String> for ErrorCodeBacktrace {
fn from(s: String) -> Self {
Self::Serialized(Arc::new(s))
}
}
impl From<Arc<String>> for ErrorCodeBacktrace {
fn from(s: Arc<String>) -> Self {
Self::Serialized(s)
}
}
impl From<Backtrace> for ErrorCodeBacktrace {
fn from(bt: Backtrace) -> Self {
Self::Origin(Arc::new(bt))
}
}
impl From<&Backtrace> for ErrorCodeBacktrace {
fn from(bt: &Backtrace) -> Self {
Self::Serialized(Arc::new(bt.to_string()))
}
}
impl From<Arc<Backtrace>> for ErrorCodeBacktrace {
fn from(bt: Arc<Backtrace>) -> Self {
Self::Origin(bt)
}
}
#[derive(Error)]
pub struct ErrorCode {
code: u16,
display_text: String,
span: Span,
// cause is only used to contain an `anyhow::Error`.
// TODO: remove `cause` when we completely get rid of `anyhow::Error`.
cause: Option<Box<dyn std::error::Error + Sync + Send>>,
backtrace: Option<ErrorCodeBacktrace>,
}
impl ErrorCode {
pub fn code(&self) -> u16 {
self.code
}
pub fn message(&self) -> String {
self.cause
.as_ref()
.map(|cause| format!("{}\n{:?}", self.display_text, cause))
.unwrap_or_else(|| self.display_text.clone())
}
#[must_use]
pub fn add_message(self, msg: impl AsRef<str>) -> Self {
Self {
display_text: format!("{}\n{}", msg.as_ref(), self.display_text),
..self
}
}
#[must_use]
pub fn add_message_back(self, msg: impl AsRef<str>) -> Self {
Self {
display_text: format!("{}{}", self.display_text, msg.as_ref()),
..self
}
}
pub fn span(&self) -> Span {
self.span
}
/// Set sql span for this error.
///
/// Used to pretty print the error when the error is related to a sql statement.
pub fn set_span(self, span: Span) -> Self {
Self { span, ..self }
}
/// Pretty display the error message onto sql statement if span is available.
pub fn display_with_sql(mut self, sql: &str) -> Self {
if let Some(span) = self.span.take() {
self.display_text =
pretty_print_error(sql, vec![(span, self.display_text.to_string())]);
}
self
}
/// Set backtrace info for this error.
///
/// Useful when trying to keep original backtrace
pub fn set_backtrace(mut self, bt: Option<impl Into<ErrorCodeBacktrace>>) -> Self {
if let Some(b) = bt {
self.backtrace = Some(b.into());
}
self
}
pub fn backtrace(&self) -> Option<ErrorCodeBacktrace> {
self.backtrace.clone()
}
pub fn backtrace_str(&self) -> String {
self.backtrace
.as_ref()
.map_or("".to_string(), |x| x.to_string())
}
}
pub type Result<T, E = ErrorCode> = std::result::Result<T, E>;
impl Debug for ErrorCode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Code: {}, displayText = {}.",
self.code(),
self.message(),
)?;
match self.backtrace.as_ref() {
None => Ok(()), // no backtrace
Some(backtrace) => {
// TODO: Custom stack frame format for print
match backtrace {
ErrorCodeBacktrace::Origin(backtrace) => {
if backtrace.status() == BacktraceStatus::Disabled {
write!(
f,
"\n\n<Backtrace disabled by default. Please use RUST_BACKTRACE=1 to enable> "
)
} else {
write!(f, "\n\n{}", backtrace)
}
}
ErrorCodeBacktrace::Serialized(backtrace) => write!(f, "\n\n{}", backtrace),
}
}
}
}
}
impl Display for ErrorCode {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Code: {}, displayText = {}.",
self.code(),
self.message(),
)
}
}
impl ErrorCode {
/// All std error will be converted to InternalError
pub fn from_std_error<T: std::error::Error>(error: T) -> Self {
ErrorCode {
code: 1001,
display_text: error.to_string(),
span: None,
cause: None,
backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::capture()))),
}
}
pub fn from_string(error: String) -> Self {
ErrorCode {
code: 1001,
display_text: error,
span: None,
cause: None,
backtrace: Some(ErrorCodeBacktrace::Origin(Arc::new(Backtrace::capture()))),
}
}
pub fn from_string_no_backtrace(error: String) -> Self {
ErrorCode {
code: 1001,
display_text: error,
span: None,
cause: None,
backtrace: None,
}
}
pub fn create(
code: u16,
display_text: String,
cause: Option<Box<dyn std::error::Error + Sync + Send>>,
backtrace: Option<ErrorCodeBacktrace>,
) -> ErrorCode {
ErrorCode {
code,
display_text,
span: None,
cause,
backtrace,
}
}
}
/// Provides the `map_err_to_code` method for `Result`.
///
/// ```
/// use common_exception::ErrorCode;
/// use common_exception::ToErrorCode;
///
/// let x: std::result::Result<(), std::fmt::Error> = Err(std::fmt::Error {});
/// let y: common_exception::Result<()> = x.map_err_to_code(ErrorCode::UnknownException, || 123);
///
/// assert_eq!(
/// "Code: 1067, displayText = 123, cause: an error occurred when formatting an argument.",
/// y.unwrap_err().to_string()
/// );
/// ```
pub trait ToErrorCode<T, E, CtxFn>
where E: Display + Send + Sync + 'static
{
/// Wrap the error value with ErrorCode. It is lazily evaluated:
/// only when an error does occur.
///
/// `err_code_fn` is one of the ErrorCode builder function such as `ErrorCode::Ok`.
/// `context_fn` builds display_text for the ErrorCode.
fn map_err_to_code<ErrFn, D>(self, err_code_fn: ErrFn, context_fn: CtxFn) -> Result<T>
where
ErrFn: FnOnce(String) -> ErrorCode,
D: Display,
CtxFn: FnOnce() -> D;
}
impl<T, E, CtxFn> ToErrorCode<T, E, CtxFn> for std::result::Result<T, E>
where E: Display + Send + Sync + 'static
{
fn map_err_to_code<ErrFn, D>(self, make_exception: ErrFn, context_fn: CtxFn) -> Result<T>
where
ErrFn: FnOnce(String) -> ErrorCode,
D: Display,
CtxFn: FnOnce() -> D,
{
self.map_err(|error| {
let err_text = format!("{}, cause: {}", context_fn(), error);
make_exception(err_text)
})
}
}
impl Clone for ErrorCode {
fn clone(&self) -> Self {
ErrorCode::create(self.code(), self.message(), None, self.backtrace()).set_span(self.span())
}
}
|
use types::Validator;
/// Trait to implement if one wants to make the `length` validator
/// work for more types
///
/// A bit sad it's not there by default in Rust
pub trait HasLen {
fn length(&self) -> u64;
}
impl HasLen for String {
fn length(&self) -> u64 {
self.chars().count() as u64
}
}
impl<'a> HasLen for &'a String {
fn length(&self) -> u64 {
self.chars().count() as u64
}
}
impl<'a> HasLen for &'a str {
fn length(&self) -> u64 {
self.chars().count() as u64
}
}
impl<T> HasLen for Vec<T> {
fn length(&self) -> u64 {
self.len() as u64
}
}
impl<'a, T> HasLen for &'a Vec<T> {
fn length(&self) -> u64 {
self.len() as u64
}
}
/// Validates the length of the value given.
/// If the validator has `equal` set, it will ignore any `min` and `max` value.
///
/// If you apply it on String, don't forget that the length can be different
/// from the number of visual characters for Unicode
pub fn validate_length<T: HasLen>(length: Validator, val: T) -> bool {
match length {
Validator::Length { min, max, equal } => {
let val_length = val.length();
if let Some(eq) = equal {
return val_length == eq;
}
if let Some(m) = min {
if val_length < m {
return false;
}
}
if let Some(m) = max {
if val_length > m {
return false;
}
}
},
_ => unreachable!()
}
true
}
#[cfg(test)]
mod tests {
use super::{validate_length, Validator};
#[test]
fn test_validate_length_equal_overrides_min_max() {
let validator = Validator::Length { min: Some(1), max: Some(2), equal: Some(5) };
assert_eq!(validate_length(validator, "hello"), true);
}
#[test]
fn test_validate_length_string_min_max() {
let validator = Validator::Length { min: Some(1), max: Some(10), equal: None };
assert_eq!(validate_length(validator, "hello"), true);
}
#[test]
fn test_validate_length_string_min_only() {
let validator = Validator::Length { min: Some(10), max: None, equal: None };
assert_eq!(validate_length(validator, "hello"), false);
}
#[test]
fn test_validate_length_string_max_only() {
let validator = Validator::Length { min: None, max: Some(1), equal: None };
assert_eq!(validate_length(validator, "hello"), false);
}
#[test]
fn test_validate_length_vec() {
let validator = Validator::Length { min: None, max: None, equal: Some(3) };
assert_eq!(validate_length(validator, vec![1, 2, 3]), true);
}
#[test]
fn test_validate_length_unicode_chars() {
let validator = Validator::Length { min: None, max: None, equal: Some(2) };
assert_eq!(validate_length(validator, "日本"), true);
}
}
|
// 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 common_base::base::tokio;
use common_exception::Result;
use common_expression::types::NumberDataType;
use common_expression::TableDataType;
use common_expression::TableField;
use common_expression::TableSchemaRefExt;
use common_meta_app::schema::TableInfo;
use common_meta_app::schema::TableMeta;
use common_sql::executor::table_read_plan::ToReadDataSourcePlan;
use common_sql::plans::TableOptions;
use common_storages_null::NullTable;
use databend_query::stream::ReadDataBlockStream;
use futures::TryStreamExt;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_null_table() -> Result<()> {
let (_guard, ctx) = crate::tests::create_query_context().await?;
let table = NullTable::try_create(TableInfo {
desc: "'default'.'a'".into(),
name: "a".into(),
ident: Default::default(),
meta: TableMeta {
schema: TableSchemaRefExt::create(vec![TableField::new(
"a",
TableDataType::Number(NumberDataType::UInt64),
)]),
engine: "Null".to_string(),
options: TableOptions::default(),
..Default::default()
},
..Default::default()
})?;
// read.
{
let source_plan = table.read_plan(ctx.clone(), None).await?;
assert_eq!(table.engine(), "Null");
let stream = table
.read_data_block_stream(ctx.clone(), &source_plan)
.await?;
let result = stream.try_collect::<Vec<_>>().await?;
let block = &result[0];
assert_eq!(block.num_columns(), 1);
}
// truncate.
{
let purge = false;
table.truncate(ctx, purge).await?;
}
Ok(())
}
|
use yew::prelude::*;
#[derive(Debug)]
pub struct Model;
impl Component for Model {
type Message = ();
type Properties = ();
fn create(_props: Self::Properties, _link: ComponentLink<Self>) -> Self {
Self
}
fn update(&mut self, _msg: Self::Message) -> ShouldRender {
unimplemented!()
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
false
}
fn view(&self) -> Html {
html! {
<main>
<img class="logo" src="https://yew.rs/img/logo.png" alt="Yew logo" />
<h1>{ "Hello World!" }</h1>
<span class="subtitle">{ "from Yew with " }<i class="heart" /></span>
</main>
}
}
}
fn main() {
yew::start_app::<Model>();
}
|
#[macro_use]
extern crate failure;
#[allow(unused_imports)]
#[macro_use]
extern crate serde_derive;
#[cfg(test)]
mod tests;
use kv_crud_core::{Create, Entity, Read, Update, ReadWithPaginationAndSort, Page, Sort, Delete};
use serde::de::DeserializeOwned;
use serde::Serialize;
#[derive(Debug, Fail)]
pub enum Error {
#[fail(display = "Value not found for key {}", _0)]
NotFound(String),
#[fail(display = "Formatting error: {}", _0)]
FormattingError(serde_json::Error),
#[fail(display = "SQLite error: {}", _0)]
SqliteError(sqlite::Error),
#[fail(display = "Unknown error")]
UnknownError,
}
fn wrap_sqlite_error(sqlite_error: sqlite::Error) -> Error {
Error::SqliteError(sqlite_error)
}
fn wrap_serde_error(serde_error: serde_json::Error) -> Error {
Error::FormattingError(serde_error)
}
type Result<T> = std::result::Result<T, Error>;
pub struct SqliteStorage {
connection: sqlite::Connection,
}
impl SqliteStorage {
pub fn new<T: ToString>(path: T) -> Result<Self> {
let connection = sqlite::open(path.to_string()).map_err(wrap_sqlite_error)?;
connection
.execute("CREATE TABLE IF NOT EXISTS data (key TEXT PRIMARY KEY, value TEXT);")
.map_err(wrap_sqlite_error)?;
Ok(Self { connection })
}
}
impl<I, E> Create<I, E> for SqliteStorage
where
I: ToString,
E: Entity<I> + Serialize,
{
type Error = Error;
fn save(&mut self, entity: &E) -> Result<()> {
let mut statement = self
.connection
.prepare(
"INSERT INTO data (key, value) VALUES (?, ?)
ON CONFLICT (key) DO UPDATE SET value = excluded.value;",
)
.map_err(wrap_sqlite_error)?;
let key: &str = &entity.get_id().to_string();
let value: &str = &serde_json::to_string(entity).map_err(wrap_serde_error)?;
statement.bind(1, key).map_err(wrap_sqlite_error)?;
statement.bind(2, value).map_err(wrap_sqlite_error)?;
statement.next().map_err(wrap_sqlite_error)?;
Ok(())
}
}
impl<I, E> Read<I, E> for SqliteStorage
where
I: ToString,
E: Entity<I> + DeserializeOwned,
{
type Error = Error;
fn find_by_id(&self, id: &I) -> Result<E> {
let mut statement = self
.connection
.prepare("SELECT value FROM data WHERE key = ?")
.map_err(wrap_sqlite_error)?;
let key: &str = &id.to_string();
statement.bind(1, key).map_err(wrap_sqlite_error)?;
match statement.next().map_err(wrap_sqlite_error)? {
sqlite::State::Row => {
let serialized: String = statement.read(0).map_err(wrap_sqlite_error)?;
Ok(serde_json::from_str(&serialized).map_err(wrap_serde_error)?)
}
sqlite::State::Done => Err(Error::NotFound(key.to_owned())),
}
}
}
impl<I, E> ReadWithPaginationAndSort<I, E> for SqliteStorage
where
I: ToString,
E: Entity<I> + DeserializeOwned,
{
type Error = Error;
fn find_all_with_page(&self, page: &Page) -> Result<Vec<E>> {
let mut statement = self.connection.prepare("SELECT value FROM data LIMIT ?, ?")
.map_err(wrap_sqlite_error)?;
statement.bind(1, page.offset() as i64).map_err(wrap_sqlite_error)?;
statement.bind(2, page.size as i64).map_err(wrap_sqlite_error)?;
let mut cursor = statement.cursor();
let mut result = Vec::<E>::new();
while let Some(row) = cursor.next().map_err(wrap_sqlite_error)? {
let serialized = row[0].as_string().unwrap();
let entity = serde_json::from_str(&serialized).map_err(wrap_serde_error)?;
result.push(entity);
}
Ok(result)
}
fn find_all_with_page_and_sort(&self, _page: &Page, _sort: &Sort) -> Result<Vec<E>> {
unimplemented!()
}
}
impl<I, E> Update<I, E> for SqliteStorage
where
I: ToString,
E: Entity<I> + Serialize,
{
type Error = Error;
fn update(&mut self, entity: &E) -> Result<()> {
self.save(entity)
}
}
impl<I, E> Delete<I, E> for SqliteStorage
where
I: ToString,
E: Entity<I>,
{
type Error = Error;
fn remove_by_id(&mut self, id: &I) -> Result<()> {
let mut statement = self.connection.prepare("DELETE FROM data WHERE key = ?").map_err(wrap_sqlite_error)?;
let id_str: &str = &id.to_string();
statement.bind(1, id_str).map_err(wrap_sqlite_error)?;
match statement.next().map_err(wrap_sqlite_error)? {
sqlite::State::Done => Ok(()),
_ => Err(Error::NotFound(id.to_string()))
}
}
fn remove(&mut self, entity: &E) -> Result<()> {
let id: I = entity.get_id();
<SqliteStorage as Delete<I, E>>::remove_by_id(self, &id);
Ok(())
}
}
|
use std::{
sync::{Arc, Barrier},
time::Instant,
};
use criterion::{
criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion, Throughput,
};
use data_types::NamespaceName;
use mutable_batch::MutableBatch;
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use sharder::{JumpHash, RoundRobin, Sharder};
fn get_random_string(length: usize) -> String {
thread_rng()
.sample_iter(&Alphanumeric)
.take(length)
.map(char::from)
.collect()
}
fn sharder_benchmarks(c: &mut Criterion) {
benchmark_impl(c, "jumphash", |num_buckets| {
JumpHash::new((0..num_buckets).map(Arc::new))
});
benchmark_impl(c, "round_robin", |num_buckets| {
RoundRobin::new((0..num_buckets).map(Arc::new))
});
}
fn benchmark_impl<T, F>(c: &mut Criterion, name: &str, init: F)
where
T: Sharder<MutableBatch>,
F: Fn(usize) -> T,
{
let mut group = c.benchmark_group(name);
// benchmark sharder with fixed table name and namespace, with varying number of buckets
benchmark_scenario(
&mut group,
"basic 1k buckets",
"table",
&NamespaceName::try_from("namespace").unwrap(),
init(1_000),
);
benchmark_scenario(
&mut group,
"basic 10k buckets",
"table",
&NamespaceName::try_from("namespace").unwrap(),
init(10_000),
);
benchmark_scenario(
&mut group,
"basic 100k buckets",
"table",
&NamespaceName::try_from("namespace").unwrap(),
init(100_000),
);
benchmark_scenario(
&mut group,
"basic 1M buckets",
"table",
&NamespaceName::try_from("namespace").unwrap(),
init(1_000_000),
);
// benchmark sharder with random table name and namespace of length 16
benchmark_scenario(
&mut group,
"random with key-length 16",
get_random_string(16).as_str(),
&NamespaceName::try_from(get_random_string(16)).unwrap(),
init(10_000),
);
// benchmark sharder with random table name and namespace of length 32
benchmark_scenario(
&mut group,
"random with key-length 32",
get_random_string(32).as_str(),
&NamespaceName::try_from(get_random_string(32)).unwrap(),
init(10_000),
);
// benchmark sharder with random table name and namespace of length 64
benchmark_scenario(
&mut group,
"random with key-length 64",
get_random_string(64).as_str(),
&NamespaceName::try_from(get_random_string(64)).unwrap(),
init(10_000),
);
group.finish();
}
fn benchmark_scenario<T>(
group: &mut BenchmarkGroup<WallTime>,
bench_name: &str,
table: &str,
namespace: &NamespaceName<'_>,
sharder: T,
) where
T: Sharder<MutableBatch>,
{
let batch = MutableBatch::default();
group.throughput(Throughput::Elements(1));
group.bench_function(bench_name, |b| {
b.iter(|| {
sharder.shard(table, namespace, &batch);
});
});
const N_THREADS: usize = 10;
// Run the same test with N contending threads.
//
// Note that this includes going through pointer indirection for each shard
// op due to the Arc.
let sharder = Arc::new(sharder);
group.bench_function(format!("{bench_name}_{N_THREADS}_threads"), |b| {
b.iter_custom(|iters| {
let sharder = Arc::clone(&sharder);
std::thread::scope(|s| {
let barrier = Arc::new(Barrier::new(N_THREADS));
// Spawn N-1 threads that wait for the last thread to spawn
for _ in 0..(N_THREADS - 1) {
let sharder = Arc::clone(&sharder);
let barrier = Arc::clone(&barrier);
s.spawn(move || {
let batch = MutableBatch::default();
barrier.wait();
for _ in 0..iters {
sharder.shard(table, namespace, &batch);
}
});
}
// Spawn the Nth thread that performs the same sharding ops, but
// measures the duration of time taken.
s.spawn(move || {
let batch = MutableBatch::default();
barrier.wait();
let start = Instant::now();
for _ in 0..iters {
sharder.shard(table, namespace, &batch);
}
start.elapsed()
})
.join()
.unwrap()
})
});
});
}
criterion_group!(benches, sharder_benchmarks);
criterion_main!(benches);
|
extern crate juniper;
use juniper::FieldResult;
use super::{
DiskInformation, LoadAverage, System, MemoryInformation, ByteUnit, CycleUnit, BootTime
};
graphql_enum!(ByteUnit {
ByteUnit::KB => "KB",
ByteUnit::MB => "MB",
ByteUnit::GB => "GB",
ByteUnit::TB => "TB",
});
graphql_enum!(CycleUnit {
CycleUnit::MHz => "MHz",
CycleUnit::GHz => "GHz"
});
graphql_object!(DiskInformation: System as "DiskInformation" |&self| {
description: "Get disk information"
field total() -> FieldResult<&String> as "Total disk space" {
Ok(&self.total)
}
field free() -> FieldResult<&String> as "Available free disk space" {
Ok(&self.free)
}
});
graphql_object!(LoadAverage: System as "LoadAverage" |&self| {
description: "CPU load averages"
field one() -> FieldResult<&String> as "One minute average" {
Ok(&self.one)
}
field five() -> FieldResult<&String> as "Five minute average" {
Ok(&self.five)
}
field fifteen() -> FieldResult<&String> as "Fifteen minute average" {
Ok(&self.fifteen)
}
});
graphql_object!(MemoryInformation: System as "MemoryInformation" |&self| {
description: "Get memory information"
field total() -> FieldResult<&String> as "Total memory" {
Ok(&self.total)
}
field free() -> FieldResult<&String> as "Free memory" {
Ok(&self.free)
}
field available() -> FieldResult<&String> as "Available memory" {
Ok(&self.available)
}
field buffers() -> FieldResult<&String> as "Buffers" {
Ok(&self.buffers)
}
field cached() -> FieldResult<&String> as "Cached memory" {
Ok(&self.cached)
}
field swap_total() -> FieldResult<&String> as "Swap total" {
Ok(&self.swap_total)
}
field swap_free() -> FieldResult<&String> as "Swap free" {
Ok(&self.swap_free)
}
});
graphql_object!(System: System as "Query" |&self| {
description: "The root query object of the schema"
field disk_info(
&executor,
unit: Option<ByteUnit> as "Byte size. Defaults to KB."
) -> Option<DiskInformation> {
Some(self.get_disk_info(unit))
}
field load_average(&executor) -> Option<LoadAverage> {
Some(self.get_load_average())
}
field memory_info(
&executor,
unit: Option<ByteUnit> as "Byte size. Defaults to KB."
) -> Option<MemoryInformation> {
Some(self.get_memory_information(unit))
}
field os_type(&executor) -> &String as "Operating system type" {
&self.os_type
}
field os_release(&executor) -> &String as "Operating system release version" {
&self.os_release
}
field hostname(&executor) -> &String as "Hostname" {
&self.hostname
}
field cpu_count(&executor) -> String as "CPU quantity." {
self.cpu_num.to_string()
}
field cpu_speed(
&executor,
unit: Option<CycleUnit> as "Hertz unit size. Defaults to MHz."
) -> String as "CPU speed. Such as 2500 MHz." {
self.get_cpu_speed(unit)
}
field proc_count(&executor) -> String as "Current quantity of processes." {
self.get_proc_total()
}
field boot_time(&executor) -> BootTime as "System boot time." {
self.get_boot_time()
}
});
graphql_object!(BootTime: System as "BootTime" |&self| {
description: "The boot time of the system"
field up_seconds() -> FieldResult<&String> as "The total number of seconds the system has been up" {
Ok(&self.up_seconds)
}
field idle_seconds() -> FieldResult<&String> as "The time the machine has spent idle, in seconds" {
Ok(&self.idle_seconds)
}
});
|
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn main() -> io::Result<()> {
let f = File::open("bil_prima.rs")?;
let mut reader = BufReader::new(f);
let mut buffer = String::new();
reader.read_line(&mut buffer)?;
println!("{}", buffer);
Ok(())
}
|
//! Parameters used in distributions, simulation modules, etc. are defined
//! here.
//!
//! These ensure the conversion between different parameter types follow
//! the right formulas.
//!
//!
//!
use anyhow::Result;
use std::{
convert::{TryFrom, TryInto},
ops::Neg,
};
use thiserror::Error;
#[readonly::make]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(
Debug, Clone, Copy, derive_more::Into, derive_more::Display, derive_more::Add, derive_more::Sum,
)]
pub struct Rate(pub f64);
impl Rate {
pub fn new(value: f64) -> Result<Self> {
Ok(value.try_into()?)
}
}
// #[readonly::make]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(
Debug,
Clone,
Copy,
derive_more::Display,
derive_more::Into,
// derive_more::MulSelf,
// derive_more::Mul, // doesn't work with product
// derive_more::Product,
)]
pub struct Probability(pub f64);
impl Probability {
pub fn new(value: f64) -> Result<Self> {
Ok(value.try_into()?)
}
pub fn complement(mut self) -> Self {
self.0 = 1. - self.0;
self
}
}
#[derive(Error, Debug)]
pub enum ConversionError {
#[error("negative float is not a valid rate")]
NegativeRate,
#[error("float is not between 0 and 1, thus not a valid probability")]
NotInbetweenZeroAndOne,
}
impl TryFrom<f64> for Rate {
type Error = ConversionError;
fn try_from(value: f64) -> Result<Self, Self::Error> {
if value < 0. {
Err(Self::Error::NegativeRate)
} else {
Ok(Self(value))
}
}
}
impl TryFrom<f64> for Probability {
type Error = ConversionError;
fn try_from(value: f64) -> Result<Self, Self::Error> {
if !(0_f64..=1.).contains(&value) {
Err(Self::Error::NotInbetweenZeroAndOne)
} else {
Ok(Self(value))
}
}
}
/// $\lambda = -\log(1-p)$
impl From<Probability> for Rate {
fn from(probability: Probability) -> Self {
Self(-(1. - probability.0).ln())
}
}
/// $p=1-\exp(-\lambda)$
impl From<Rate> for Probability {
fn from(rate: Rate) -> Self {
Self(1. - (-rate.0).exp())
}
}
impl Probability {
// but this doesn't really work...
// pub fn compound(self, other: Self) -> Self {
// Self((1. - self.0) * (1. - other.0))
// }
/// Composition is done according to [Poisson binomial distribution](https://www.wikiwand.com/en/Poisson_binomial_distribution)
///
pub fn compound<const N: usize>(probabilities: [Self; N]) -> Self {
Self(
1. - std::array::IntoIter::new(probabilities)
.map(|x| 1. - x.0)
.product::<f64>(),
)
}
}
///
///
/// Formula is: probability = 1 - exp(-\sum_i \lambda_i)
pub fn compound_rates(rates: &[Rate]) -> Probability {
Probability::try_from(1. - rates.iter().copied().sum::<Rate>().0.neg().exp()).unwrap()
}
/// This is less numerically efficient/precise than [compound_rates], but it
/// should yield the same result.
fn compound_probabilities(probabilities: &[Probability]) -> Probability {
probabilities
.iter()
.map(|p| p.complement())
// .product::<Probability>() // use this instead when derive_more works
// with Product and Mul
.fold(Probability::new(1.).unwrap(), |mut acc, x| {
acc.0 *= x.0;
acc
})
.complement()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_equivalence_of_compounding_probability() {
dbg!(&compound_rates(&[
Rate::new(0.5).unwrap(),
Rate::new(0.5).unwrap(),
// Rate::new(12.).unwrap()
]));
dbg!(&compound_probabilities(&[
Probability::new(0.5).unwrap(),
Probability::new(0.5).unwrap(),
// Rate::new(12.).unwrap()
]));
// dbg!(&compound_rates([0.5, 0.5]));
}
}
|
use std::{ffi::CString, os::raw::c_char, ptr};
use crate::v8facade::{JavaScriptError, JavaScriptResult, Output};
#[repr(C)]
#[derive(Debug)]
pub struct UnsafeJavaScriptError {
pub exception: *mut c_char,
pub stack_trace: *mut c_char,
}
#[repr(C)]
#[derive(Debug)]
pub struct PrimitiveResult {
pub number_value: f64,
pub number_value_set: bool,
pub bigint_value: i64,
pub bigint_value_set: bool,
pub bool_value: bool,
pub bool_value_set: bool,
pub string_value: *mut c_char,
pub array_value: *mut c_char,
pub object_value: *mut c_char,
pub error: *mut UnsafeJavaScriptError,
}
impl PrimitiveResult {
pub fn blank() -> PrimitiveResult {
PrimitiveResult {
number_value: 0.0,
number_value_set: false,
bigint_value: 0,
bigint_value_set: false,
bool_value: false,
bool_value_set: false,
string_value: ptr::null_mut(),
array_value: ptr::null_mut(),
object_value: ptr::null_mut(),
error: ptr::null_mut(),
}
}
pub fn create_for_number(number: f64) -> PrimitiveResult {
let blank_result = PrimitiveResult::blank();
PrimitiveResult {
number_value: number,
number_value_set: true,
..blank_result
}
}
pub fn create_for_bigint(bigint: i64) -> PrimitiveResult {
let blank_result = PrimitiveResult::blank();
PrimitiveResult {
bigint_value: bigint,
bigint_value_set: true,
..blank_result
}
}
pub fn create_for_bool(boolean: bool) -> PrimitiveResult {
let blank_result = PrimitiveResult::blank();
PrimitiveResult {
bool_value: boolean,
bool_value_set: true,
..blank_result
}
}
pub fn create_for_string(string: String) -> PrimitiveResult {
let blank_result = PrimitiveResult::blank();
PrimitiveResult {
string_value: CString::new(string).unwrap().into_raw(),
..blank_result
}
}
pub fn create_for_array(array: String) -> PrimitiveResult {
let blank_result = PrimitiveResult::blank();
PrimitiveResult {
array_value: CString::new(array).unwrap().into_raw(),
..blank_result
}
}
pub fn create_for_object(object: String) -> PrimitiveResult {
let blank_result = PrimitiveResult::blank();
PrimitiveResult {
object_value: CString::new(object).unwrap().into_raw(),
..blank_result
}
}
pub fn create_for_error(javascript_error: JavaScriptError) -> PrimitiveResult {
let exception = CString::new(javascript_error.exception).unwrap().into_raw();
let stack_trace = CString::new(javascript_error.stack_trace)
.unwrap()
.into_raw();
let unsafe_error = UnsafeJavaScriptError {
exception,
stack_trace,
};
let unsafe_error = Box::into_raw(Box::new(unsafe_error));
let blank_result = PrimitiveResult::blank();
PrimitiveResult {
error: unsafe_error,
..blank_result
}
}
pub fn from_output(output: Output) -> PrimitiveResult {
match output {
Output::Result(r) => match r {
JavaScriptResult::StringValue(s) => {
PrimitiveResult::create_for_string(s)
}
JavaScriptResult::NumberValue(n) => {
PrimitiveResult::create_for_number(n)
}
JavaScriptResult::BigIntValue(i) => {
PrimitiveResult::create_for_bigint(i)
}
JavaScriptResult::BoolValue(b) => {
PrimitiveResult::create_for_bool(b)
}
JavaScriptResult::ArrayValue(av) => {
PrimitiveResult::create_for_array(av)
}
JavaScriptResult::ObjectValue(ov) => {
PrimitiveResult::create_for_object(ov)
}
},
Output::Error(e) => PrimitiveResult::create_for_error(e),
// You can't get heap statistics out of V8 by invoking script so this result is impossible.
Output::HeapStatistics(_) => unreachable!(),
}
}
pub fn from_javascriptresult(result: JavaScriptResult) -> PrimitiveResult {
match result {
JavaScriptResult::ArrayValue(v) => {
PrimitiveResult::create_for_array(v)
}
JavaScriptResult::StringValue(v) => {
PrimitiveResult::create_for_string(v)
}
JavaScriptResult::NumberValue(v) => {
PrimitiveResult::create_for_number(v)
}
JavaScriptResult::BigIntValue(v) => {
PrimitiveResult::create_for_bigint(v)
}
JavaScriptResult::BoolValue(v) => {
PrimitiveResult::create_for_bool(v)
}
JavaScriptResult::ObjectValue(v) => {
PrimitiveResult::create_for_object(v)
}
}
}
pub fn into_raw(self: Self) -> *mut PrimitiveResult {
Box::into_raw(Box::new(self))
}
pub unsafe fn free_raw(raw_prim_result: *mut PrimitiveResult) {
let primitive_result = Box::from_raw(raw_prim_result);
if !primitive_result.string_value.is_null() {
CString::from_raw(primitive_result.string_value);
}
if !primitive_result.array_value.is_null() {
CString::from_raw(primitive_result.array_value);
}
if !primitive_result.object_value.is_null() {
CString::from_raw(primitive_result.object_value);
}
if !primitive_result.error.is_null() {
let error = primitive_result.error;
CString::from_raw((*error).exception);
CString::from_raw((*error).stack_trace);
Box::from_raw(primitive_result.error);
}
}
} |
use fraction::ToPrimitive;
use encoding_rs::*;
//reading functions
/// Read a byte and increase the cursor position by 1
/// * `data` - array of bytes
/// * `seek` - start position to read
/// * returns the read byte as u8
pub(crate) fn read_byte(data: &[u8], seek: &mut usize ) -> u8 {
if data.len() < *seek {panic!("End of filee reached");}
let b = data[*seek];
*seek += 1;
b
}
/// Read a signed byte and increase the cursor position by 1
/// * `data` - array of bytes
/// * `seek` - start position to read
/// * returns the read byte as u8
pub(crate) fn read_signed_byte(data: &[u8], seek: &mut usize ) -> i8 {
if data.len() < *seek {panic!("End of file reached");}
let b = data[*seek] as i8;
*seek += 1;
b
}
/// Read a boolean and increase the cursor position by 1
/// * `data` - array of bytes
/// * `seek` - start position to read
/// * returns boolean value
pub(crate) fn read_bool(data: &[u8], seek: &mut usize ) -> bool {
if data.len() < *seek {panic!("End of file reached");}
let b = data[*seek];
*seek += 1;
b != 0
}
/// Read a short and increase the cursor position by 2 (2 little-endian bytes)
/// * `data` - array of bytes
/// * `seek` - start position to read
/// * returns the short value
pub(crate) fn read_short(data: &[u8], seek: &mut usize ) -> i16 {
if data.len() < *seek + 2 {panic!("End of file reached");}
let n = i16::from_le_bytes([data[*seek], data[*seek+1]]);
*seek += 2;
n
}
/// Read an integer and increase the cursor position by 4 (4 little-endian bytes)
/// * `data` - array of bytes
/// * `seek` - start position to read
/// * returns the integer value
pub(crate) fn read_int(data: &[u8], seek: &mut usize ) -> i32 {
if data.len() < *seek + 4 {panic!("End of file reached");}
let n = i32::from_le_bytes([data[*seek], data[*seek+1], data[*seek+2], data[*seek+3]]);
*seek += 4;
n
}
/*/// Read a float and increase the cursor position by 4 (4 little-endian bytes)
/// * `data` - array of bytes
/// * `seek` - start position to read
/// * returns the float value
pub(crate) fn read_float(data: &[u8], seek: &mut usize ) -> f32 {
let n = f32::from_le_bytes([data[*seek], data[*seek+1], data[*seek+2], data[*seek+3]]);
*seek += 4;
n
}*/
/// Read a double and increase the cursor position by 8 (8 little-endian bytes)
/// * `data` - array of bytes
/// * `seek` - start position to read
/// * returns the float value
pub(crate) fn read_double(data: &[u8], seek: &mut usize ) -> f64 {
let n = f64::from_le_bytes([data[*seek], data[*seek+1], data[*seek+2], data[*seek+3], data[*seek+4], data[*seek+5], data[*seek+6], data[*seek+7]]);
*seek += 8;
n
}
/// Read length of the string stored in 1 integer and followed by character bytes.
pub(crate) fn read_int_size_string(data: &[u8], seek: &mut usize) -> String {
let size = read_int(data, seek).to_usize().unwrap();
read_string(data, seek, size, None)
}
/// Read length of the string increased by 1 and stored in 1 integer followed by length of the string in 1 byte and finally followed by character bytes.
pub(crate) fn read_int_byte_size_string(data: &[u8], seek: &mut usize) -> String {
let s = (read_int(data, seek) - 1).to_usize().unwrap();
read_byte_size_string(data, seek, s)
}
/// Read length of the string stored in 1 byte and followed by character bytes.
/// * `size`: string length that we should attempt to read.
pub(crate) fn read_byte_size_string(data: &[u8], seek: &mut usize, size: usize) -> String {
//println!("read_int_byte_size_string(), size={}", size);
let length = read_byte(data, seek).to_usize().unwrap();
read_string(data, seek, size, Some(length))
}
/// Read a string
/// * `size`: real string length
/// * `length`: optionnal provided length (in case of blank chars after the string)
fn read_string(data: &[u8], seek: &mut usize, size: usize, length: Option<usize>) -> String {
//println!("read_string(), size={} \t length={:?}", size, length);
let length = length.unwrap_or(size);
//let count = if size > 0 {size} else {length};
let (cow, _encoding_used, had_errors) = WINDOWS_1252.decode(&data[*seek..*seek+length]);
if had_errors {
let parse = std::str::from_utf8(&data[*seek..*seek+length]);
if parse.is_err() {panic!("Unable to read string");}
*seek += size;
return parse.unwrap().to_string();
}
*seek += size;
cow.to_string()
}
pub const VERSIONS: [((u8,u8,u8), bool, &str); 10] = [((3, 0, 0), false, "FICHIER GUITAR PRO v3.00"),
((4, 0, 0), false, "FICHIER GUITAR PRO v4.00"),
((4, 0, 6), false, "FICHIER GUITAR PRO v4.06"),
((4, 0, 6), true, "CLIPBOARD GUITAR PRO 4.0 [c6]"),
((5, 0, 0), false, "FICHIER GUITAR PRO v5.00"),
((5, 1, 0), false, "FICHIER GUITAR PRO v5.10"),
((5, 2, 0), false, "FICHIER GUITAR PRO v5.10"), // sic
((5, 0, 0), true, "CLIPBOARD GP 5.0"),
((5, 1, 0), true, "CLIPBOARD GP 5.1"),
((5, 2, 0), true, "CLIPBOARD GP 5.2")];
/// Read the file version. It is on the first 31 bytes (1st byte is the real length, the following 30 bytes contain the version string) of the file.
/// * `data` - array of bytes
/// * `seek` - cursor that will be incremented
/// * returns version
pub(crate) fn read_version_string(data: &[u8], seek: &mut usize) -> crate::headers::Version {
let mut v = crate::headers::Version {data: read_byte_size_string(data, seek, 30), number: (5,2,0), clipboard: false};
//println!("Version {} {}", n, s);
//get the version
for x in VERSIONS {
if v.data == x.2 {
v.number = x.0;
v.clipboard = x.1;
break;
}
}
//println!("########################## Version: {:?}", v);
v
}
/// Read a color. Colors are used by `Marker` and `Track`. They consist of 3 consecutive bytes and one blank byte.
pub(crate) fn read_color(data: &[u8], seek: &mut usize) -> i32 {
let r = read_byte(data, seek).to_i32().unwrap();
let g = read_byte(data, seek).to_i32().unwrap();
let b = read_byte(data, seek).to_i32().unwrap();
*seek += 1;
r * 65536 + g * 256 + b
}
//writing functions
fn write_placeholder(data: &mut Vec<u8>, count: usize, byte: u8) { for _ in 0..count {data.push(byte);} }
pub(crate) fn write_placeholder_default(data: &mut Vec<u8>, count: usize) {write_placeholder(data, count, 0x00);}
pub(crate) fn write_byte(data: &mut Vec<u8>, value: u8) {data.push(value);}
pub(crate) fn write_signed_byte(data: &mut Vec<u8>, value: i8) {data.extend(value.to_le_bytes());}
pub(crate) fn write_bool(data: &mut Vec<u8>, value: bool) {data.push(u8::from(value));}
pub(crate) fn write_i32(data: &mut Vec<u8>, value: i32) {data.extend(value.to_le_bytes());}
//pub(crate) fn write_u32(data: &mut Vec<u8>, value: u32) {data.extend(value.to_le_bytes());}
pub(crate) fn write_i16(data: &mut Vec<u8>, value: i16) {data.extend(value.to_le_bytes());}
//pub(crate) fn write_u16(data: &mut Vec<u8>, value: u16) {data.extend(value.to_le_bytes());}
//pub(crate) fn write_f32(data: &mut Vec<u8>, value: f32) {data.extend(value.to_le_bytes());}
pub(crate) fn write_f64(data: &mut Vec<u8>, value: f64) {data.extend(value.to_le_bytes());}
pub(crate) fn write_color(data: &mut Vec<u8>, value: i32) {
let r: u8 = ((value & 0xff0000) >> 16).to_u8().unwrap();
let g: u8 = ((value & 0x00ff00) >> 8).to_u8().unwrap();
let b: u8 = (value & 0x0000ff).to_u8().unwrap();
write_byte(data, r);
write_byte(data, g);
write_byte(data, b);
write_placeholder_default(data, 1);
}
pub(crate) fn write_byte_size_string(data: &mut Vec<u8>, value: &str) {
write_byte(data, value.chars().count().to_u8().unwrap());
data.extend(value.as_bytes());
}
pub(crate) fn write_int_size_string(data: &mut Vec<u8>, value: &str) {
let count = value.chars().count();
write_i32(data, count.to_i32().unwrap()+1);
data.extend(value.as_bytes());
}
pub(crate) fn write_int_byte_size_string(data: &mut Vec<u8>, value: &str) {
let count = value.chars().count();
write_i32(data, count.to_i32().unwrap()+1); //write_i32( (value.getBytes(charset).length + 1) );
write_byte(data, count.to_u8().unwrap());
data.extend(value.as_bytes());
}
pub(crate) fn write_version(data: &mut Vec<u8>, version: (u8,u8,u8)) {
for v in VERSIONS {
if version == v.0 {
write_byte_size_string(data, v.2);
write_placeholder_default(data, 30 - v.2.len());
break;
}
}
}
#[cfg(test)]
mod test {
use crate::io::*;
#[test]
fn test_read_byte_size_string() {
let data: Vec<u8> = vec![0x18,0x46,0x49,0x43,0x48,0x49,0x45,0x52,
0x20,0x47,0x55,0x49,0x54,0x41,0x52,0x20,
0x50,0x52,0x4f,0x20,0x76,0x33,0x2e,0x30,
0x30];
let mut seek = 0usize;
assert_eq!(read_byte_size_string(&data, &mut seek, 30), "FICHIER GUITAR PRO v3.00");
}
#[test]
fn test_read_int_size_string() {
let data: Vec<u8> = vec![0x08,0x00,0x00,0x00, 0x25,0x41,0x52,0x54,0x49,0x53,0x54,0x25];
let mut seek = 0usize;
assert_eq!(read_int_size_string(&data, &mut seek), "%ARTIST%");
}
#[test]
fn test_read_int_byte_size_string() {
let data: Vec<u8> = vec![0x09,0x00,0x00,0x00, 0x08, 0x25,0x41,0x52,0x54,0x49,0x53,0x54,0x25];
let mut seek = 0usize;
assert_eq!(read_int_byte_size_string(&data, &mut seek), "%ARTIST%");
}
#[test]
fn test_write_byte_size_string() {
let mut out: Vec<u8> = Vec::with_capacity(32);
write_byte_size_string(&mut out, "FICHIER GUITAR PRO v3.00");
let expected_result: Vec<u8> = vec![0x18,0x46,0x49,0x43,0x48,0x49,0x45,0x52,
0x20,0x47,0x55,0x49,0x54,0x41,0x52,0x20,
0x50,0x52,0x4f,0x20,0x76,0x33,0x2e,0x30,
0x30];
assert_eq!(out, expected_result);
}
#[test]
fn test_write_int_size_string() {
let mut out: Vec<u8> = Vec::with_capacity(16);
write_int_size_string(&mut out, "%ARTIST%");
let expected_result: Vec<u8> = vec![0x09,0x00,0x00,0x00, 0x08,0x25,0x41,0x52,0x54,0x49,0x53,0x54,0x25];
assert_eq!(out, expected_result);
}
#[test]
fn test_write_int_byte_size_string() {
let mut out: Vec<u8> = Vec::with_capacity(16);
write_int_byte_size_string(&mut out, "%ARTIST%");
let expected_result: Vec<u8> = vec![0x09,0x00,0x00,0x00, 0x08, 0x25,0x41,0x52,0x54,0x49,0x53,0x54,0x25];
assert_eq!(out, expected_result);
}
}
|
//! To run this code, clone the rusty_engine repository and run the command:
//!
//! cargo run --release --example sfx_sampler
use rusty_engine::prelude::*;
#[derive(Default)]
struct GameState {
sfx_timers: Vec<Timer>,
end_timer: Timer,
}
fn main() {
let mut game = Game::new();
let mut game_state = GameState::default();
// One timer to launch each sound effect
for (i, _sfx) in SfxPreset::variant_iter().enumerate() {
game_state
.sfx_timers
.push(Timer::from_seconds((i as f32) * 2.0, false));
}
// One timer to end them all
game_state.end_timer =
Timer::from_seconds((SfxPreset::variant_iter().len() as f32) * 2.0 + 1.0, false);
let mut msg = game.add_text("msg", "Playing sound effects!");
msg.translation = Vec2::new(0.0, 100.0);
msg.font_size = 60.0;
let mut sfx_label = game.add_text("sfx_label", "");
sfx_label.translation = Vec2::new(0.0, -100.0);
sfx_label.font_size = 90.0;
game.add_logic(logic);
game.run(game_state);
}
fn logic(engine: &mut Engine, game_state: &mut GameState) {
for (i, timer) in game_state.sfx_timers.iter_mut().enumerate() {
// None of the timers repeat, and they're all set to different times, so when the timer in
// index X goes off, play sound effect in index X
if timer.tick(engine.delta).just_finished() {
// Play a new sound effect
let sfx = SfxPreset::variant_iter().nth(i).unwrap();
engine.audio_manager.play_sfx(sfx, 1.0);
// Update the text to show which sound effect we are playing
let sfx_label = engine.texts.get_mut("sfx_label").unwrap();
sfx_label.value = format!("{:?}", sfx);
}
}
// Are we all done?
if game_state.end_timer.tick(engine.delta).just_finished() {
let sfx_label = engine.texts.get_mut("sfx_label").unwrap();
sfx_label.value = "That's all! Press Esc to quit.".into();
}
}
|
fn main() {
let this_file: &str = file!();
println!("file_name: {}", this_file);
println!("line: {}", line!());
println!("column: {}", column!());
}
|
#[derive(PartialEq, Copy, Clone)]
enum Direction {
Down, Up, Left, Right
}
#[derive(PartialEq, Copy, Clone)]
enum Part {
Cable, Letter, Space
}
type Point = (i32,i32);
type Map = Vec<String>;
fn next( p : &Point, d : &Direction ) -> Point {
let (x,y) = p;
match d {
Direction::Down => ( *x, *y + 1 ),
Direction::Up => ( *x, *y - 1 ),
Direction::Left => ( *x - 1, *y ),
Direction::Right => ( *x + 1, *y )
}
}
fn at( m : &Map, p : &Point ) -> char {
let (x,y) = p;
let empty = ' ';
if *x < 0 || *y < 0 { return empty; }
let sy = m.len() as i32;
if *y >= sy { return empty; }
let row : &str = m.get(*y as usize).unwrap();
let sx = row.len() as i32;
if *x >= sx { return empty; }
return row.chars().nth( *x as usize).unwrap();
}
fn opposite( d: &Direction ) -> Direction {
match *d {
Direction::Right => Direction::Left,
Direction::Left => Direction::Right,
Direction::Up => Direction::Down,
Direction::Down => Direction::Up
}
}
fn directions( d: &Direction ) -> Vec<Direction> {
let mut r = vec![Direction::Down, Direction::Left, Direction::Right, Direction::Up];
let o : Direction = opposite(d);
let i = r.iter().position( |e| *e == o ).unwrap();
r.remove(i);
r
}
fn is_cross( c : char ) -> bool { c == '+' }
fn is_cable( c : char ) -> bool {
match c {
'-' | '|' | '+' => true,
_ => false
}
}
fn is_space( c : char ) -> bool { c == ' ' }
fn what( c : char ) -> Part {
if is_cable(c) { return Part::Cable }
if is_space( c ) { return Part::Space }
Part::Letter
}
fn next_point( m: &Map, p : &Point, d : &Direction ) -> Option<( Point, Direction )> {
let nd = directions(d);
for d1 in nd {
let p1 = next(&p, &d1);
let c1 = at(&m, &p1);
if !is_space(c1 ) {
return Some( ( p1, d1 ) );
}
}
None
}
pub fn task12(map : &str) -> ( String, i32 ) {
let m : Map = map.lines().map( |s| s.to_string() ).collect();
let mut answer = String::new();
let start = m.get(0).unwrap().find('|').unwrap() as i32;
let mut p : Point = (start, 0);
let mut d = Direction::Down;
let mut steps = 1;
loop {
let c = at(&m, &p);
let part = what(c);
match part {
Part::Letter => answer.push(c),
Part::Space =>
panic!( "must not ever happen" ),
Part::Cable => {}
}
let p1 = next(&p, &d);
let cross = is_cross(c) || ( part == Part::Letter && is_space( at( &m, &p1 ) ) );
if cross {
let o1 = next_point( &m, &p, &d );
match o1 {
None => break,
Some( (p1, d1) ) => { p = p1; d = d1 }
}
} else {
p = p1;
}
steps += 1;
}
( answer, steps )
}
|
use std::collections::HashMap;
use std::collections::HashSet;
type Coord = (i32, i32);
fn main() {
let fname = "data/06.txt";
let fdata = std::fs::read_to_string(fname)
.expect(&format!("couldn't read {}", fname));
let mut lines : Vec<&str> = fdata.lines().collect();
lines.sort();
let parsed_lines : Vec<Coord> =
lines.iter().map(|line| parse_line(&line)).collect();
println!("result p1: {}", part1(&parsed_lines));
println!("result p2: {}", part2(&parsed_lines));
}
fn parse_line(l : &str) -> Coord {
let mut s = l.split(", ");
( s.next().expect("x").parse::<i32>().expect("parse x")
, s.next().expect("y").parse::<i32>().expect("parse y")
)
}
#[test]
fn test_parse() {
let parsed = parse_line("3, 23");
assert_eq!(3, parsed.0);
assert_eq!(23, parsed.1);
}
fn part1(coords: &Vec<Coord>) -> i32 {
let (x0, x1, y0, y1) = grid_corner_coords(coords);
let cap : usize = ((x1 - x0) * (y1 - y0)) as usize;
let mut counts : HashMap<&(i32, i32), i32> = HashMap::with_capacity(cap);
let mut hitting_edge : HashSet<&(i32, i32)> = HashSet::new();
for x in (x0 - 1)..(x1 + 1) {
for y in (y0 - 1)..(y1 + 1) {
match closest(coords, (x, y)) {
None => {}
Some(c) => {
*counts.entry(c).or_insert(0) += 1;
if x == x0 || x == x1 || y == y0 || y == y1 {
hitting_edge.insert(c);
}
}
}
}
}
let mut by_largest = counts.iter().collect::<Vec<_>>();
by_largest.sort_by(|(_,v1), (_,v2)| {v2.cmp(v1)});
*by_largest.iter()
.filter(|(c, _)| { ! hitting_edge.contains(*c) }).nth(0)
.expect("largest not hitting edge").1
}
fn grid_corner_coords(coords: &Vec<Coord>) -> (i32, i32, i32, i32) {
let mut x0 = None;
let mut x1 = None;
let mut y0 = None;
let mut y1 = None;
for (x, y) in coords {
match x0 { None => { x0 = Some(x); }
| Some(xx0) => { if x < xx0 { x0 = Some(x); }} };
match x1 { None => { x1 = Some(x); }
| Some(xx1) => { if x > xx1 { x1 = Some(x); }} };
match y0 { None => { y0 = Some(y); }
| Some(yy0) => { if y < yy0 { y0 = Some(y); }} };
match y1 { None => { y1 = Some(y); }
| Some(yy1) => { if y > yy1 { y1 = Some(y); }} };
}
(*x0.expect("x0"), *x1.expect("x1"), *y0.expect("y0"), *y1.expect("y1"))
}
fn closest(coords: &Vec<Coord>, c0: (i32, i32)) -> Option<&Coord> {
let mut closest_d = None;
let mut closest_coords = Vec::new();
for c1 in coords {
let new_d = distance(*c1, c0);
match closest_d {
| None => {
closest_d = Some(new_d);
closest_coords.push(c1);
}
| Some(old_d) => {
if new_d < old_d {
closest_d = Some(new_d);
closest_coords.clear();
closest_coords.push(c1);
} else if new_d == old_d {
closest_coords.push(c1);
}
}
}
}
if closest_coords.len() == 1 {
Some(closest_coords[0])
} else {
None
}
}
fn distance((x1, y1) : Coord, (x2, y2): Coord) -> i32 {
(x2 - x1).abs() + (y2 - y1).abs()
}
fn part2(coords: &Vec<Coord>) -> i32 {
let (x0, x1, y0, y1) = grid_corner_coords(coords);
let mut count = 0;
for x in (x0 - 1)..(x1 + 1) {
for y in (y0 - 1)..(y1 + 1) {
if coords.iter().fold(0, |acc, c| { acc + distance(*c, (x, y)) }) < 10000 {
count += 1;
}
}
}
count
}
|
#![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 ISysStorageProviderEventReceivedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISysStorageProviderEventReceivedEventArgs {
type Vtable = ISysStorageProviderEventReceivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe132d1b9_7b9d_5820_9728_4262b5289142);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISysStorageProviderEventReceivedEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISysStorageProviderEventReceivedEventArgsFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISysStorageProviderEventReceivedEventArgsFactory {
type Vtable = ISysStorageProviderEventReceivedEventArgsFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xde1a780e_e975_5f68_bcc6_fb46281c6a61);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISysStorageProviderEventReceivedEventArgsFactory_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, json: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISysStorageProviderEventSource(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISysStorageProviderEventSource {
type Vtable = ISysStorageProviderEventSource_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f36c476_9546_536a_8381_2f9a2c08cedd);
}
impl ISysStorageProviderEventSource {
#[cfg(feature = "Foundation")]
pub fn EventReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<ISysStorageProviderEventSource, SysStorageProviderEventReceivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveEventReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for ISysStorageProviderEventSource {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{1f36c476-9546-536a-8381-2f9a2c08cedd}");
}
impl ::core::convert::From<ISysStorageProviderEventSource> for ::windows::core::IUnknown {
fn from(value: ISysStorageProviderEventSource) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISysStorageProviderEventSource> for ::windows::core::IUnknown {
fn from(value: &ISysStorageProviderEventSource) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISysStorageProviderEventSource {
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 ISysStorageProviderEventSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISysStorageProviderEventSource> for ::windows::core::IInspectable {
fn from(value: ISysStorageProviderEventSource) -> Self {
value.0
}
}
impl ::core::convert::From<&ISysStorageProviderEventSource> for ::windows::core::IInspectable {
fn from(value: &ISysStorageProviderEventSource) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISysStorageProviderEventSource {
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 ISysStorageProviderEventSource {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISysStorageProviderEventSource_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, handler: ::windows::core::RawPtr, result__: *mut 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::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISysStorageProviderHandlerFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISysStorageProviderHandlerFactory {
type Vtable = ISysStorageProviderHandlerFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xee798431_8213_5e89_a623_14d8c72b8a61);
}
impl ISysStorageProviderHandlerFactory {
pub fn GetHttpRequestProvider<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, syncrootid: Param0) -> ::windows::core::Result<ISysStorageProviderHttpRequestProvider> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), syncrootid.into_param().abi(), &mut result__).from_abi::<ISysStorageProviderHttpRequestProvider>(result__)
}
}
pub fn GetEventSource<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, syncrootid: Param0, eventname: Param1) -> ::windows::core::Result<ISysStorageProviderEventSource> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), syncrootid.into_param().abi(), eventname.into_param().abi(), &mut result__).from_abi::<ISysStorageProviderEventSource>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ISysStorageProviderHandlerFactory {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{ee798431-8213-5e89-a623-14d8c72b8a61}");
}
impl ::core::convert::From<ISysStorageProviderHandlerFactory> for ::windows::core::IUnknown {
fn from(value: ISysStorageProviderHandlerFactory) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISysStorageProviderHandlerFactory> for ::windows::core::IUnknown {
fn from(value: &ISysStorageProviderHandlerFactory) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISysStorageProviderHandlerFactory {
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 ISysStorageProviderHandlerFactory {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISysStorageProviderHandlerFactory> for ::windows::core::IInspectable {
fn from(value: ISysStorageProviderHandlerFactory) -> Self {
value.0
}
}
impl ::core::convert::From<&ISysStorageProviderHandlerFactory> for ::windows::core::IInspectable {
fn from(value: &ISysStorageProviderHandlerFactory) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISysStorageProviderHandlerFactory {
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 ISysStorageProviderHandlerFactory {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISysStorageProviderHandlerFactory_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, syncrootid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, syncrootid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, eventname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISysStorageProviderHttpRequestProvider(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISysStorageProviderHttpRequestProvider {
type Vtable = ISysStorageProviderHttpRequestProvider_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcb6fefb6_e76a_5c25_a33e_3e78a6e0e0ce);
}
impl ISysStorageProviderHttpRequestProvider {
#[cfg(all(feature = "Foundation", feature = "Web_Http"))]
pub fn SendRequestAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Web::Http::HttpRequestMessage>>(&self, request: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncOperation<super::super::super::Web::Http::HttpResponseMessage>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), request.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncOperation<super::super::super::Web::Http::HttpResponseMessage>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ISysStorageProviderHttpRequestProvider {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{cb6fefb6-e76a-5c25-a33e-3e78a6e0e0ce}");
}
impl ::core::convert::From<ISysStorageProviderHttpRequestProvider> for ::windows::core::IUnknown {
fn from(value: ISysStorageProviderHttpRequestProvider) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISysStorageProviderHttpRequestProvider> for ::windows::core::IUnknown {
fn from(value: &ISysStorageProviderHttpRequestProvider) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISysStorageProviderHttpRequestProvider {
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 ISysStorageProviderHttpRequestProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISysStorageProviderHttpRequestProvider> for ::windows::core::IInspectable {
fn from(value: ISysStorageProviderHttpRequestProvider) -> Self {
value.0
}
}
impl ::core::convert::From<&ISysStorageProviderHttpRequestProvider> for ::windows::core::IInspectable {
fn from(value: &ISysStorageProviderHttpRequestProvider) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISysStorageProviderHttpRequestProvider {
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 ISysStorageProviderHttpRequestProvider {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISysStorageProviderHttpRequestProvider_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 = "Web_Http"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, request: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Web_Http")))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SysStorageProviderEventReceivedEventArgs(pub ::windows::core::IInspectable);
impl SysStorageProviderEventReceivedEventArgs {
pub fn Json(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn CreateInstance<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(json: Param0) -> ::windows::core::Result<SysStorageProviderEventReceivedEventArgs> {
Self::ISysStorageProviderEventReceivedEventArgsFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), json.into_param().abi(), &mut result__).from_abi::<SysStorageProviderEventReceivedEventArgs>(result__)
})
}
pub fn ISysStorageProviderEventReceivedEventArgsFactory<R, F: FnOnce(&ISysStorageProviderEventReceivedEventArgsFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SysStorageProviderEventReceivedEventArgs, ISysStorageProviderEventReceivedEventArgsFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SysStorageProviderEventReceivedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.System.Implementation.FileExplorer.SysStorageProviderEventReceivedEventArgs;{e132d1b9-7b9d-5820-9728-4262b5289142})");
}
unsafe impl ::windows::core::Interface for SysStorageProviderEventReceivedEventArgs {
type Vtable = ISysStorageProviderEventReceivedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe132d1b9_7b9d_5820_9728_4262b5289142);
}
impl ::windows::core::RuntimeName for SysStorageProviderEventReceivedEventArgs {
const NAME: &'static str = "Windows.System.Implementation.FileExplorer.SysStorageProviderEventReceivedEventArgs";
}
impl ::core::convert::From<SysStorageProviderEventReceivedEventArgs> for ::windows::core::IUnknown {
fn from(value: SysStorageProviderEventReceivedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SysStorageProviderEventReceivedEventArgs> for ::windows::core::IUnknown {
fn from(value: &SysStorageProviderEventReceivedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SysStorageProviderEventReceivedEventArgs {
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 SysStorageProviderEventReceivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SysStorageProviderEventReceivedEventArgs> for ::windows::core::IInspectable {
fn from(value: SysStorageProviderEventReceivedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&SysStorageProviderEventReceivedEventArgs> for ::windows::core::IInspectable {
fn from(value: &SysStorageProviderEventReceivedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SysStorageProviderEventReceivedEventArgs {
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 SysStorageProviderEventReceivedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SysStorageProviderEventReceivedEventArgs {}
unsafe impl ::core::marker::Sync for SysStorageProviderEventReceivedEventArgs {}
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![feature(overlapping_marker_traits)]
#![feature(optin_builtin_traits)]
// Overlapping negative impls for `MyStruct` are permitted:
struct MyStruct;
impl !Send for MyStruct {}
impl !Send for MyStruct {}
fn main() {
}
|
// "Tifflin" Kernel - FAT Filesystem Driver
// - By John Hodge (thePowersGang)
//
// Modules/fs_fat/on_disk.rs
//! On-Disk structures and flags
#[allow(unused_imports)]
use kernel::prelude::*;
pub const ATTR_READONLY : u8 = 0x01; // Read-only file
pub const ATTR_HIDDEN : u8 = 0x02; // Hidden File
pub const ATTR_SYSTEM : u8 = 0x04; // System File
pub const ATTR_VOLUMEID : u8 = 0x08; // Volume ID (Deprecated)
pub const ATTR_DIRECTORY: u8 = 0x10; // Directory
pub const ATTR_LFN: u8 = ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUMEID;
#[allow(dead_code)]
pub const ATTR_ARCHIVE : u8 = 0x20; // Flag set by user
pub const CASE_LOWER_BASE: u8 = 0x08; // Linux (maybe NT) flag
pub const CASE_LOWER_EXT : u8 = 0x10; // Linux (maybe NT) flag
fn read_u8(s: &mut &[u8]) -> u8 {
use kernel::lib::byteorder::ReadBytesExt;
s.read_u8().unwrap()
}
fn read_u16(s: &mut &[u8]) -> u16 {
use kernel::lib::byteorder::{ReadBytesExt,LittleEndian};
s.read_u16::<LittleEndian>().unwrap()
}
fn read_u32(s: &mut &[u8]) -> u32 {
use kernel::lib::byteorder::{ReadBytesExt,LittleEndian};
s.read_u32::<LittleEndian>().unwrap()
}
fn read_arr<T: AsMut<[u8]>>(s: &mut &[u8]) -> T {
use kernel::lib::io::Read;
// (mostly) SAFE: 'T' should be POD... but can't enforce that easily
let mut v: T = unsafe { ::core::mem::zeroed() };
s.read(v.as_mut()).unwrap();
v
}
fn read_arr16<T: AsMut<[u16]>>(s: &mut &[u8]) -> T {
// (mostly) SAFE: 'T' should be POD... but can't enforce that easily
let mut v: T = unsafe { ::core::mem::zeroed() };
for p in v.as_mut() {
*p = read_u16(s);
}
v
}
pub enum BootSect
{
Legacy(BootSect16),
Fat32(BootSect32),
}
impl BootSect {
pub fn read(src: &[u8]) -> BootSect {
assert_eq!(src.len(), 512);
let mut s = src;
let common = BootSectInfo::read(&mut s);
assert_eq!(s.len(), 512-0x24);
if common.fat_size_16 > 0 {
let rv = BootSect::Legacy( BootSect16 {
common: common,
info: BootSect16Info::read(&mut s),
});
assert_eq!(s.len(), 512-(0x24+26));
rv
}
else {
let rv = BootSect::Fat32( BootSect32 {
common: common,
info32: BootSect32Info::read(&mut s),
info16: BootSect16Info::read(&mut s),
});
assert_eq!(s.len(), 512-90);
rv
}
}
pub fn common(&self) -> &BootSectInfo {
match self
{
&BootSect::Legacy(ref i) => &i.common,
&BootSect::Fat32(ref i) => &i.common,
}
}
pub fn info32(&self) -> Option<&BootSect32Info> {
match self
{
&BootSect::Legacy(_) => None,
&BootSect::Fat32(ref i) => Some(&i.info32),
}
}
pub fn tail_common(&self) -> &BootSect16Info {
match self
{
&BootSect::Legacy(ref i) => &i.info,
&BootSect::Fat32(ref i) => &i.info16,
}
}
}
pub struct BootSectInfo
{
pub _jump: [u8; 3],
pub oem_name: [u8; 8],
pub bps: u16,
pub spc: u8,
pub reserved_sect_count: u16,
pub fat_count: u8,
pub files_in_root: u16,
pub total_sectors_16: u16,
pub media_descriptor: u8,
pub fat_size_16: u16,
pub _spt: u16,
pub _heads: u16,
pub _hidden_count: u32,
pub total_sectors_32: u32,
}
impl BootSectInfo {
fn read(src: &mut &[u8]) -> BootSectInfo {
BootSectInfo {
_jump: read_arr(src),
oem_name: read_arr(src),
bps: read_u16(src),
spc: read_u8(src),
reserved_sect_count: read_u16(src),
fat_count: read_u8(src),
files_in_root: read_u16(src),
total_sectors_16: read_u16(src),
media_descriptor: read_u8(src),
fat_size_16: read_u16(src),
_spt: read_u16(src),
_heads: read_u16(src),
_hidden_count: read_u32(src),
total_sectors_32: read_u32(src),
}
}
}
pub struct BootSect16
{
common: BootSectInfo,
info: BootSect16Info,
}
pub struct BootSect16Info
{
pub drive_num: u8,
_rsvd: u8,
pub boot_sig: u8,
pub vol_id: u32,
pub label: [u8; 11],
pub fs_type: [u8; 8],
}
impl BootSect16Info {
fn read(src: &mut &[u8]) -> BootSect16Info {
BootSect16Info {
drive_num: read_u8(src),
_rsvd: read_u8(src),
boot_sig: read_u8(src),
vol_id: read_u32(src),
label: read_arr(src),
fs_type: read_arr(src),
}
}
}
pub struct BootSect32
{
common: BootSectInfo,
info32: BootSect32Info,
info16: BootSect16Info,
}
pub struct BootSect32Info
{
pub fat_size_32: u32,
pub ext_flags: u16,
pub fs_ver: u16,
pub root_cluster: u32,
pub fs_info: u16,
pub backup_bootsect: u16,
_resvd: [u8; 12],
}
impl BootSect32Info {
fn read(src: &mut &[u8]) -> BootSect32Info {
BootSect32Info {
fat_size_32: read_u32(src),
ext_flags: read_u16(src),
fs_ver: read_u16(src),
root_cluster: read_u32(src),
fs_info: read_u16(src),
backup_bootsect: read_u16(src),
_resvd: read_arr(src),
}
}
}
#[derive(Debug)]
pub struct DirEnt
{
pub name: [u8; 11],
pub attribs: u8,
pub lcase: u8,
pub creation_ds: u8, // 10ths of a second
pub creation_time: u16,
pub creation_date: u16,
pub accessed_date: u16,
pub cluster_hi: u16,
pub modified_time: u16,
pub modified_date: u16,
pub cluster: u16,
pub size: u32,
}
impl DirEnt {
pub fn read(src: &mut &[u8]) -> DirEnt {
DirEnt {
name: read_arr(src),
attribs: read_u8(src),
lcase: read_u8(src),
creation_ds: read_u8(src),
creation_time: read_u16(src),
creation_date: read_u16(src),
accessed_date: read_u16(src),
cluster_hi: read_u16(src),
modified_time: read_u16(src),
modified_date: read_u16(src),
cluster: read_u16(src),
size: read_u32(src),
}
}
}
#[derive(Debug)]
pub struct DirEntLong
{
pub id: u8,
pub name1: [u16; 5],
pub attrib: u8, // Must be ATTR_LFN
pub ty: u8, // Dunno?
pub checksum: u8,
pub name2: [u16; 6],
pub first_cluster: u16,
pub name3: [u16; 2],
}
impl DirEntLong {
pub fn read(src: &mut &[u8]) -> DirEntLong {
DirEntLong {
id: read_u8(src),
name1: read_arr16(src),
attrib: read_u8(src),
ty: read_u8(src),
checksum: read_u8(src),
name2: read_arr16(src),
first_cluster: read_u16(src),
name3: read_arr16(src),
}
}
}
|
//! Cranelift shared settings.
//!
//! This module defines settings relevant for all code generators.
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Backup data register (BKP_DR)"]
pub dr: [DR; 10],
#[doc = "0x28 - RTC clock calibration register (BKP_RTCCR)"]
pub rtccr: RTCCR,
#[doc = "0x2c - Backup control register (BKP_CR)"]
pub cr: CR,
#[doc = "0x30 - BKP_CSR control/status register (BKP_CSR)"]
pub csr: CSR,
_reserved4: [u8; 8usize],
#[doc = "0x3c - Backup data register (BKP_DR)"]
pub bkp_dr: [BKP_DR; 32],
}
#[doc = "Backup data register (BKP_DR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dr](dr) module"]
pub type DR = crate::Reg<u32, _DR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DR;
#[doc = "`read()` method returns [dr::R](dr::R) reader structure"]
impl crate::Readable for DR {}
#[doc = "`write(|w| ..)` method takes [dr::W](dr::W) writer structure"]
impl crate::Writable for DR {}
#[doc = "Backup data register (BKP_DR)"]
pub mod dr;
#[doc = "Backup data register (BKP_DR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [bkp_dr](bkp_dr) module"]
pub type BKP_DR = crate::Reg<u32, _BKP_DR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BKP_DR;
#[doc = "`read()` method returns [bkp_dr::R](bkp_dr::R) reader structure"]
impl crate::Readable for BKP_DR {}
#[doc = "`write(|w| ..)` method takes [bkp_dr::W](bkp_dr::W) writer structure"]
impl crate::Writable for BKP_DR {}
#[doc = "Backup data register (BKP_DR)"]
pub mod bkp_dr;
#[doc = "RTC clock calibration register (BKP_RTCCR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtccr](rtccr) module"]
pub type RTCCR = crate::Reg<u32, _RTCCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RTCCR;
#[doc = "`read()` method returns [rtccr::R](rtccr::R) reader structure"]
impl crate::Readable for RTCCR {}
#[doc = "`write(|w| ..)` method takes [rtccr::W](rtccr::W) writer structure"]
impl crate::Writable for RTCCR {}
#[doc = "RTC clock calibration register (BKP_RTCCR)"]
pub mod rtccr;
#[doc = "Backup control register (BKP_CR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"]
pub type CR = crate::Reg<u32, _CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CR;
#[doc = "`read()` method returns [cr::R](cr::R) reader structure"]
impl crate::Readable for CR {}
#[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"]
impl crate::Writable for CR {}
#[doc = "Backup control register (BKP_CR)"]
pub mod cr;
#[doc = "BKP_CSR control/status register (BKP_CSR)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [csr](csr) module"]
pub type CSR = crate::Reg<u32, _CSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CSR;
#[doc = "`read()` method returns [csr::R](csr::R) reader structure"]
impl crate::Readable for CSR {}
#[doc = "`write(|w| ..)` method takes [csr::W](csr::W) writer structure"]
impl crate::Writable for CSR {}
#[doc = "BKP_CSR control/status register (BKP_CSR)"]
pub mod csr;
|
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use crate::{MetricKind, MetricObserver, Observation};
/// A `CumulativeGauge` reports the total of the values reported by `CumulativeRecorder`
///
/// Unlike `U64Gauge` this means it is safe to use in multiple locations with the same
/// set of `Attributes`. The value reported will be the sum of all `CumulativeRecorder`.
///
/// Any contributions made by a `CumulativeRecorder` to the total reported by the
/// `CumulativeGauge` are lost when the `CumulativeRecorder` is dropped
///
/// The primary use-case for CumulativeGauge is reporting observations at a lower
/// granularity than the instrumented objects. For example, we might want
/// to instrument individual Chunks but report the total across all Chunks
/// in a partition or table.
#[derive(Debug, Default, Clone)]
pub struct CumulativeGauge {
state: Arc<AtomicU64>,
}
impl CumulativeGauge {
pub fn fetch(&self) -> u64 {
self.state.load(Ordering::Relaxed)
}
}
impl MetricObserver for CumulativeGauge {
type Recorder = CumulativeRecorder;
fn kind() -> MetricKind {
MetricKind::U64Gauge
}
fn recorder(&self) -> Self::Recorder {
CumulativeRecorder {
local: 0,
state: Arc::clone(&self.state),
}
}
fn observe(&self) -> Observation {
Observation::U64Gauge(self.fetch())
}
}
#[derive(Debug)]
pub struct CumulativeRecorder {
local: u64,
state: Arc<AtomicU64>,
}
impl CumulativeRecorder {
/// Gets a new unregistered recorder
pub fn new_unregistered() -> Self {
Self {
local: 0,
state: Default::default(),
}
}
/// Gets the CumulativeGauge this CumulativeRecorder is associated with
pub fn reporter(&self) -> CumulativeGauge {
CumulativeGauge {
state: Arc::clone(&self.state),
}
}
/// Gets the local contribution from this instance
pub fn get_local(&self) -> u64 {
self.local
}
/// Increment the local value for this CumulativeRecorder
pub fn inc(&mut self, delta: u64) {
self.local += delta;
self.state.fetch_add(delta, Ordering::Relaxed);
}
/// Decrement the local value for this CumulativeRecorder
pub fn decr(&mut self, delta: u64) {
self.local -= delta;
self.state.fetch_sub(delta, Ordering::Relaxed);
}
/// Sets the local value for this CumulativeRecorder
pub fn set(&mut self, new: u64) {
match new.cmp(&self.local) {
std::cmp::Ordering::Less => self.decr(self.local - new),
std::cmp::Ordering::Equal => {}
std::cmp::Ordering::Greater => self.inc(new - self.local),
}
}
}
impl Drop for CumulativeRecorder {
fn drop(&mut self) {
self.state.fetch_sub(self.local, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gauge() {
let gauge = CumulativeGauge::default();
let mut r1 = gauge.recorder();
assert_eq!(gauge.observe(), Observation::U64Gauge(0));
r1.set(23);
assert_eq!(gauge.observe(), Observation::U64Gauge(23));
let mut r2 = gauge.recorder();
assert_eq!(gauge.observe(), Observation::U64Gauge(23));
r2.set(34);
assert_eq!(gauge.observe(), Observation::U64Gauge(57));
std::mem::drop(r2);
assert_eq!(gauge.observe(), Observation::U64Gauge(23));
let mut r3 = gauge.recorder();
r3.set(7);
assert_eq!(gauge.observe(), Observation::U64Gauge(30));
r1.set(53);
assert_eq!(gauge.observe(), Observation::U64Gauge(60));
std::mem::drop(r1);
assert_eq!(gauge.observe(), Observation::U64Gauge(7));
std::mem::drop(r3);
assert_eq!(gauge.observe(), Observation::U64Gauge(0));
// Test overflow behaviour
let mut r1 = gauge.recorder();
let mut r2 = gauge.recorder();
r1.set(u64::MAX);
assert_eq!(gauge.observe(), Observation::U64Gauge(u64::MAX));
r2.set(34);
assert_eq!(gauge.observe(), Observation::U64Gauge(33));
std::mem::drop(r1);
assert_eq!(gauge.observe(), Observation::U64Gauge(34));
std::mem::drop(r2);
assert_eq!(gauge.observe(), Observation::U64Gauge(0));
}
}
|
use domain_patterns::collections::Repository;
use crate::errors::Error::{ResourceNotFound, NotAuthorized, RepoFailure, ConcurrencyFailure};
use crate::errors::Result;
use domain_patterns::command::Handles;
use crate::survey::Survey;
use crate::app_services::commands::{CreateSurveyCommand, UpdateSurveyCommand, SurveyCommands, RemoveSurveyCommand};
pub struct SurveyCommandsHandler<T> where
T: Repository<Survey>
{
repo: T,
}
impl<T> SurveyCommandsHandler<T> where
T: Repository<Survey>
{
pub fn new(repo: T) -> SurveyCommandsHandler<T> {
SurveyCommandsHandler {
repo,
}
}
}
impl<T: Repository<Survey>> Handles<CreateSurveyCommand> for SurveyCommandsHandler<T> {
type Result = Result<String>;
fn handle(&mut self, msg: CreateSurveyCommand) -> Result<String> {
let new_survey = Survey::new(&msg)?;
let s_id = self.repo.insert(&new_survey)
.map_err(|e| RepoFailure { source: Box::new(e) })?;
// Safe to unwrap. If we had a duplicate key error, that's a database error and would
// be returned above in the map err
Ok(s_id.unwrap())
}
}
impl<T: Repository<Survey>> Handles<UpdateSurveyCommand> for SurveyCommandsHandler<T> {
type Result = Result<String>;
fn handle(&mut self, msg: UpdateSurveyCommand) -> Result<String> {
let mut survey = self.repo.get(&msg.id)
.map_err(|e| RepoFailure { source: Box::new(e) })?
.ok_or(ResourceNotFound { resource: format!("survey with id {}", &msg.id) })?;
if !survey.belongs_to(&msg.author) {
return Err(NotAuthorized.into());
}
survey.try_update(msg)?;
let s_id = self.repo.update(&survey)
.map_err(|e| RepoFailure { source: Box::new(e) })?;
if let Some(s) = s_id {
return Ok(s);
}
// If we got here then repo.update returned None. This would only happen if there was no valid
// survey to update, which could only have happened if the survey was deleted between the time
// that we retrieved it with repo.get, and updated it with repo.update. Any other database errors
// would have been returned inside the mapped RepoFailure error on the update.
Err(ConcurrencyFailure)
}
}
impl<T> Handles<RemoveSurveyCommand> for SurveyCommandsHandler<T>
where T: Repository<Survey>
{
type Result = Result<String>;
fn handle(&mut self, msg: RemoveSurveyCommand) -> Self::Result {
let survey = self.repo.get(&msg.id)
.map_err(|e| RepoFailure { source: Box::new(e) })?
.ok_or(ResourceNotFound { resource: format!("survey with id {}", &msg.id) })?;
if !survey.belongs_to(&msg.requesting_author) {
return Err(NotAuthorized.into());
}
let s_id = self.repo.remove(&msg.id)
.map_err(|e| RepoFailure { source: Box::new(e) })?;
Ok(s_id.unwrap())
}
}
impl<T: Repository<Survey>> Handles<SurveyCommands> for SurveyCommandsHandler<T> {
type Result = Result<String>;
fn handle(&mut self, msg: SurveyCommands) -> Result<String> {
match msg {
SurveyCommands::CreateSurveyCommand(cmd) => self.handle(cmd),
SurveyCommands::UpdateSurveyCommand(cmd) => self.handle(cmd),
SurveyCommands::RemoveSurveyCommand(cmd) => self.handle(cmd),
}
}
}
|
use druid::piet::Color;
use druid::widget::{Button, Flex, Painter};
use druid::Data;
use druid::RenderContext;
use druid::{AppLauncher, PlatformError, Widget, WidgetExt, WindowDesc};
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
mod traverse;
const DEFAULT_HEIGHT: i32 = 9;
const DEFAULT_WIDTH: i32 = 10;
const DEFAULT_START_X: i32 = 1;
const DEFAULT_START_Y: i32 = 5;
const DEFAULT_END_X: i32 = 8;
const DEFAULT_END_Y: i32 = 5;
#[derive(Clone)]
enum ButtonState {
NewGame,
Obstacle,
Start,
}
#[derive(Clone, PartialEq, Debug)]
pub enum SquareKind {
Init,
Obstacle,
PossiblePath,
SolutionPath,
StartSquare,
EndSquare,
}
#[derive(Clone, Debug)]
pub struct Node {
x: i32,
y: i32,
parent: Option<Rc<Node>>,
}
impl Node {
pub fn new(x: i32, y: i32) -> Node {
Node {
x: x,
y: y,
parent: None,
}
}
pub fn add(&self, child_node: &mut Node) {
child_node.parent = Some(Rc::new(self.clone()));
}
pub fn find_reverse_path(&self) -> Vec<(i32, i32)> {
let mut result: Vec<(i32, i32)> = vec![];
let mut current_node = &Rc::new(self.clone());
while !current_node.parent.is_none() {
result.push((current_node.x, current_node.y));
current_node = current_node.parent.as_ref().unwrap();
}
result
}
}
#[derive(Clone, Debug)]
// (x, y, previous position)
struct Move(i32, i32, Node);
trait Metadata {
fn new() -> Self;
fn gen_board(&self, height: i32, width: i32) -> Flex<State>;
fn init_state(height: i32, width: i32) -> Arc<Vec<Vec<SquareKind>>>;
fn clear(&mut self);
// traversal methods
fn is_valid_move(&self, x: i32, y: i32) -> bool;
fn get_possible_moves(&self, parent: Node) -> Vec<Move>;
fn traverse(&mut self) -> Vec<(i32, i32)>;
}
#[derive(Clone, Data)]
struct State {
button_state: Arc<ButtonState>,
width: i32,
height: i32,
solved: bool,
state: Arc<Vec<Vec<SquareKind>>>,
}
impl Metadata for State {
fn init_state(height: i32, width: i32) -> Arc<Vec<Vec<SquareKind>>> {
let mut state: Vec<Vec<SquareKind>> = vec![vec![]];
for column in 0..height {
state.push(vec![]);
for row in 0..width {
let mut square_type = SquareKind::Init;
if column == DEFAULT_START_Y && row == DEFAULT_START_X {
square_type = SquareKind::StartSquare;
} else if column == DEFAULT_END_Y && row == DEFAULT_END_X {
square_type = SquareKind::EndSquare;
}
state[column as usize].push(square_type)
}
}
Arc::new(state)
}
fn gen_board(&self, height: i32, width: i32) -> Flex<State> {
let mut board = Flex::column();
for y in 0..height {
board = board.with_flex_child(gen_square_row(y, width), 1.0);
}
board
}
fn clear(&mut self) {
self.button_state = Arc::new(ButtonState::NewGame);
self.state = State::init_state(self.height, self.width);
}
fn new() -> Self {
State {
button_state: Arc::new(ButtonState::NewGame),
height: DEFAULT_HEIGHT,
width: DEFAULT_WIDTH,
solved: false,
state: Self::init_state(DEFAULT_HEIGHT, DEFAULT_WIDTH),
}
}
fn is_valid_move(&self, x: i32, y: i32) -> bool {
// check if move is out of bounds
if y < 0 || y >= self.height || x < 0 || x >= self.width {
return false;
}
// check if move is on an obstacle, or the start square,
// allow all other kinds.
let square_kind = &self.state[y as usize][x as usize];
return match square_kind {
SquareKind::Obstacle => false,
SquareKind::StartSquare => false,
SquareKind::Init => true,
SquareKind::SolutionPath => true,
SquareKind::PossiblePath => true,
SquareKind::EndSquare => true,
};
}
fn get_possible_moves(&self, parent: Node) -> Vec<Move> {
let cur_x = parent.x;
let cur_y = parent.y;
let mut result: Vec<Move> = vec![];
let mut all_moves = vec![
Move(cur_x + 1, cur_y, parent.clone()),
Move(cur_x - 1, cur_y, parent.clone()),
Move(cur_x, cur_y - 1, parent.clone()),
Move(cur_x, cur_y + 1, parent.clone()),
];
all_moves.reverse();
for m in all_moves {
if self.is_valid_move(m.0, m.1) {
result.push(m)
}
}
result
}
fn traverse(&mut self) -> Vec<(i32, i32)> {
let mut visited = HashMap::new();
let mut stack: Vec<Move> =
self.get_possible_moves(Node::new(DEFAULT_START_X, DEFAULT_START_Y));
while stack.len() > 0 {
let m = stack.pop().unwrap();
let (cur_x, cur_y) = (m.0, m.1);
let parent = &m.2.clone();
let mut child = Node::new(cur_x, cur_y);
parent.add(&mut child);
if self.state[cur_y as usize][cur_x as usize] == SquareKind::EndSquare {
self.solved = true;
for square in parent.find_reverse_path() {
let (x, y) = square;
Arc::make_mut(&mut self.state)[y as usize][x as usize] =
SquareKind::SolutionPath;
}
return parent.find_reverse_path();
}
let value = format!("{},{}", cur_x, cur_y);
if *visited.get(&value).unwrap_or(&false) {
continue;
}
visited.insert(value, true);
Arc::make_mut(&mut self.state)[cur_y as usize][cur_x as usize] =
SquareKind::PossiblePath;
for m in self.get_possible_moves(child) {
stack.push(m)
}
}
vec![]
}
}
fn square(y: i32, x: i32) -> impl Widget<State> {
Painter::new(move |ctx, data: &State, _| {
let bounds = ctx.size().to_rect();
let color = match data.state[y as usize][x as usize] {
SquareKind::Init => &Color::WHITE,
SquareKind::Obstacle => &Color::BLACK,
SquareKind::PossiblePath => &Color::WHITE,
SquareKind::SolutionPath => &Color::YELLOW,
SquareKind::StartSquare => &Color::GREEN,
SquareKind::EndSquare => &Color::PURPLE,
};
ctx.fill(bounds, color);
ctx.stroke(bounds.inset(-0.5), &Color::BLACK, 1.0);
})
.on_click(move |_ctx, data: &mut State, _env| {
Arc::make_mut(&mut data.state)[y as usize][x as usize] = match *data.button_state {
ButtonState::Obstacle => SquareKind::Obstacle,
ButtonState::NewGame => SquareKind::Init,
ButtonState::Start => SquareKind::Init,
};
})
}
fn gen_square_row(y: i32, width: i32) -> impl Widget<State> {
let mut row = Flex::row();
for x in 0..width {
row = row.with_flex_child(square(y, x), 1.0);
}
row
}
fn main() -> Result<(), PlatformError> {
let data = State::new();
let main_window = WindowDesc::new(ui_builder(&data));
AppLauncher::with_window(main_window)
.log_to_console()
.launch(data)
}
fn ui_builder(data: &State) -> impl Widget<State> {
let start_button = Button::new("start")
.on_click(|_ctx, data: &mut State, _env| {
*Arc::make_mut(&mut data.button_state) = ButtonState::Start;
data.traverse();
})
.padding(5.0);
let obstacle_button = Button::new("add obstacles")
.on_click(|_ctx, data: &mut State, _env| {
*Arc::make_mut(&mut data.button_state) = ButtonState::Obstacle;
})
.padding(5.0);
let new_game_button = Button::new("new game")
.on_click(|_ctx, data: &mut State, _env| data.clear())
.padding(5.0);
data.gen_board(DEFAULT_HEIGHT, DEFAULT_WIDTH)
.with_flex_spacer(2.0)
.with_child(start_button)
.with_child(obstacle_button)
.with_child(new_game_button)
}
|
use bevy::{prelude::Mesh, render::mesh::VertexAttribute, render::pipeline::PrimitiveTopology};
pub struct Skybox {
pub size: f32,
}
impl Default for Skybox {
fn default() -> Self {
Skybox { size: 1.0 }
}
}
// impl Skybox {
impl From<Skybox> for Mesh {
fn from(cube: Skybox) -> Mesh {
let size = cube.size;
let vertices = &[
// top (0., 0., size)
([-size, -size, size], [0., 0., size], [0., 0.]),
([size, -size, size], [0., 0., size], [size, 0.]),
([size, size, size], [0., 0., size], [size, size]),
([-size, size, size], [0., 0., size], [0., size]),
// bottom (0., 0., -size)
([-size, size, -size], [0., 0., -size], [size, 0.]),
([size, size, -size], [0., 0., -size], [0., 0.]),
([size, -size, -size], [0., 0., -size], [0., size]),
([-size, -size, -size], [0., 0., -size], [size, size]),
// right (size, 0., 0.)
([size, -size, -size], [size, 0., 0.], [0., 0.]),
([size, size, -size], [size, 0., 0.], [size, 0.]),
([size, size, size], [size, 0., 0.], [size, size]),
([size, -size, size], [size, 0., 0.], [0., size]),
// left (-size, 0., 0.)
([-size, -size, size], [-size, 0., 0.], [size, 0.]),
([-size, size, size], [-size, 0., 0.], [0., 0.]),
([-size, size, -size], [-size, 0., 0.], [0., size]),
([-size, -size, -size], [-size, 0., 0.], [size, size]),
// front (0., size, 0.)
([size, size, -size], [0., size, 0.], [size, 0.]),
([-size, size, -size], [0., size, 0.], [0., 0.]),
([-size, size, size], [0., size, 0.], [0., size]),
([size, size, size], [0., size, 0.], [size, size]),
// back (0., -size, 0.)
([size, -size, size], [0., -size, 0.], [0., 0.]),
([-size, -size, size], [0., -size, 0.], [size, 0.]),
([-size, -size, -size], [0., -size, 0.], [size, size]),
([size, -size, -size], [0., -size, 0.], [0., size]),
];
let mut positions = Vec::new();
let mut normals = Vec::new();
let mut uvs = Vec::new();
for (position, normal, uv) in vertices.iter() {
positions.push(*position);
normals.push(*normal);
uvs.push(*uv);
}
let indices = vec![
3, 2, 1, 1, 0, 3, // top
7, 6, 5, 5, 4, 7, // bottom
11, 10, 9, 9, 8, 11, // right
15, 14, 13, 13, 12, 15, // left
19, 18, 17, 17, 16, 19, // front
23, 22, 21, 21, 20, 23, // back
];
Mesh {
primitive_topology: PrimitiveTopology::TriangleList,
attributes: vec![
VertexAttribute::position(positions),
VertexAttribute::normal(normals),
VertexAttribute::uv(uvs),
],
indices: Some(indices),
}
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheCheckManifest(pwszmasterurl: super::super::Foundation::PWSTR, pwszmanifesturl: super::super::Foundation::PWSTR, pbmanifestdata: *const u8, dwmanifestdatasize: u32, pbmanifestresponseheaders: *const u8, dwmanifestresponseheaderssize: u32, pestate: *mut APP_CACHE_STATE, phnewappcache: *mut *mut ::core::ffi::c_void) -> u32;
pub fn AppCacheCloseHandle(happcache: *const ::core::ffi::c_void);
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheCreateAndCommitFile(happcache: *const ::core::ffi::c_void, pwszsourcefilepath: super::super::Foundation::PWSTR, pwszurl: super::super::Foundation::PWSTR, pbresponseheaders: *const u8, dwresponseheaderssize: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheDeleteGroup(pwszmanifesturl: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheDeleteIEGroup(pwszmanifesturl: super::super::Foundation::PWSTR) -> u32;
pub fn AppCacheDuplicateHandle(happcache: *const ::core::ffi::c_void, phduplicatedappcache: *mut *mut ::core::ffi::c_void) -> u32;
pub fn AppCacheFinalize(happcache: *const ::core::ffi::c_void, pbmanifestdata: *const u8, dwmanifestdatasize: u32, pestate: *mut APP_CACHE_FINALIZE_STATE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheFreeDownloadList(pdownloadlist: *mut APP_CACHE_DOWNLOAD_LIST);
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheFreeGroupList(pappcachegrouplist: *mut APP_CACHE_GROUP_LIST);
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheFreeIESpace(ftcutoff: super::super::Foundation::FILETIME) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheFreeSpace(ftcutoff: super::super::Foundation::FILETIME) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheGetDownloadList(happcache: *const ::core::ffi::c_void, pdownloadlist: *mut APP_CACHE_DOWNLOAD_LIST) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheGetFallbackUrl(happcache: *const ::core::ffi::c_void, pwszurl: super::super::Foundation::PWSTR, ppwszfallbackurl: *mut super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheGetGroupList(pappcachegrouplist: *mut APP_CACHE_GROUP_LIST) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheGetIEGroupList(pappcachegrouplist: *mut APP_CACHE_GROUP_LIST) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheGetInfo(happcache: *const ::core::ffi::c_void, pappcacheinfo: *mut APP_CACHE_GROUP_INFO) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheGetManifestUrl(happcache: *const ::core::ffi::c_void, ppwszmanifesturl: *mut super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn AppCacheLookup(pwszurl: super::super::Foundation::PWSTR, dwflags: u32, phappcache: *mut *mut ::core::ffi::c_void) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn CommitUrlCacheEntryA(lpszurlname: super::super::Foundation::PSTR, lpszlocalfilename: super::super::Foundation::PSTR, expiretime: super::super::Foundation::FILETIME, lastmodifiedtime: super::super::Foundation::FILETIME, cacheentrytype: u32, lpheaderinfo: *const u8, cchheaderinfo: u32, lpszfileextension: super::super::Foundation::PSTR, lpszoriginalurl: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CommitUrlCacheEntryBinaryBlob(pwszurlname: super::super::Foundation::PWSTR, dwtype: u32, ftexpiretime: super::super::Foundation::FILETIME, ftmodifiedtime: super::super::Foundation::FILETIME, pbblob: *const u8, cbblob: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn CommitUrlCacheEntryW(lpszurlname: super::super::Foundation::PWSTR, lpszlocalfilename: super::super::Foundation::PWSTR, expiretime: super::super::Foundation::FILETIME, lastmodifiedtime: super::super::Foundation::FILETIME, cacheentrytype: u32, lpszheaderinfo: super::super::Foundation::PWSTR, cchheaderinfo: u32, lpszfileextension: super::super::Foundation::PWSTR, lpszoriginalurl: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateMD5SSOHash(pszchallengeinfo: super::super::Foundation::PWSTR, pwszrealm: super::super::Foundation::PWSTR, pwsztarget: super::super::Foundation::PWSTR, pbhexhash: *mut u8) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateUrlCacheContainerA(name: super::super::Foundation::PSTR, lpcacheprefix: super::super::Foundation::PSTR, lpszcachepath: super::super::Foundation::PSTR, kbcachelimit: u32, dwcontainertype: u32, dwoptions: u32, pvbuffer: *mut ::core::ffi::c_void, cbbuffer: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateUrlCacheContainerW(name: super::super::Foundation::PWSTR, lpcacheprefix: super::super::Foundation::PWSTR, lpszcachepath: super::super::Foundation::PWSTR, kbcachelimit: u32, dwcontainertype: u32, dwoptions: u32, pvbuffer: *mut ::core::ffi::c_void, cbbuffer: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateUrlCacheEntryA(lpszurlname: super::super::Foundation::PSTR, dwexpectedfilesize: u32, lpszfileextension: super::super::Foundation::PSTR, lpszfilename: super::super::Foundation::PSTR, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateUrlCacheEntryExW(lpszurlname: super::super::Foundation::PWSTR, dwexpectedfilesize: u32, lpszfileextension: super::super::Foundation::PWSTR, lpszfilename: super::super::Foundation::PWSTR, dwreserved: u32, fpreserveincomingfilename: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn CreateUrlCacheEntryW(lpszurlname: super::super::Foundation::PWSTR, dwexpectedfilesize: u32, lpszfileextension: super::super::Foundation::PWSTR, lpszfilename: super::super::Foundation::PWSTR, dwreserved: u32) -> super::super::Foundation::BOOL;
pub fn CreateUrlCacheGroup(dwflags: u32, lpreserved: *mut ::core::ffi::c_void) -> i64;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteIE3Cache(hwnd: super::super::Foundation::HWND, hinst: super::super::Foundation::HINSTANCE, lpszcmd: super::super::Foundation::PSTR, ncmdshow: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteUrlCacheContainerA(name: super::super::Foundation::PSTR, dwoptions: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteUrlCacheContainerW(name: super::super::Foundation::PWSTR, dwoptions: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteUrlCacheEntry(lpszurlname: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteUrlCacheEntryA(lpszurlname: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteUrlCacheEntryW(lpszurlname: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteUrlCacheGroup(groupid: i64, dwflags: u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DeleteWpadCacheForNetworks(param0: WPAD_CACHE_DELETE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DetectAutoProxyUrl(pszautoproxyurl: super::super::Foundation::PSTR, cchautoproxyurl: u32, dwdetectflags: PROXY_AUTO_DETECT_TYPE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn DoConnectoidsExist() -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ExportCookieFileA(szfilename: super::super::Foundation::PSTR, fappend: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ExportCookieFileW(szfilename: super::super::Foundation::PWSTR, fappend: super::super::Foundation::BOOL) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindCloseUrlCache(henumhandle: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindFirstUrlCacheContainerA(pdwmodified: *mut u32, lpcontainerinfo: *mut INTERNET_CACHE_CONTAINER_INFOA, lpcbcontainerinfo: *mut u32, dwoptions: u32) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn FindFirstUrlCacheContainerW(pdwmodified: *mut u32, lpcontainerinfo: *mut INTERNET_CACHE_CONTAINER_INFOW, lpcbcontainerinfo: *mut u32, dwoptions: u32) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn FindFirstUrlCacheEntryA(lpszurlsearchpattern: super::super::Foundation::PSTR, lpfirstcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn FindFirstUrlCacheEntryExA(lpszurlsearchpattern: super::super::Foundation::PSTR, dwflags: u32, dwfilter: u32, groupid: i64, lpfirstcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32, lpgroupattributes: *mut ::core::ffi::c_void, lpcbgroupattributes: *mut u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn FindFirstUrlCacheEntryExW(lpszurlsearchpattern: super::super::Foundation::PWSTR, dwflags: u32, dwfilter: u32, groupid: i64, lpfirstcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32, lpgroupattributes: *mut ::core::ffi::c_void, lpcbgroupattributes: *mut u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn FindFirstUrlCacheEntryW(lpszurlsearchpattern: super::super::Foundation::PWSTR, lpfirstcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn FindFirstUrlCacheGroup(dwflags: u32, dwfilter: u32, lpsearchcondition: *mut ::core::ffi::c_void, dwsearchcondition: u32, lpgroupid: *mut i64, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn FindNextUrlCacheContainerA(henumhandle: super::super::Foundation::HANDLE, lpcontainerinfo: *mut INTERNET_CACHE_CONTAINER_INFOA, lpcbcontainerinfo: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindNextUrlCacheContainerW(henumhandle: super::super::Foundation::HANDLE, lpcontainerinfo: *mut INTERNET_CACHE_CONTAINER_INFOW, lpcbcontainerinfo: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindNextUrlCacheEntryA(henumhandle: super::super::Foundation::HANDLE, lpnextcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindNextUrlCacheEntryExA(henumhandle: super::super::Foundation::HANDLE, lpnextcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32, lpgroupattributes: *mut ::core::ffi::c_void, lpcbgroupattributes: *mut u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindNextUrlCacheEntryExW(henumhandle: super::super::Foundation::HANDLE, lpnextcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32, lpgroupattributes: *mut ::core::ffi::c_void, lpcbgroupattributes: *mut u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindNextUrlCacheEntryW(henumhandle: super::super::Foundation::HANDLE, lpnextcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindNextUrlCacheGroup(hfind: super::super::Foundation::HANDLE, lpgroupid: *mut i64, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FindP3PPolicySymbol(pszsymbol: super::super::Foundation::PSTR) -> i32;
#[cfg(feature = "Win32_Foundation")]
pub fn FreeUrlCacheSpaceA(lpszcachepath: super::super::Foundation::PSTR, dwsize: u32, dwfilter: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FreeUrlCacheSpaceW(lpszcachepath: super::super::Foundation::PWSTR, dwsize: u32, dwfilter: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpCommandA(hconnect: *const ::core::ffi::c_void, fexpectresponse: super::super::Foundation::BOOL, dwflags: FTP_FLAGS, lpszcommand: super::super::Foundation::PSTR, dwcontext: usize, phftpcommand: *mut *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpCommandW(hconnect: *const ::core::ffi::c_void, fexpectresponse: super::super::Foundation::BOOL, dwflags: FTP_FLAGS, lpszcommand: super::super::Foundation::PWSTR, dwcontext: usize, phftpcommand: *mut *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpCreateDirectoryA(hconnect: *const ::core::ffi::c_void, lpszdirectory: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpCreateDirectoryW(hconnect: *const ::core::ffi::c_void, lpszdirectory: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpDeleteFileA(hconnect: *const ::core::ffi::c_void, lpszfilename: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpDeleteFileW(hconnect: *const ::core::ffi::c_void, lpszfilename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_FileSystem"))]
pub fn FtpFindFirstFileA(hconnect: *const ::core::ffi::c_void, lpszsearchfile: super::super::Foundation::PSTR, lpfindfiledata: *mut super::super::Storage::FileSystem::WIN32_FIND_DATAA, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Storage_FileSystem"))]
pub fn FtpFindFirstFileW(hconnect: *const ::core::ffi::c_void, lpszsearchfile: super::super::Foundation::PWSTR, lpfindfiledata: *mut super::super::Storage::FileSystem::WIN32_FIND_DATAW, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpGetCurrentDirectoryA(hconnect: *const ::core::ffi::c_void, lpszcurrentdirectory: super::super::Foundation::PSTR, lpdwcurrentdirectory: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpGetCurrentDirectoryW(hconnect: *const ::core::ffi::c_void, lpszcurrentdirectory: super::super::Foundation::PWSTR, lpdwcurrentdirectory: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpGetFileA(hconnect: *const ::core::ffi::c_void, lpszremotefile: super::super::Foundation::PSTR, lpsznewfile: super::super::Foundation::PSTR, ffailifexists: super::super::Foundation::BOOL, dwflagsandattributes: u32, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpGetFileEx(hftpsession: *const ::core::ffi::c_void, lpszremotefile: super::super::Foundation::PSTR, lpsznewfile: super::super::Foundation::PWSTR, ffailifexists: super::super::Foundation::BOOL, dwflagsandattributes: u32, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
pub fn FtpGetFileSize(hfile: *const ::core::ffi::c_void, lpdwfilesizehigh: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpGetFileW(hconnect: *const ::core::ffi::c_void, lpszremotefile: super::super::Foundation::PWSTR, lpsznewfile: super::super::Foundation::PWSTR, ffailifexists: super::super::Foundation::BOOL, dwflagsandattributes: u32, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpOpenFileA(hconnect: *const ::core::ffi::c_void, lpszfilename: super::super::Foundation::PSTR, dwaccess: u32, dwflags: FTP_FLAGS, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpOpenFileW(hconnect: *const ::core::ffi::c_void, lpszfilename: super::super::Foundation::PWSTR, dwaccess: u32, dwflags: FTP_FLAGS, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpPutFileA(hconnect: *const ::core::ffi::c_void, lpszlocalfile: super::super::Foundation::PSTR, lpsznewremotefile: super::super::Foundation::PSTR, dwflags: FTP_FLAGS, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpPutFileEx(hftpsession: *const ::core::ffi::c_void, lpszlocalfile: super::super::Foundation::PWSTR, lpsznewremotefile: super::super::Foundation::PSTR, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpPutFileW(hconnect: *const ::core::ffi::c_void, lpszlocalfile: super::super::Foundation::PWSTR, lpsznewremotefile: super::super::Foundation::PWSTR, dwflags: FTP_FLAGS, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpRemoveDirectoryA(hconnect: *const ::core::ffi::c_void, lpszdirectory: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpRemoveDirectoryW(hconnect: *const ::core::ffi::c_void, lpszdirectory: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpRenameFileA(hconnect: *const ::core::ffi::c_void, lpszexisting: super::super::Foundation::PSTR, lpsznew: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpRenameFileW(hconnect: *const ::core::ffi::c_void, lpszexisting: super::super::Foundation::PWSTR, lpsznew: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpSetCurrentDirectoryA(hconnect: *const ::core::ffi::c_void, lpszdirectory: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn FtpSetCurrentDirectoryW(hconnect: *const ::core::ffi::c_void, lpszdirectory: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetDiskInfoA(pszpath: super::super::Foundation::PSTR, pdwclustersize: *mut u32, pdlavail: *mut u64, pdltotal: *mut u64) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheConfigInfoA(lpcacheconfiginfo: *mut INTERNET_CACHE_CONFIG_INFOA, lpcbcacheconfiginfo: *mut u32, dwfieldcontrol: CACHE_CONFIG) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheConfigInfoW(lpcacheconfiginfo: *mut INTERNET_CACHE_CONFIG_INFOW, lpcbcacheconfiginfo: *mut u32, dwfieldcontrol: CACHE_CONFIG) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheEntryBinaryBlob(pwszurlname: super::super::Foundation::PWSTR, dwtype: *mut u32, pftexpiretime: *mut super::super::Foundation::FILETIME, pftaccesstime: *mut super::super::Foundation::FILETIME, pftmodifiedtime: *mut super::super::Foundation::FILETIME, ppbblob: *mut *mut u8, pcbblob: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheEntryInfoA(lpszurlname: super::super::Foundation::PSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheEntryInfoExA(lpszurl: super::super::Foundation::PSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32, lpszredirecturl: super::super::Foundation::PSTR, lpcbredirecturl: *mut u32, lpreserved: *mut ::core::ffi::c_void, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheEntryInfoExW(lpszurl: super::super::Foundation::PWSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32, lpszredirecturl: super::super::Foundation::PWSTR, lpcbredirecturl: *mut u32, lpreserved: *mut ::core::ffi::c_void, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheEntryInfoW(lpszurlname: super::super::Foundation::PWSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheGroupAttributeA(gid: i64, dwflags: u32, dwattributes: u32, lpgroupinfo: *mut INTERNET_CACHE_GROUP_INFOA, lpcbgroupinfo: *mut u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheGroupAttributeW(gid: i64, dwflags: u32, dwattributes: u32, lpgroupinfo: *mut INTERNET_CACHE_GROUP_INFOW, lpcbgroupinfo: *mut u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GetUrlCacheHeaderData(nidx: u32, lpdwdata: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherCreateLocatorA(lpszhost: super::super::Foundation::PSTR, nserverport: u16, lpszdisplaystring: super::super::Foundation::PSTR, lpszselectorstring: super::super::Foundation::PSTR, dwgophertype: u32, lpszlocator: super::super::Foundation::PSTR, lpdwbufferlength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherCreateLocatorW(lpszhost: super::super::Foundation::PWSTR, nserverport: u16, lpszdisplaystring: super::super::Foundation::PWSTR, lpszselectorstring: super::super::Foundation::PWSTR, dwgophertype: u32, lpszlocator: super::super::Foundation::PWSTR, lpdwbufferlength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherFindFirstFileA(hconnect: *const ::core::ffi::c_void, lpszlocator: super::super::Foundation::PSTR, lpszsearchstring: super::super::Foundation::PSTR, lpfinddata: *mut GOPHER_FIND_DATAA, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherFindFirstFileW(hconnect: *const ::core::ffi::c_void, lpszlocator: super::super::Foundation::PWSTR, lpszsearchstring: super::super::Foundation::PWSTR, lpfinddata: *mut GOPHER_FIND_DATAW, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherGetAttributeA(hconnect: *const ::core::ffi::c_void, lpszlocator: super::super::Foundation::PSTR, lpszattributename: super::super::Foundation::PSTR, lpbuffer: *mut u8, dwbufferlength: u32, lpdwcharactersreturned: *mut u32, lpfnenumerator: GOPHER_ATTRIBUTE_ENUMERATOR, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherGetAttributeW(hconnect: *const ::core::ffi::c_void, lpszlocator: super::super::Foundation::PWSTR, lpszattributename: super::super::Foundation::PWSTR, lpbuffer: *mut u8, dwbufferlength: u32, lpdwcharactersreturned: *mut u32, lpfnenumerator: GOPHER_ATTRIBUTE_ENUMERATOR, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherGetLocatorTypeA(lpszlocator: super::super::Foundation::PSTR, lpdwgophertype: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherGetLocatorTypeW(lpszlocator: super::super::Foundation::PWSTR, lpdwgophertype: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherOpenFileA(hconnect: *const ::core::ffi::c_void, lpszlocator: super::super::Foundation::PSTR, lpszview: super::super::Foundation::PSTR, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn GopherOpenFileW(hconnect: *const ::core::ffi::c_void, lpszlocator: super::super::Foundation::PWSTR, lpszview: super::super::Foundation::PWSTR, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpAddRequestHeadersA(hrequest: *const ::core::ffi::c_void, lpszheaders: super::super::Foundation::PSTR, dwheaderslength: u32, dwmodifiers: HTTP_ADDREQ_FLAG) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpAddRequestHeadersW(hrequest: *const ::core::ffi::c_void, lpszheaders: super::super::Foundation::PWSTR, dwheaderslength: u32, dwmodifiers: HTTP_ADDREQ_FLAG) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpCheckDavComplianceA(lpszurl: super::super::Foundation::PSTR, lpszcompliancetoken: super::super::Foundation::PSTR, lpffound: *mut i32, hwnd: super::super::Foundation::HWND, lpvreserved: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpCheckDavComplianceW(lpszurl: super::super::Foundation::PWSTR, lpszcompliancetoken: super::super::Foundation::PWSTR, lpffound: *mut i32, hwnd: super::super::Foundation::HWND, lpvreserved: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
pub fn HttpCloseDependencyHandle(hdependencyhandle: *const ::core::ffi::c_void);
pub fn HttpDuplicateDependencyHandle(hdependencyhandle: *const ::core::ffi::c_void, phduplicateddependencyhandle: *mut *mut ::core::ffi::c_void) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpEndRequestA(hrequest: *const ::core::ffi::c_void, lpbuffersout: *mut INTERNET_BUFFERSA, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpEndRequestW(hrequest: *const ::core::ffi::c_void, lpbuffersout: *mut INTERNET_BUFFERSW, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpGetServerCredentials(pwszurl: super::super::Foundation::PWSTR, ppwszusername: *mut super::super::Foundation::PWSTR, ppwszpassword: *mut super::super::Foundation::PWSTR) -> u32;
pub fn HttpIndicatePageLoadComplete(hdependencyhandle: *const ::core::ffi::c_void) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpIsHostHstsEnabled(pcwszurl: super::super::Foundation::PWSTR, pfishsts: *mut super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpOpenDependencyHandle(hrequesthandle: *const ::core::ffi::c_void, fbackground: super::super::Foundation::BOOL, phdependencyhandle: *mut *mut ::core::ffi::c_void) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpOpenRequestA(hconnect: *const ::core::ffi::c_void, lpszverb: super::super::Foundation::PSTR, lpszobjectname: super::super::Foundation::PSTR, lpszversion: super::super::Foundation::PSTR, lpszreferrer: super::super::Foundation::PSTR, lplpszaccepttypes: *const super::super::Foundation::PSTR, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpOpenRequestW(hconnect: *const ::core::ffi::c_void, lpszverb: super::super::Foundation::PWSTR, lpszobjectname: super::super::Foundation::PWSTR, lpszversion: super::super::Foundation::PWSTR, lpszreferrer: super::super::Foundation::PWSTR, lplpszaccepttypes: *const super::super::Foundation::PWSTR, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
pub fn HttpPushClose(hwait: HTTP_PUSH_WAIT_HANDLE);
pub fn HttpPushEnable(hrequest: *const ::core::ffi::c_void, ptransportsetting: *const HTTP_PUSH_TRANSPORT_SETTING, phwait: *mut HTTP_PUSH_WAIT_HANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpPushWait(hwait: HTTP_PUSH_WAIT_HANDLE, etype: HTTP_PUSH_WAIT_TYPE, pnotificationstatus: *mut HTTP_PUSH_NOTIFICATION_STATUS) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpQueryInfoA(hrequest: *const ::core::ffi::c_void, dwinfolevel: u32, lpbuffer: *mut ::core::ffi::c_void, lpdwbufferlength: *mut u32, lpdwindex: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpQueryInfoW(hrequest: *const ::core::ffi::c_void, dwinfolevel: u32, lpbuffer: *mut ::core::ffi::c_void, lpdwbufferlength: *mut u32, lpdwindex: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpSendRequestA(hrequest: *const ::core::ffi::c_void, lpszheaders: super::super::Foundation::PSTR, dwheaderslength: u32, lpoptional: *const ::core::ffi::c_void, dwoptionallength: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpSendRequestExA(hrequest: *const ::core::ffi::c_void, lpbuffersin: *const INTERNET_BUFFERSA, lpbuffersout: *mut INTERNET_BUFFERSA, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpSendRequestExW(hrequest: *const ::core::ffi::c_void, lpbuffersin: *const INTERNET_BUFFERSW, lpbuffersout: *mut INTERNET_BUFFERSW, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpSendRequestW(hrequest: *const ::core::ffi::c_void, lpszheaders: super::super::Foundation::PWSTR, dwheaderslength: u32, lpoptional: *const ::core::ffi::c_void, dwoptionallength: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpWebSocketClose(hwebsocket: *const ::core::ffi::c_void, usstatus: u16, pvreason: *const ::core::ffi::c_void, dwreasonlength: u32) -> super::super::Foundation::BOOL;
pub fn HttpWebSocketCompleteUpgrade(hrequest: *const ::core::ffi::c_void, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpWebSocketQueryCloseStatus(hwebsocket: *const ::core::ffi::c_void, pusstatus: *mut u16, pvreason: *mut ::core::ffi::c_void, dwreasonlength: u32, pdwreasonlengthconsumed: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpWebSocketReceive(hwebsocket: *const ::core::ffi::c_void, pvbuffer: *mut ::core::ffi::c_void, dwbufferlength: u32, pdwbytesread: *mut u32, pbuffertype: *mut HTTP_WEB_SOCKET_BUFFER_TYPE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpWebSocketSend(hwebsocket: *const ::core::ffi::c_void, buffertype: HTTP_WEB_SOCKET_BUFFER_TYPE, pvbuffer: *const ::core::ffi::c_void, dwbufferlength: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn HttpWebSocketShutdown(hwebsocket: *const ::core::ffi::c_void, usstatus: u16, pvreason: *const ::core::ffi::c_void, dwreasonlength: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ImportCookieFileA(szfilename: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ImportCookieFileW(szfilename: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IncrementUrlCacheHeaderData(nidx: u32, lpdwdata: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternalInternetGetCookie(lpszurl: super::super::Foundation::PSTR, lpszcookiedata: super::super::Foundation::PSTR, lpdwdatasize: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetAlgIdToStringA(ai: u32, lpstr: super::super::Foundation::PSTR, lpdwstrlength: *mut u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetAlgIdToStringW(ai: u32, lpstr: super::super::Foundation::PWSTR, lpdwstrlength: *mut u32, dwreserved: u32) -> super::super::Foundation::BOOL;
pub fn InternetAttemptConnect(dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetAutodial(dwflags: INTERNET_AUTODIAL, hwndparent: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetAutodialHangup(dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCanonicalizeUrlA(lpszurl: super::super::Foundation::PSTR, lpszbuffer: super::super::Foundation::PSTR, lpdwbufferlength: *mut u32, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCanonicalizeUrlW(lpszurl: super::super::Foundation::PWSTR, lpszbuffer: super::super::Foundation::PWSTR, lpdwbufferlength: *mut u32, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCheckConnectionA(lpszurl: super::super::Foundation::PSTR, dwflags: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCheckConnectionW(lpszurl: super::super::Foundation::PWSTR, dwflags: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetClearAllPerSiteCookieDecisions() -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCloseHandle(hinternet: *const ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCombineUrlA(lpszbaseurl: super::super::Foundation::PSTR, lpszrelativeurl: super::super::Foundation::PSTR, lpszbuffer: super::super::Foundation::PSTR, lpdwbufferlength: *mut u32, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCombineUrlW(lpszbaseurl: super::super::Foundation::PWSTR, lpszrelativeurl: super::super::Foundation::PWSTR, lpszbuffer: super::super::Foundation::PWSTR, lpdwbufferlength: *mut u32, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetConfirmZoneCrossing(hwnd: super::super::Foundation::HWND, szurlprev: super::super::Foundation::PSTR, szurlnew: super::super::Foundation::PSTR, bpost: super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetConfirmZoneCrossingA(hwnd: super::super::Foundation::HWND, szurlprev: super::super::Foundation::PSTR, szurlnew: super::super::Foundation::PSTR, bpost: super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetConfirmZoneCrossingW(hwnd: super::super::Foundation::HWND, szurlprev: super::super::Foundation::PWSTR, szurlnew: super::super::Foundation::PWSTR, bpost: super::super::Foundation::BOOL) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetConnectA(hinternet: *const ::core::ffi::c_void, lpszservername: super::super::Foundation::PSTR, nserverport: u16, lpszusername: super::super::Foundation::PSTR, lpszpassword: super::super::Foundation::PSTR, dwservice: u32, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetConnectW(hinternet: *const ::core::ffi::c_void, lpszservername: super::super::Foundation::PWSTR, nserverport: u16, lpszusername: super::super::Foundation::PWSTR, lpszpassword: super::super::Foundation::PWSTR, dwservice: u32, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetConvertUrlFromWireToWideChar(pcszurl: super::super::Foundation::PSTR, cchurl: u32, pcwszbaseurl: super::super::Foundation::PWSTR, dwcodepagehost: u32, dwcodepagepath: u32, fencodepathextra: super::super::Foundation::BOOL, dwcodepageextra: u32, ppwszconvertedurl: *mut super::super::Foundation::PWSTR) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Networking_WinHttp"))]
pub fn InternetCrackUrlA(lpszurl: super::super::Foundation::PSTR, dwurllength: u32, dwflags: super::WinHttp::WIN_HTTP_CREATE_URL_FLAGS, lpurlcomponents: *mut URL_COMPONENTSA) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Networking_WinHttp"))]
pub fn InternetCrackUrlW(lpszurl: super::super::Foundation::PWSTR, dwurllength: u32, dwflags: super::WinHttp::WIN_HTTP_CREATE_URL_FLAGS, lpurlcomponents: *mut URL_COMPONENTSW) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCreateUrlA(lpurlcomponents: *const URL_COMPONENTSA, dwflags: u32, lpszurl: super::super::Foundation::PSTR, lpdwurllength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetCreateUrlW(lpurlcomponents: *const URL_COMPONENTSW, dwflags: u32, lpszurl: super::super::Foundation::PWSTR, lpdwurllength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetDial(hwndparent: super::super::Foundation::HWND, lpszconnectoid: super::super::Foundation::PSTR, dwflags: u32, lpdwconnection: *mut u32, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetDialA(hwndparent: super::super::Foundation::HWND, lpszconnectoid: super::super::Foundation::PSTR, dwflags: u32, lpdwconnection: *mut usize, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetDialW(hwndparent: super::super::Foundation::HWND, lpszconnectoid: super::super::Foundation::PWSTR, dwflags: u32, lpdwconnection: *mut usize, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetEnumPerSiteCookieDecisionA(pszsitename: super::super::Foundation::PSTR, pcsitenamesize: *mut u32, pdwdecision: *mut u32, dwindex: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetEnumPerSiteCookieDecisionW(pszsitename: super::super::Foundation::PWSTR, pcsitenamesize: *mut u32, pdwdecision: *mut u32, dwindex: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetErrorDlg(hwnd: super::super::Foundation::HWND, hrequest: *mut ::core::ffi::c_void, dwerror: u32, dwflags: u32, lppvdata: *mut *mut ::core::ffi::c_void) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetFindNextFileA(hfind: *const ::core::ffi::c_void, lpvfinddata: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetFindNextFileW(hfind: *const ::core::ffi::c_void, lpvfinddata: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetFortezzaCommand(dwcommand: u32, hwnd: super::super::Foundation::HWND, dwreserved: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetFreeCookies(pcookies: *mut INTERNET_COOKIE2, dwcookiecount: u32);
#[cfg(feature = "Win32_Foundation")]
pub fn InternetFreeProxyInfoList(pproxyinfolist: *mut WININET_PROXY_INFO_LIST);
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetConnectedState(lpdwflags: *mut INTERNET_CONNECTION, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetConnectedStateEx(lpdwflags: *mut INTERNET_CONNECTION, lpszconnectionname: super::super::Foundation::PSTR, dwnamelen: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetConnectedStateExA(lpdwflags: *mut INTERNET_CONNECTION, lpszconnectionname: super::super::Foundation::PSTR, cchnamelen: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetConnectedStateExW(lpdwflags: *mut INTERNET_CONNECTION, lpszconnectionname: super::super::Foundation::PWSTR, cchnamelen: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetCookieA(lpszurl: super::super::Foundation::PSTR, lpszcookiename: super::super::Foundation::PSTR, lpszcookiedata: super::super::Foundation::PSTR, lpdwsize: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetCookieEx2(pcwszurl: super::super::Foundation::PWSTR, pcwszcookiename: super::super::Foundation::PWSTR, dwflags: u32, ppcookies: *mut *mut INTERNET_COOKIE2, pdwcookiecount: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetCookieExA(lpszurl: super::super::Foundation::PSTR, lpszcookiename: super::super::Foundation::PSTR, lpszcookiedata: super::super::Foundation::PSTR, lpdwsize: *mut u32, dwflags: INTERNET_COOKIE_FLAGS, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetCookieExW(lpszurl: super::super::Foundation::PWSTR, lpszcookiename: super::super::Foundation::PWSTR, lpszcookiedata: super::super::Foundation::PWSTR, lpdwsize: *mut u32, dwflags: INTERNET_COOKIE_FLAGS, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetCookieW(lpszurl: super::super::Foundation::PWSTR, lpszcookiename: super::super::Foundation::PWSTR, lpszcookiedata: super::super::Foundation::PWSTR, lpdwsize: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetLastResponseInfoA(lpdwerror: *mut u32, lpszbuffer: super::super::Foundation::PSTR, lpdwbufferlength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetLastResponseInfoW(lpdwerror: *mut u32, lpszbuffer: super::super::Foundation::PWSTR, lpdwbufferlength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetPerSiteCookieDecisionA(pchhostname: super::super::Foundation::PSTR, presult: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetPerSiteCookieDecisionW(pchhostname: super::super::Foundation::PWSTR, presult: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGetProxyForUrl(hinternet: *const ::core::ffi::c_void, pcwszurl: super::super::Foundation::PWSTR, pproxyinfolist: *mut WININET_PROXY_INFO_LIST) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography"))]
pub fn InternetGetSecurityInfoByURL(lpszurl: super::super::Foundation::PSTR, ppcertchain: *mut *mut super::super::Security::Cryptography::CERT_CHAIN_CONTEXT, pdwsecureflags: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography"))]
pub fn InternetGetSecurityInfoByURLA(lpszurl: super::super::Foundation::PSTR, ppcertchain: *mut *mut super::super::Security::Cryptography::CERT_CHAIN_CONTEXT, pdwsecureflags: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Cryptography"))]
pub fn InternetGetSecurityInfoByURLW(lpszurl: super::super::Foundation::PWSTR, ppcertchain: *mut *mut super::super::Security::Cryptography::CERT_CHAIN_CONTEXT, pdwsecureflags: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGoOnline(lpszurl: super::super::Foundation::PSTR, hwndparent: super::super::Foundation::HWND, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGoOnlineA(lpszurl: super::super::Foundation::PSTR, hwndparent: super::super::Foundation::HWND, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetGoOnlineW(lpszurl: super::super::Foundation::PWSTR, hwndparent: super::super::Foundation::HWND, dwflags: u32) -> super::super::Foundation::BOOL;
pub fn InternetHangUp(dwconnection: usize, dwreserved: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetInitializeAutoProxyDll(dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetLockRequestFile(hinternet: *const ::core::ffi::c_void, lphlockrequestinfo: *mut super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetOpenA(lpszagent: super::super::Foundation::PSTR, dwaccesstype: u32, lpszproxy: super::super::Foundation::PSTR, lpszproxybypass: super::super::Foundation::PSTR, dwflags: u32) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetOpenUrlA(hinternet: *const ::core::ffi::c_void, lpszurl: super::super::Foundation::PSTR, lpszheaders: super::super::Foundation::PSTR, dwheaderslength: u32, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetOpenUrlW(hinternet: *const ::core::ffi::c_void, lpszurl: super::super::Foundation::PWSTR, lpszheaders: super::super::Foundation::PWSTR, dwheaderslength: u32, dwflags: u32, dwcontext: usize) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetOpenW(lpszagent: super::super::Foundation::PWSTR, dwaccesstype: u32, lpszproxy: super::super::Foundation::PWSTR, lpszproxybypass: super::super::Foundation::PWSTR, dwflags: u32) -> *mut ::core::ffi::c_void;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetQueryDataAvailable(hfile: *const ::core::ffi::c_void, lpdwnumberofbytesavailable: *mut u32, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetQueryFortezzaStatus(pdwstatus: *mut u32, dwreserved: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetQueryOptionA(hinternet: *const ::core::ffi::c_void, dwoption: u32, lpbuffer: *mut ::core::ffi::c_void, lpdwbufferlength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetQueryOptionW(hinternet: *const ::core::ffi::c_void, dwoption: u32, lpbuffer: *mut ::core::ffi::c_void, lpdwbufferlength: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetReadFile(hfile: *const ::core::ffi::c_void, lpbuffer: *mut ::core::ffi::c_void, dwnumberofbytestoread: u32, lpdwnumberofbytesread: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetReadFileExA(hfile: *const ::core::ffi::c_void, lpbuffersout: *mut INTERNET_BUFFERSA, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetReadFileExW(hfile: *const ::core::ffi::c_void, lpbuffersout: *mut INTERNET_BUFFERSW, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSecurityProtocolToStringA(dwprotocol: u32, lpstr: super::super::Foundation::PSTR, lpdwstrlength: *mut u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSecurityProtocolToStringW(dwprotocol: u32, lpstr: super::super::Foundation::PWSTR, lpdwstrlength: *mut u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetCookieA(lpszurl: super::super::Foundation::PSTR, lpszcookiename: super::super::Foundation::PSTR, lpszcookiedata: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetCookieEx2(pcwszurl: super::super::Foundation::PWSTR, pcookie: *const INTERNET_COOKIE2, pcwszp3ppolicy: super::super::Foundation::PWSTR, dwflags: u32, pdwcookiestate: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetCookieExA(lpszurl: super::super::Foundation::PSTR, lpszcookiename: super::super::Foundation::PSTR, lpszcookiedata: super::super::Foundation::PSTR, dwflags: u32, dwreserved: usize) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetCookieExW(lpszurl: super::super::Foundation::PWSTR, lpszcookiename: super::super::Foundation::PWSTR, lpszcookiedata: super::super::Foundation::PWSTR, dwflags: u32, dwreserved: usize) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetCookieW(lpszurl: super::super::Foundation::PWSTR, lpszcookiename: super::super::Foundation::PWSTR, lpszcookiedata: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetDialState(lpszconnectoid: super::super::Foundation::PSTR, dwstate: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetDialStateA(lpszconnectoid: super::super::Foundation::PSTR, dwstate: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetDialStateW(lpszconnectoid: super::super::Foundation::PWSTR, dwstate: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
pub fn InternetSetFilePointer(hfile: *const ::core::ffi::c_void, ldistancetomove: i32, lpdistancetomovehigh: *mut i32, dwmovemethod: u32, dwcontext: usize) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetOptionA(hinternet: *const ::core::ffi::c_void, dwoption: u32, lpbuffer: *const ::core::ffi::c_void, dwbufferlength: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetOptionExA(hinternet: *const ::core::ffi::c_void, dwoption: u32, lpbuffer: *const ::core::ffi::c_void, dwbufferlength: u32, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetOptionExW(hinternet: *const ::core::ffi::c_void, dwoption: u32, lpbuffer: *const ::core::ffi::c_void, dwbufferlength: u32, dwflags: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetOptionW(hinternet: *const ::core::ffi::c_void, dwoption: u32, lpbuffer: *const ::core::ffi::c_void, dwbufferlength: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetPerSiteCookieDecisionA(pchhostname: super::super::Foundation::PSTR, dwdecision: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetSetPerSiteCookieDecisionW(pchhostname: super::super::Foundation::PWSTR, dwdecision: u32) -> super::super::Foundation::BOOL;
pub fn InternetSetStatusCallback(hinternet: *const ::core::ffi::c_void, lpfninternetcallback: LPINTERNET_STATUS_CALLBACK) -> LPINTERNET_STATUS_CALLBACK;
pub fn InternetSetStatusCallbackA(hinternet: *const ::core::ffi::c_void, lpfninternetcallback: LPINTERNET_STATUS_CALLBACK) -> LPINTERNET_STATUS_CALLBACK;
pub fn InternetSetStatusCallbackW(hinternet: *const ::core::ffi::c_void, lpfninternetcallback: LPINTERNET_STATUS_CALLBACK) -> LPINTERNET_STATUS_CALLBACK;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetShowSecurityInfoByURL(lpszurl: super::super::Foundation::PSTR, hwndparent: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetShowSecurityInfoByURLA(lpszurl: super::super::Foundation::PSTR, hwndparent: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetShowSecurityInfoByURLW(lpszurl: super::super::Foundation::PWSTR, hwndparent: super::super::Foundation::HWND) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetTimeFromSystemTime(pst: *const super::super::Foundation::SYSTEMTIME, dwrfc: u32, lpsztime: super::super::Foundation::PSTR, cbtime: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetTimeFromSystemTimeA(pst: *const super::super::Foundation::SYSTEMTIME, dwrfc: u32, lpsztime: super::super::Foundation::PSTR, cbtime: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetTimeFromSystemTimeW(pst: *const super::super::Foundation::SYSTEMTIME, dwrfc: u32, lpsztime: super::super::Foundation::PWSTR, cbtime: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetTimeToSystemTime(lpsztime: super::super::Foundation::PSTR, pst: *mut super::super::Foundation::SYSTEMTIME, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetTimeToSystemTimeA(lpsztime: super::super::Foundation::PSTR, pst: *mut super::super::Foundation::SYSTEMTIME, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetTimeToSystemTimeW(lpsztime: super::super::Foundation::PWSTR, pst: *mut super::super::Foundation::SYSTEMTIME, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetUnlockRequestFile(hlockrequestinfo: super::super::Foundation::HANDLE) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetWriteFile(hfile: *const ::core::ffi::c_void, lpbuffer: *const ::core::ffi::c_void, dwnumberofbytestowrite: u32, lpdwnumberofbyteswritten: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetWriteFileExA(hfile: *const ::core::ffi::c_void, lpbuffersin: *const INTERNET_BUFFERSA, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn InternetWriteFileExW(hfile: *const ::core::ffi::c_void, lpbuffersin: *const INTERNET_BUFFERSW, dwflags: u32, dwcontext: usize) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IsDomainLegalCookieDomainA(pchdomain: super::super::Foundation::PSTR, pchfulldomain: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IsDomainLegalCookieDomainW(pchdomain: super::super::Foundation::PWSTR, pchfulldomain: super::super::Foundation::PWSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IsHostInProxyBypassList(tscheme: INTERNET_SCHEME, lpszhost: super::super::Foundation::PSTR, cchhost: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IsProfilesEnabled() -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IsUrlCacheEntryExpiredA(lpszurlname: super::super::Foundation::PSTR, dwflags: u32, pftlastmodified: *mut super::super::Foundation::FILETIME) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn IsUrlCacheEntryExpiredW(lpszurlname: super::super::Foundation::PWSTR, dwflags: u32, pftlastmodified: *mut super::super::Foundation::FILETIME) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn LoadUrlCacheContent() -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ParseX509EncodedCertificateForListBoxEntry(lpcert: *const u8, cbcert: u32, lpszlistboxentry: super::super::Foundation::PSTR, lpdwlistboxentry: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn PerformOperationOverUrlCacheA(pszurlsearchpattern: super::super::Foundation::PSTR, dwflags: u32, dwfilter: u32, groupid: i64, preserved1: *mut ::core::ffi::c_void, pdwreserved2: *mut u32, preserved3: *mut ::core::ffi::c_void, op: CACHE_OPERATOR, poperatordata: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn PrivacyGetZonePreferenceW(dwzone: u32, dwtype: u32, pdwtemplate: *mut u32, pszbuffer: super::super::Foundation::PWSTR, pdwbufferlength: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn PrivacySetZonePreferenceW(dwzone: u32, dwtype: u32, dwtemplate: u32, pszpreference: super::super::Foundation::PWSTR) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn ReadGuidsForConnectedNetworks(pcnetworks: *mut u32, pppwsznetworkguids: *mut *mut super::super::Foundation::PWSTR, pppbstrnetworknames: *mut *mut super::super::Foundation::BSTR, pppwszgwmacs: *mut *mut super::super::Foundation::PWSTR, pcgatewaymacs: *mut u32, pdwflags: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ReadUrlCacheEntryStream(hurlcachestream: super::super::Foundation::HANDLE, dwlocation: u32, lpbuffer: *mut ::core::ffi::c_void, lpdwlen: *mut u32, reserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ReadUrlCacheEntryStreamEx(hurlcachestream: super::super::Foundation::HANDLE, qwlocation: u64, lpbuffer: *mut ::core::ffi::c_void, lpdwlen: *mut u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn RegisterUrlCacheNotification(hwnd: super::super::Foundation::HWND, umsg: u32, gid: i64, dwopsfilter: u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ResumeSuspendedDownload(hrequest: *const ::core::ffi::c_void, dwresultcode: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn RetrieveUrlCacheEntryFileA(lpszurlname: super::super::Foundation::PSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn RetrieveUrlCacheEntryFileW(lpszurlname: super::super::Foundation::PWSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn RetrieveUrlCacheEntryStreamA(lpszurlname: super::super::Foundation::PSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOA, lpcbcacheentryinfo: *mut u32, frandomread: super::super::Foundation::BOOL, dwreserved: u32) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn RetrieveUrlCacheEntryStreamW(lpszurlname: super::super::Foundation::PWSTR, lpcacheentryinfo: *mut INTERNET_CACHE_ENTRY_INFOW, lpcbcacheentryinfo: *mut u32, frandomread: super::super::Foundation::BOOL, dwreserved: u32) -> super::super::Foundation::HANDLE;
#[cfg(feature = "Win32_Foundation")]
pub fn RunOnceUrlCache(hwnd: super::super::Foundation::HWND, hinst: super::super::Foundation::HINSTANCE, lpszcmd: super::super::Foundation::PSTR, ncmdshow: i32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheConfigInfoA(lpcacheconfiginfo: *const INTERNET_CACHE_CONFIG_INFOA, dwfieldcontrol: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheConfigInfoW(lpcacheconfiginfo: *const INTERNET_CACHE_CONFIG_INFOW, dwfieldcontrol: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheEntryGroup(lpszurlname: super::super::Foundation::PSTR, dwflags: u32, groupid: i64, pbgroupattributes: *mut u8, cbgroupattributes: u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheEntryGroupA(lpszurlname: super::super::Foundation::PSTR, dwflags: u32, groupid: i64, pbgroupattributes: *mut u8, cbgroupattributes: u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheEntryGroupW(lpszurlname: super::super::Foundation::PWSTR, dwflags: u32, groupid: i64, pbgroupattributes: *mut u8, cbgroupattributes: u32, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheEntryInfoA(lpszurlname: super::super::Foundation::PSTR, lpcacheentryinfo: *const INTERNET_CACHE_ENTRY_INFOA, dwfieldcontrol: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheEntryInfoW(lpszurlname: super::super::Foundation::PWSTR, lpcacheentryinfo: *const INTERNET_CACHE_ENTRY_INFOW, dwfieldcontrol: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheGroupAttributeA(gid: i64, dwflags: u32, dwattributes: u32, lpgroupinfo: *const INTERNET_CACHE_GROUP_INFOA, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheGroupAttributeW(gid: i64, dwflags: u32, dwattributes: u32, lpgroupinfo: *const INTERNET_CACHE_GROUP_INFOW, lpreserved: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn SetUrlCacheHeaderData(nidx: u32, dwdata: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn ShowClientAuthCerts(hwndparent: super::super::Foundation::HWND) -> u32;
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity", feature = "Win32_Security_Cryptography"))]
pub fn ShowSecurityInfo(hwndparent: super::super::Foundation::HWND, psecurityinfo: *const INTERNET_SECURITY_INFO) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn ShowX509EncodedCertificate(hwndparent: super::super::Foundation::HWND, lpcert: *const u8, cbcert: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UnlockUrlCacheEntryFile(lpszurlname: super::super::Foundation::PSTR, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn UnlockUrlCacheEntryFileA(lpszurlname: super::super::Foundation::PSTR, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn UnlockUrlCacheEntryFileW(lpszurlname: super::super::Foundation::PWSTR, dwreserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn UnlockUrlCacheEntryStream(hurlcachestream: super::super::Foundation::HANDLE, reserved: u32) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn UpdateUrlCacheContentPath(sznewpath: super::super::Foundation::PSTR) -> super::super::Foundation::BOOL;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheCheckEntriesExist(rgpwszurls: *const super::super::Foundation::PWSTR, centries: u32, rgfexist: *mut super::super::Foundation::BOOL) -> u32;
pub fn UrlCacheCloseEntryHandle(hentryfile: *const ::core::ffi::c_void);
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheContainerSetEntryMaximumAge(pwszprefix: super::super::Foundation::PWSTR, dwentrymaxage: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheCreateContainer(pwszname: super::super::Foundation::PWSTR, pwszprefix: super::super::Foundation::PWSTR, pwszdirectory: super::super::Foundation::PWSTR, ulllimit: u64, dwoptions: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheFindFirstEntry(pwszprefix: super::super::Foundation::PWSTR, dwflags: u32, dwfilter: u32, groupid: i64, pcacheentryinfo: *mut URLCACHE_ENTRY_INFO, phfind: *mut super::super::Foundation::HANDLE) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheFindNextEntry(hfind: super::super::Foundation::HANDLE, pcacheentryinfo: *mut URLCACHE_ENTRY_INFO) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheFreeEntryInfo(pcacheentryinfo: *mut URLCACHE_ENTRY_INFO);
pub fn UrlCacheFreeGlobalSpace(ulltargetsize: u64, dwfilter: u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheGetContentPaths(pppwszdirectories: *mut *mut super::super::Foundation::PWSTR, pcdirectories: *mut u32) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheGetEntryInfo(happcache: *const ::core::ffi::c_void, pcwszurl: super::super::Foundation::PWSTR, pcacheentryinfo: *mut URLCACHE_ENTRY_INFO) -> u32;
pub fn UrlCacheGetGlobalCacheSize(dwfilter: u32, pullsize: *mut u64, pulllimit: *mut u64) -> u32;
pub fn UrlCacheGetGlobalLimit(limittype: URL_CACHE_LIMIT_TYPE, pulllimit: *mut u64) -> u32;
pub fn UrlCacheReadEntryStream(hurlcachestream: *const ::core::ffi::c_void, ulllocation: u64, pbuffer: *mut ::core::ffi::c_void, dwbufferlen: u32, pdwbufferlen: *mut u32) -> u32;
pub fn UrlCacheReloadSettings() -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheRetrieveEntryFile(happcache: *const ::core::ffi::c_void, pcwszurl: super::super::Foundation::PWSTR, pcacheentryinfo: *mut URLCACHE_ENTRY_INFO, phentryfile: *mut *mut ::core::ffi::c_void) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheRetrieveEntryStream(happcache: *const ::core::ffi::c_void, pcwszurl: super::super::Foundation::PWSTR, frandomread: super::super::Foundation::BOOL, pcacheentryinfo: *mut URLCACHE_ENTRY_INFO, phentrystream: *mut *mut ::core::ffi::c_void) -> u32;
pub fn UrlCacheServer() -> u32;
pub fn UrlCacheSetGlobalLimit(limittype: URL_CACHE_LIMIT_TYPE, ulllimit: u64) -> u32;
#[cfg(feature = "Win32_Foundation")]
pub fn UrlCacheUpdateEntryExtraData(happcache: *const ::core::ffi::c_void, pcwszurl: super::super::Foundation::PWSTR, pbextradata: *const u8, cbextradata: u32) -> u32;
}
pub const ANY_CACHE_ENTRY: u32 = 4294967295u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct APP_CACHE_DOWNLOAD_ENTRY {
pub pwszUrl: super::super::Foundation::PWSTR,
pub dwEntryType: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for APP_CACHE_DOWNLOAD_ENTRY {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for APP_CACHE_DOWNLOAD_ENTRY {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct APP_CACHE_DOWNLOAD_LIST {
pub dwEntryCount: u32,
pub pEntries: *mut APP_CACHE_DOWNLOAD_ENTRY,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for APP_CACHE_DOWNLOAD_LIST {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for APP_CACHE_DOWNLOAD_LIST {
fn clone(&self) -> Self {
*self
}
}
pub const APP_CACHE_ENTRY_TYPE_EXPLICIT: u32 = 2u32;
pub const APP_CACHE_ENTRY_TYPE_FALLBACK: u32 = 4u32;
pub const APP_CACHE_ENTRY_TYPE_FOREIGN: u32 = 8u32;
pub const APP_CACHE_ENTRY_TYPE_MANIFEST: u32 = 16u32;
pub const APP_CACHE_ENTRY_TYPE_MASTER: u32 = 1u32;
pub type APP_CACHE_FINALIZE_STATE = i32;
pub const AppCacheFinalizeStateIncomplete: APP_CACHE_FINALIZE_STATE = 0i32;
pub const AppCacheFinalizeStateManifestChange: APP_CACHE_FINALIZE_STATE = 1i32;
pub const AppCacheFinalizeStateComplete: APP_CACHE_FINALIZE_STATE = 2i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct APP_CACHE_GROUP_INFO {
pub pwszManifestUrl: super::super::Foundation::PWSTR,
pub ftLastAccessTime: super::super::Foundation::FILETIME,
pub ullSize: u64,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for APP_CACHE_GROUP_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for APP_CACHE_GROUP_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct APP_CACHE_GROUP_LIST {
pub dwAppCacheGroupCount: u32,
pub pAppCacheGroups: *mut APP_CACHE_GROUP_INFO,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for APP_CACHE_GROUP_LIST {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for APP_CACHE_GROUP_LIST {
fn clone(&self) -> Self {
*self
}
}
pub const APP_CACHE_LOOKUP_NO_MASTER_ONLY: u32 = 1u32;
pub type APP_CACHE_STATE = i32;
pub const AppCacheStateNoUpdateNeeded: APP_CACHE_STATE = 0i32;
pub const AppCacheStateUpdateNeeded: APP_CACHE_STATE = 1i32;
pub const AppCacheStateUpdateNeededNew: APP_CACHE_STATE = 2i32;
pub const AppCacheStateUpdateNeededMasterOnly: APP_CACHE_STATE = 3i32;
pub const AUTH_FLAG_DISABLE_BASIC_CLEARCHANNEL: u32 = 4u32;
pub const AUTH_FLAG_DISABLE_NEGOTIATE: u32 = 1u32;
pub const AUTH_FLAG_DISABLE_SERVER_AUTH: u32 = 8u32;
pub const AUTH_FLAG_ENABLE_NEGOTIATE: u32 = 2u32;
pub const AUTH_FLAG_RESET: u32 = 0u32;
pub const AUTODIAL_MODE_ALWAYS: u32 = 2u32;
pub const AUTODIAL_MODE_NEVER: u32 = 1u32;
pub const AUTODIAL_MODE_NO_NETWORK_PRESENT: u32 = 4u32;
pub const AUTO_PROXY_FLAG_ALWAYS_DETECT: u32 = 2u32;
pub const AUTO_PROXY_FLAG_CACHE_INIT_RUN: u32 = 32u32;
pub const AUTO_PROXY_FLAG_DETECTION_RUN: u32 = 4u32;
pub const AUTO_PROXY_FLAG_DETECTION_SUSPECT: u32 = 64u32;
pub const AUTO_PROXY_FLAG_DONT_CACHE_PROXY_RESULT: u32 = 16u32;
pub const AUTO_PROXY_FLAG_MIGRATED: u32 = 8u32;
pub const AUTO_PROXY_FLAG_USER_SET: u32 = 1u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct AUTO_PROXY_SCRIPT_BUFFER {
pub dwStructSize: u32,
pub lpszScriptBuffer: super::super::Foundation::PSTR,
pub dwScriptBufferSize: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for AUTO_PROXY_SCRIPT_BUFFER {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for AUTO_PROXY_SCRIPT_BUFFER {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct AutoProxyHelperFunctions {
pub lpVtbl: *mut AutoProxyHelperVtbl,
}
impl ::core::marker::Copy for AutoProxyHelperFunctions {}
impl ::core::clone::Clone for AutoProxyHelperFunctions {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct AutoProxyHelperVtbl {
pub IsResolvable: isize,
pub GetIPAddress: isize,
pub ResolveHostName: isize,
pub IsInNet: isize,
pub IsResolvableEx: isize,
pub GetIPAddressEx: isize,
pub ResolveHostNameEx: isize,
pub IsInNetEx: isize,
pub SortIpList: isize,
}
impl ::core::marker::Copy for AutoProxyHelperVtbl {}
impl ::core::clone::Clone for AutoProxyHelperVtbl {
fn clone(&self) -> Self {
*self
}
}
pub const CACHEGROUP_ATTRIBUTE_BASIC: u32 = 1u32;
pub const CACHEGROUP_ATTRIBUTE_FLAG: u32 = 2u32;
pub const CACHEGROUP_ATTRIBUTE_GET_ALL: u32 = 4294967295u32;
pub const CACHEGROUP_ATTRIBUTE_GROUPNAME: u32 = 16u32;
pub const CACHEGROUP_ATTRIBUTE_QUOTA: u32 = 8u32;
pub const CACHEGROUP_ATTRIBUTE_STORAGE: u32 = 32u32;
pub const CACHEGROUP_ATTRIBUTE_TYPE: u32 = 4u32;
pub const CACHEGROUP_FLAG_FLUSHURL_ONDELETE: u32 = 2u32;
pub const CACHEGROUP_FLAG_GIDONLY: u32 = 4u32;
pub const CACHEGROUP_FLAG_NONPURGEABLE: u32 = 1u32;
pub const CACHEGROUP_FLAG_VALID: u32 = 7u32;
pub const CACHEGROUP_ID_BUILTIN_STICKY: u64 = 1152921504606846983u64;
pub const CACHEGROUP_SEARCH_ALL: u32 = 0u32;
pub const CACHEGROUP_SEARCH_BYURL: u32 = 1u32;
pub const CACHEGROUP_TYPE_INVALID: u32 = 1u32;
pub type CACHE_CONFIG = u32;
pub const CACHE_CONFIG_FORCE_CLEANUP_FC: CACHE_CONFIG = 32u32;
pub const CACHE_CONFIG_DISK_CACHE_PATHS_FC: CACHE_CONFIG = 64u32;
pub const CACHE_CONFIG_SYNC_MODE_FC: CACHE_CONFIG = 128u32;
pub const CACHE_CONFIG_CONTENT_PATHS_FC: CACHE_CONFIG = 256u32;
pub const CACHE_CONFIG_HISTORY_PATHS_FC: CACHE_CONFIG = 1024u32;
pub const CACHE_CONFIG_COOKIES_PATHS_FC: CACHE_CONFIG = 512u32;
pub const CACHE_CONFIG_QUOTA_FC: CACHE_CONFIG = 2048u32;
pub const CACHE_CONFIG_USER_MODE_FC: CACHE_CONFIG = 4096u32;
pub const CACHE_CONFIG_CONTENT_USAGE_FC: CACHE_CONFIG = 8192u32;
pub const CACHE_CONFIG_STICKY_CONTENT_USAGE_FC: CACHE_CONFIG = 16384u32;
pub const CACHE_CONFIG_APPCONTAINER_CONTENT_QUOTA_FC: u32 = 131072u32;
pub const CACHE_CONFIG_APPCONTAINER_TOTAL_CONTENT_QUOTA_FC: u32 = 262144u32;
pub const CACHE_CONFIG_CONTENT_QUOTA_FC: u32 = 32768u32;
pub const CACHE_CONFIG_TOTAL_CONTENT_QUOTA_FC: u32 = 65536u32;
pub const CACHE_ENTRY_ACCTIME_FC: u32 = 256u32;
pub const CACHE_ENTRY_ATTRIBUTE_FC: u32 = 4u32;
pub const CACHE_ENTRY_EXEMPT_DELTA_FC: u32 = 2048u32;
pub const CACHE_ENTRY_EXPTIME_FC: u32 = 128u32;
pub const CACHE_ENTRY_HEADERINFO_FC: u32 = 1024u32;
pub const CACHE_ENTRY_HITRATE_FC: u32 = 16u32;
pub const CACHE_ENTRY_MODIFY_DATA_FC: u32 = 2147483648u32;
pub const CACHE_ENTRY_MODTIME_FC: u32 = 64u32;
pub const CACHE_ENTRY_SYNCTIME_FC: u32 = 512u32;
pub const CACHE_ENTRY_TYPE_FC: u32 = 4096u32;
pub const CACHE_FIND_CONTAINER_RETURN_NOCHANGE: u32 = 1u32;
pub const CACHE_HEADER_DATA_CACHE_READ_COUNT_SINCE_LAST_SCAVENGE: u32 = 9u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_12: u32 = 12u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_13: u32 = 13u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_15: u32 = 15u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_16: u32 = 16u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_17: u32 = 17u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_18: u32 = 18u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_19: u32 = 19u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_20: u32 = 20u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_23: u32 = 23u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_24: u32 = 24u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_25: u32 = 25u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_26: u32 = 26u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_28: u32 = 28u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_29: u32 = 29u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_30: u32 = 30u32;
pub const CACHE_HEADER_DATA_CACHE_RESERVED_31: u32 = 31u32;
pub const CACHE_HEADER_DATA_CACHE_WRITE_COUNT_SINCE_LAST_SCAVENGE: u32 = 10u32;
pub const CACHE_HEADER_DATA_CONLIST_CHANGE_COUNT: u32 = 1u32;
pub const CACHE_HEADER_DATA_COOKIE_CHANGE_COUNT: u32 = 2u32;
pub const CACHE_HEADER_DATA_CURRENT_SETTINGS_VERSION: u32 = 0u32;
pub const CACHE_HEADER_DATA_DOWNLOAD_PARTIAL: u32 = 14u32;
pub const CACHE_HEADER_DATA_GID_HIGH: u32 = 7u32;
pub const CACHE_HEADER_DATA_GID_LOW: u32 = 6u32;
pub const CACHE_HEADER_DATA_HSTS_CHANGE_COUNT: u32 = 11u32;
pub const CACHE_HEADER_DATA_LAST: u32 = 31u32;
pub const CACHE_HEADER_DATA_LAST_SCAVENGE_TIMESTAMP: u32 = 8u32;
pub const CACHE_HEADER_DATA_NOTIFICATION_FILTER: u32 = 21u32;
pub const CACHE_HEADER_DATA_NOTIFICATION_HWND: u32 = 3u32;
pub const CACHE_HEADER_DATA_NOTIFICATION_MESG: u32 = 4u32;
pub const CACHE_HEADER_DATA_ROOTGROUP_OFFSET: u32 = 5u32;
pub const CACHE_HEADER_DATA_ROOT_GROUPLIST_OFFSET: u32 = 27u32;
pub const CACHE_HEADER_DATA_ROOT_LEAK_OFFSET: u32 = 22u32;
pub const CACHE_HEADER_DATA_SSL_STATE_COUNT: u32 = 14u32;
pub const CACHE_NOTIFY_ADD_URL: u32 = 1u32;
pub const CACHE_NOTIFY_DELETE_ALL: u32 = 8u32;
pub const CACHE_NOTIFY_DELETE_URL: u32 = 2u32;
pub const CACHE_NOTIFY_FILTER_CHANGED: u32 = 268435456u32;
pub const CACHE_NOTIFY_SET_OFFLINE: u32 = 512u32;
pub const CACHE_NOTIFY_SET_ONLINE: u32 = 256u32;
pub const CACHE_NOTIFY_UPDATE_URL: u32 = 4u32;
pub const CACHE_NOTIFY_URL_SET_STICKY: u32 = 16u32;
pub const CACHE_NOTIFY_URL_UNSET_STICKY: u32 = 32u32;
#[cfg(feature = "Win32_Foundation")]
pub type CACHE_OPERATOR = ::core::option::Option<unsafe extern "system" fn(pcei: *mut INTERNET_CACHE_ENTRY_INFOA, pcbcei: *mut u32, popdata: *mut ::core::ffi::c_void) -> super::super::Foundation::BOOL>;
pub const COOKIE_ACCEPTED_CACHE_ENTRY: u32 = 4096u32;
pub const COOKIE_ALLOW: u32 = 2u32;
pub const COOKIE_ALLOW_ALL: u32 = 4u32;
pub const COOKIE_CACHE_ENTRY: u32 = 1048576u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct COOKIE_DLG_INFO {
pub pszServer: super::super::Foundation::PWSTR,
pub pic: *mut INTERNET_COOKIE,
pub dwStopWarning: u32,
pub cx: i32,
pub cy: i32,
pub pszHeader: super::super::Foundation::PWSTR,
pub dwOperation: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for COOKIE_DLG_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for COOKIE_DLG_INFO {
fn clone(&self) -> Self {
*self
}
}
pub const COOKIE_DONT_ALLOW: u32 = 1u32;
pub const COOKIE_DONT_ALLOW_ALL: u32 = 8u32;
pub const COOKIE_DOWNGRADED_CACHE_ENTRY: u32 = 16384u32;
pub const COOKIE_LEASHED_CACHE_ENTRY: u32 = 8192u32;
pub const COOKIE_OP_3RD_PARTY: u32 = 32u32;
pub const COOKIE_OP_GET: u32 = 4u32;
pub const COOKIE_OP_MODIFY: u32 = 2u32;
pub const COOKIE_OP_PERSISTENT: u32 = 16u32;
pub const COOKIE_OP_SESSION: u32 = 8u32;
pub const COOKIE_OP_SET: u32 = 1u32;
pub const COOKIE_REJECTED_CACHE_ENTRY: u32 = 32768u32;
pub const COOKIE_STATE_LB: u32 = 0u32;
pub const COOKIE_STATE_UB: u32 = 5u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct CookieDecision {
pub dwCookieState: u32,
pub fAllowSession: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for CookieDecision {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for CookieDecision {
fn clone(&self) -> Self {
*self
}
}
pub const DIALENG_OperationComplete: u32 = 65536u32;
pub const DIALENG_RedialAttempt: u32 = 65537u32;
pub const DIALENG_RedialWait: u32 = 65538u32;
pub const DLG_FLAGS_INSECURE_FALLBACK: u32 = 4194304u32;
pub const DLG_FLAGS_INVALID_CA: u32 = 16777216u32;
pub const DLG_FLAGS_SEC_CERT_CN_INVALID: u32 = 33554432u32;
pub const DLG_FLAGS_SEC_CERT_DATE_INVALID: u32 = 67108864u32;
pub const DLG_FLAGS_SEC_CERT_REV_FAILED: u32 = 8388608u32;
pub const DLG_FLAGS_WEAK_SIGNATURE: u32 = 2097152u32;
pub const DOWNLOAD_CACHE_ENTRY: u32 = 1024u32;
pub const DUO_PROTOCOL_FLAG_SPDY3: u32 = 1u32;
pub const DUO_PROTOCOL_MASK: u32 = 1u32;
pub const EDITED_CACHE_ENTRY: u32 = 8u32;
pub const ERROR_FTP_DROPPED: u32 = 12111u32;
pub const ERROR_FTP_NO_PASSIVE_MODE: u32 = 12112u32;
pub const ERROR_FTP_TRANSFER_IN_PROGRESS: u32 = 12110u32;
pub const ERROR_GOPHER_ATTRIBUTE_NOT_FOUND: u32 = 12137u32;
pub const ERROR_GOPHER_DATA_ERROR: u32 = 12132u32;
pub const ERROR_GOPHER_END_OF_DATA: u32 = 12133u32;
pub const ERROR_GOPHER_INCORRECT_LOCATOR_TYPE: u32 = 12135u32;
pub const ERROR_GOPHER_INVALID_LOCATOR: u32 = 12134u32;
pub const ERROR_GOPHER_NOT_FILE: u32 = 12131u32;
pub const ERROR_GOPHER_NOT_GOPHER_PLUS: u32 = 12136u32;
pub const ERROR_GOPHER_PROTOCOL_ERROR: u32 = 12130u32;
pub const ERROR_GOPHER_UNKNOWN_LOCATOR: u32 = 12138u32;
pub const ERROR_HTTP_COOKIE_DECLINED: u32 = 12162u32;
pub const ERROR_HTTP_COOKIE_NEEDS_CONFIRMATION: u32 = 12161u32;
pub const ERROR_HTTP_COOKIE_NEEDS_CONFIRMATION_EX: u32 = 12907u32;
pub const ERROR_HTTP_DOWNLEVEL_SERVER: u32 = 12151u32;
pub const ERROR_HTTP_HEADER_ALREADY_EXISTS: u32 = 12155u32;
pub const ERROR_HTTP_HEADER_NOT_FOUND: u32 = 12150u32;
pub const ERROR_HTTP_HSTS_REDIRECT_REQUIRED: u32 = 12060u32;
pub const ERROR_HTTP_INVALID_HEADER: u32 = 12153u32;
pub const ERROR_HTTP_INVALID_QUERY_REQUEST: u32 = 12154u32;
pub const ERROR_HTTP_INVALID_SERVER_RESPONSE: u32 = 12152u32;
pub const ERROR_HTTP_NOT_REDIRECTED: u32 = 12160u32;
pub const ERROR_HTTP_PUSH_ENABLE_FAILED: u32 = 12149u32;
pub const ERROR_HTTP_PUSH_RETRY_NOT_SUPPORTED: u32 = 12148u32;
pub const ERROR_HTTP_PUSH_STATUS_CODE_NOT_SUPPORTED: u32 = 12147u32;
pub const ERROR_HTTP_REDIRECT_FAILED: u32 = 12156u32;
pub const ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION: u32 = 12168u32;
pub const ERROR_INTERNET_ASYNC_THREAD_FAILED: u32 = 12047u32;
pub const ERROR_INTERNET_BAD_AUTO_PROXY_SCRIPT: u32 = 12166u32;
pub const ERROR_INTERNET_BAD_OPTION_LENGTH: u32 = 12010u32;
pub const ERROR_INTERNET_BAD_REGISTRY_PARAMETER: u32 = 12022u32;
pub const ERROR_INTERNET_CACHE_SUCCESS: u32 = 12906u32;
pub const ERROR_INTERNET_CANNOT_CONNECT: u32 = 12029u32;
pub const ERROR_INTERNET_CHG_POST_IS_NON_SECURE: u32 = 12042u32;
pub const ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED: u32 = 12044u32;
pub const ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED_PROXY: u32 = 12187u32;
pub const ERROR_INTERNET_CLIENT_AUTH_NOT_SETUP: u32 = 12046u32;
pub const ERROR_INTERNET_CONNECTION_ABORTED: u32 = 12030u32;
pub const ERROR_INTERNET_CONNECTION_AVAILABLE: u32 = 12902u32;
pub const ERROR_INTERNET_CONNECTION_RESET: u32 = 12031u32;
pub const ERROR_INTERNET_DECODING_FAILED: u32 = 12175u32;
pub const ERROR_INTERNET_DIALOG_PENDING: u32 = 12049u32;
pub const ERROR_INTERNET_DISALLOW_INPRIVATE: u32 = 12189u32;
pub const ERROR_INTERNET_DISCONNECTED: u32 = 12163u32;
pub const ERROR_INTERNET_EXTENDED_ERROR: u32 = 12003u32;
pub const ERROR_INTERNET_FAILED_DUETOSECURITYCHECK: u32 = 12171u32;
pub const ERROR_INTERNET_FEATURE_DISABLED: u32 = 12192u32;
pub const ERROR_INTERNET_FORCE_RETRY: u32 = 12032u32;
pub const ERROR_INTERNET_FORTEZZA_LOGIN_NEEDED: u32 = 12054u32;
pub const ERROR_INTERNET_GLOBAL_CALLBACK_FAILED: u32 = 12191u32;
pub const ERROR_INTERNET_HANDLE_EXISTS: u32 = 12036u32;
pub const ERROR_INTERNET_HTTPS_HTTP_SUBMIT_REDIR: u32 = 12052u32;
pub const ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR: u32 = 12040u32;
pub const ERROR_INTERNET_HTTP_PROTOCOL_MISMATCH: u32 = 12190u32;
pub const ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR: u32 = 12039u32;
pub const ERROR_INTERNET_INCORRECT_FORMAT: u32 = 12027u32;
pub const ERROR_INTERNET_INCORRECT_HANDLE_STATE: u32 = 12019u32;
pub const ERROR_INTERNET_INCORRECT_HANDLE_TYPE: u32 = 12018u32;
pub const ERROR_INTERNET_INCORRECT_PASSWORD: u32 = 12014u32;
pub const ERROR_INTERNET_INCORRECT_USER_NAME: u32 = 12013u32;
pub const ERROR_INTERNET_INSECURE_FALLBACK_REQUIRED: u32 = 12059u32;
pub const ERROR_INTERNET_INSERT_CDROM: u32 = 12053u32;
pub const ERROR_INTERNET_INTERNAL_ERROR: u32 = 12004u32;
pub const ERROR_INTERNET_INTERNAL_SOCKET_ERROR: u32 = 12901u32;
pub const ERROR_INTERNET_INVALID_CA: u32 = 12045u32;
pub const ERROR_INTERNET_INVALID_OPERATION: u32 = 12016u32;
pub const ERROR_INTERNET_INVALID_OPTION: u32 = 12009u32;
pub const ERROR_INTERNET_INVALID_PROXY_REQUEST: u32 = 12033u32;
pub const ERROR_INTERNET_INVALID_URL: u32 = 12005u32;
pub const ERROR_INTERNET_ITEM_NOT_FOUND: u32 = 12028u32;
pub const ERROR_INTERNET_LOGIN_FAILURE: u32 = 12015u32;
pub const ERROR_INTERNET_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: u32 = 12174u32;
pub const ERROR_INTERNET_MIXED_SECURITY: u32 = 12041u32;
pub const ERROR_INTERNET_NAME_NOT_RESOLVED: u32 = 12007u32;
pub const ERROR_INTERNET_NEED_MSN_SSPI_PKG: u32 = 12173u32;
pub const ERROR_INTERNET_NEED_UI: u32 = 12034u32;
pub const ERROR_INTERNET_NOT_INITIALIZED: u32 = 12172u32;
pub const ERROR_INTERNET_NOT_PROXY_REQUEST: u32 = 12020u32;
pub const ERROR_INTERNET_NO_CALLBACK: u32 = 12025u32;
pub const ERROR_INTERNET_NO_CM_CONNECTION: u32 = 12080u32;
pub const ERROR_INTERNET_NO_CONTEXT: u32 = 12024u32;
pub const ERROR_INTERNET_NO_DIRECT_ACCESS: u32 = 12023u32;
pub const ERROR_INTERNET_NO_KNOWN_SERVERS: u32 = 12903u32;
pub const ERROR_INTERNET_NO_NEW_CONTAINERS: u32 = 12051u32;
pub const ERROR_INTERNET_NO_PING_SUPPORT: u32 = 12905u32;
pub const ERROR_INTERNET_OFFLINE: u32 = 12163u32;
pub const ERROR_INTERNET_OPERATION_CANCELLED: u32 = 12017u32;
pub const ERROR_INTERNET_OPTION_NOT_SETTABLE: u32 = 12011u32;
pub const ERROR_INTERNET_OUT_OF_HANDLES: u32 = 12001u32;
pub const ERROR_INTERNET_PING_FAILED: u32 = 12904u32;
pub const ERROR_INTERNET_POST_IS_NON_SECURE: u32 = 12043u32;
pub const ERROR_INTERNET_PROTOCOL_NOT_FOUND: u32 = 12008u32;
pub const ERROR_INTERNET_PROXY_ALERT: u32 = 12061u32;
pub const ERROR_INTERNET_PROXY_SERVER_UNREACHABLE: u32 = 12165u32;
pub const ERROR_INTERNET_REDIRECT_SCHEME_CHANGE: u32 = 12048u32;
pub const ERROR_INTERNET_REGISTRY_VALUE_NOT_FOUND: u32 = 12021u32;
pub const ERROR_INTERNET_REQUEST_PENDING: u32 = 12026u32;
pub const ERROR_INTERNET_RETRY_DIALOG: u32 = 12050u32;
pub const ERROR_INTERNET_SECURE_FAILURE_PROXY: u32 = 12188u32;
pub const ERROR_INTERNET_SECURITY_CHANNEL_ERROR: u32 = 12157u32;
pub const ERROR_INTERNET_SEC_CERT_CN_INVALID: u32 = 12038u32;
pub const ERROR_INTERNET_SEC_CERT_DATE_INVALID: u32 = 12037u32;
pub const ERROR_INTERNET_SEC_CERT_ERRORS: u32 = 12055u32;
pub const ERROR_INTERNET_SEC_CERT_NO_REV: u32 = 12056u32;
pub const ERROR_INTERNET_SEC_CERT_REVOKED: u32 = 12170u32;
pub const ERROR_INTERNET_SEC_CERT_REV_FAILED: u32 = 12057u32;
pub const ERROR_INTERNET_SEC_CERT_WEAK_SIGNATURE: u32 = 12062u32;
pub const ERROR_INTERNET_SEC_INVALID_CERT: u32 = 12169u32;
pub const ERROR_INTERNET_SERVER_UNREACHABLE: u32 = 12164u32;
pub const ERROR_INTERNET_SHUTDOWN: u32 = 12012u32;
pub const ERROR_INTERNET_SOURCE_PORT_IN_USE: u32 = 12058u32;
pub const ERROR_INTERNET_TCPIP_NOT_INSTALLED: u32 = 12159u32;
pub const ERROR_INTERNET_TIMEOUT: u32 = 12002u32;
pub const ERROR_INTERNET_UNABLE_TO_CACHE_FILE: u32 = 12158u32;
pub const ERROR_INTERNET_UNABLE_TO_DOWNLOAD_SCRIPT: u32 = 12167u32;
pub const ERROR_INTERNET_UNRECOGNIZED_SCHEME: u32 = 12006u32;
pub const FLAGS_ERROR_UI_FILTER_FOR_ERRORS: u32 = 1u32;
pub const FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS: u32 = 2u32;
pub const FLAGS_ERROR_UI_FLAGS_GENERATE_DATA: u32 = 4u32;
pub const FLAGS_ERROR_UI_FLAGS_NO_UI: u32 = 8u32;
pub const FLAGS_ERROR_UI_SERIALIZE_DIALOGS: u32 = 16u32;
pub const FLAGS_ERROR_UI_SHOW_IDN_HOSTNAME: u32 = 32u32;
pub const FLAG_ICC_FORCE_CONNECTION: u32 = 1u32;
pub type FORTCMD = i32;
pub const FORTCMD_LOGON: FORTCMD = 1i32;
pub const FORTCMD_LOGOFF: FORTCMD = 2i32;
pub const FORTCMD_CHG_PERSONALITY: FORTCMD = 3i32;
pub type FORTSTAT = i32;
pub const FORTSTAT_INSTALLED: FORTSTAT = 1i32;
pub const FORTSTAT_LOGGEDON: FORTSTAT = 2i32;
pub type FTP_FLAGS = u32;
pub const FTP_TRANSFER_TYPE_ASCII: FTP_FLAGS = 1u32;
pub const FTP_TRANSFER_TYPE_BINARY: FTP_FLAGS = 2u32;
pub const FTP_TRANSFER_TYPE_UNKNOWN: FTP_FLAGS = 0u32;
pub const INTERNET_FLAG_TRANSFER_ASCII: FTP_FLAGS = 1u32;
pub const INTERNET_FLAG_TRANSFER_BINARY: FTP_FLAGS = 2u32;
#[repr(C)]
pub struct GOPHER_ABSTRACT_ATTRIBUTE_TYPE {
pub ShortAbstract: *mut i8,
pub AbstractFile: *mut i8,
}
impl ::core::marker::Copy for GOPHER_ABSTRACT_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_ABSTRACT_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_ADMIN_ATTRIBUTE_TYPE {
pub Comment: *mut i8,
pub EmailAddress: *mut i8,
}
impl ::core::marker::Copy for GOPHER_ADMIN_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_ADMIN_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_ASK_ATTRIBUTE_TYPE {
pub QuestionType: *mut i8,
pub QuestionText: *mut i8,
}
impl ::core::marker::Copy for GOPHER_ASK_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_ASK_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[cfg(feature = "Win32_Foundation")]
pub type GOPHER_ATTRIBUTE_ENUMERATOR = ::core::option::Option<unsafe extern "system" fn(lpattributeinfo: *const GOPHER_ATTRIBUTE_TYPE, dwerror: u32) -> super::super::Foundation::BOOL>;
pub const GOPHER_ATTRIBUTE_ID_ABSTRACT: u32 = 2882325526u32;
pub const GOPHER_ATTRIBUTE_ID_ADMIN: u32 = 2882325514u32;
pub const GOPHER_ATTRIBUTE_ID_ALL: u32 = 2882325513u32;
pub const GOPHER_ATTRIBUTE_ID_BASE: u32 = 2882325504u32;
pub const GOPHER_ATTRIBUTE_ID_GEOG: u32 = 2882325522u32;
pub const GOPHER_ATTRIBUTE_ID_LOCATION: u32 = 2882325521u32;
pub const GOPHER_ATTRIBUTE_ID_MOD_DATE: u32 = 2882325515u32;
pub const GOPHER_ATTRIBUTE_ID_ORG: u32 = 2882325520u32;
pub const GOPHER_ATTRIBUTE_ID_PROVIDER: u32 = 2882325524u32;
pub const GOPHER_ATTRIBUTE_ID_RANGE: u32 = 2882325518u32;
pub const GOPHER_ATTRIBUTE_ID_SCORE: u32 = 2882325517u32;
pub const GOPHER_ATTRIBUTE_ID_SITE: u32 = 2882325519u32;
pub const GOPHER_ATTRIBUTE_ID_TIMEZONE: u32 = 2882325523u32;
pub const GOPHER_ATTRIBUTE_ID_TREEWALK: u32 = 2882325528u32;
pub const GOPHER_ATTRIBUTE_ID_TTL: u32 = 2882325516u32;
pub const GOPHER_ATTRIBUTE_ID_UNKNOWN: u32 = 2882325529u32;
pub const GOPHER_ATTRIBUTE_ID_VERSION: u32 = 2882325525u32;
pub const GOPHER_ATTRIBUTE_ID_VIEW: u32 = 2882325527u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GOPHER_ATTRIBUTE_TYPE {
pub CategoryId: u32,
pub AttributeId: u32,
pub AttributeType: GOPHER_ATTRIBUTE_TYPE_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GOPHER_ATTRIBUTE_TYPE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GOPHER_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union GOPHER_ATTRIBUTE_TYPE_0 {
pub Admin: GOPHER_ADMIN_ATTRIBUTE_TYPE,
pub ModDate: GOPHER_MOD_DATE_ATTRIBUTE_TYPE,
pub Ttl: GOPHER_TTL_ATTRIBUTE_TYPE,
pub Score: GOPHER_SCORE_ATTRIBUTE_TYPE,
pub ScoreRange: GOPHER_SCORE_RANGE_ATTRIBUTE_TYPE,
pub Site: GOPHER_SITE_ATTRIBUTE_TYPE,
pub Organization: GOPHER_ORGANIZATION_ATTRIBUTE_TYPE,
pub Location: GOPHER_LOCATION_ATTRIBUTE_TYPE,
pub GeographicalLocation: GOPHER_GEOGRAPHICAL_LOCATION_ATTRIBUTE_TYPE,
pub TimeZone: GOPHER_TIMEZONE_ATTRIBUTE_TYPE,
pub Provider: GOPHER_PROVIDER_ATTRIBUTE_TYPE,
pub Version: GOPHER_VERSION_ATTRIBUTE_TYPE,
pub Abstract: GOPHER_ABSTRACT_ATTRIBUTE_TYPE,
pub View: GOPHER_VIEW_ATTRIBUTE_TYPE,
pub Veronica: GOPHER_VERONICA_ATTRIBUTE_TYPE,
pub Ask: GOPHER_ASK_ATTRIBUTE_TYPE,
pub Unknown: GOPHER_UNKNOWN_ATTRIBUTE_TYPE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GOPHER_ATTRIBUTE_TYPE_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GOPHER_ATTRIBUTE_TYPE_0 {
fn clone(&self) -> Self {
*self
}
}
pub const GOPHER_CATEGORY_ID_ABSTRACT: u32 = 2882325509u32;
pub const GOPHER_CATEGORY_ID_ADMIN: u32 = 2882325507u32;
pub const GOPHER_CATEGORY_ID_ALL: u32 = 2882325505u32;
pub const GOPHER_CATEGORY_ID_ASK: u32 = 2882325511u32;
pub const GOPHER_CATEGORY_ID_INFO: u32 = 2882325506u32;
pub const GOPHER_CATEGORY_ID_UNKNOWN: u32 = 2882325512u32;
pub const GOPHER_CATEGORY_ID_VERONICA: u32 = 2882325510u32;
pub const GOPHER_CATEGORY_ID_VIEWS: u32 = 2882325508u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GOPHER_FIND_DATAA {
pub DisplayString: [super::super::Foundation::CHAR; 129],
pub GopherType: GOPHER_TYPE,
pub SizeLow: u32,
pub SizeHigh: u32,
pub LastModificationTime: super::super::Foundation::FILETIME,
pub Locator: [super::super::Foundation::CHAR; 654],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GOPHER_FIND_DATAA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GOPHER_FIND_DATAA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GOPHER_FIND_DATAW {
pub DisplayString: [u16; 129],
pub GopherType: GOPHER_TYPE,
pub SizeLow: u32,
pub SizeHigh: u32,
pub LastModificationTime: super::super::Foundation::FILETIME,
pub Locator: [u16; 654],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GOPHER_FIND_DATAW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GOPHER_FIND_DATAW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_GEOGRAPHICAL_LOCATION_ATTRIBUTE_TYPE {
pub DegreesNorth: i32,
pub MinutesNorth: i32,
pub SecondsNorth: i32,
pub DegreesEast: i32,
pub MinutesEast: i32,
pub SecondsEast: i32,
}
impl ::core::marker::Copy for GOPHER_GEOGRAPHICAL_LOCATION_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_GEOGRAPHICAL_LOCATION_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_LOCATION_ATTRIBUTE_TYPE {
pub Location: *mut i8,
}
impl ::core::marker::Copy for GOPHER_LOCATION_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_LOCATION_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GOPHER_MOD_DATE_ATTRIBUTE_TYPE {
pub DateAndTime: super::super::Foundation::FILETIME,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GOPHER_MOD_DATE_ATTRIBUTE_TYPE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GOPHER_MOD_DATE_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_ORGANIZATION_ATTRIBUTE_TYPE {
pub Organization: *mut i8,
}
impl ::core::marker::Copy for GOPHER_ORGANIZATION_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_ORGANIZATION_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_PROVIDER_ATTRIBUTE_TYPE {
pub Provider: *mut i8,
}
impl ::core::marker::Copy for GOPHER_PROVIDER_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_PROVIDER_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_SCORE_ATTRIBUTE_TYPE {
pub Score: i32,
}
impl ::core::marker::Copy for GOPHER_SCORE_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_SCORE_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_SCORE_RANGE_ATTRIBUTE_TYPE {
pub LowerBound: i32,
pub UpperBound: i32,
}
impl ::core::marker::Copy for GOPHER_SCORE_RANGE_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_SCORE_RANGE_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_SITE_ATTRIBUTE_TYPE {
pub Site: *mut i8,
}
impl ::core::marker::Copy for GOPHER_SITE_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_SITE_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_TIMEZONE_ATTRIBUTE_TYPE {
pub Zone: i32,
}
impl ::core::marker::Copy for GOPHER_TIMEZONE_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_TIMEZONE_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_TTL_ATTRIBUTE_TYPE {
pub Ttl: u32,
}
impl ::core::marker::Copy for GOPHER_TTL_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_TTL_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
pub type GOPHER_TYPE = u32;
pub const GOPHER_TYPE_ASK: GOPHER_TYPE = 1073741824u32;
pub const GOPHER_TYPE_BINARY: GOPHER_TYPE = 512u32;
pub const GOPHER_TYPE_BITMAP: GOPHER_TYPE = 16384u32;
pub const GOPHER_TYPE_CALENDAR: GOPHER_TYPE = 524288u32;
pub const GOPHER_TYPE_CSO: GOPHER_TYPE = 4u32;
pub const GOPHER_TYPE_DIRECTORY: GOPHER_TYPE = 2u32;
pub const GOPHER_TYPE_DOS_ARCHIVE: GOPHER_TYPE = 32u32;
pub const GOPHER_TYPE_ERROR: GOPHER_TYPE = 8u32;
pub const GOPHER_TYPE_GIF: GOPHER_TYPE = 4096u32;
pub const GOPHER_TYPE_GOPHER_PLUS: GOPHER_TYPE = 2147483648u32;
pub const GOPHER_TYPE_HTML: GOPHER_TYPE = 131072u32;
pub const GOPHER_TYPE_IMAGE: GOPHER_TYPE = 8192u32;
pub const GOPHER_TYPE_INDEX_SERVER: GOPHER_TYPE = 128u32;
pub const GOPHER_TYPE_INLINE: GOPHER_TYPE = 1048576u32;
pub const GOPHER_TYPE_MAC_BINHEX: GOPHER_TYPE = 16u32;
pub const GOPHER_TYPE_MOVIE: GOPHER_TYPE = 32768u32;
pub const GOPHER_TYPE_PDF: GOPHER_TYPE = 262144u32;
pub const GOPHER_TYPE_REDUNDANT: GOPHER_TYPE = 1024u32;
pub const GOPHER_TYPE_SOUND: GOPHER_TYPE = 65536u32;
pub const GOPHER_TYPE_TELNET: GOPHER_TYPE = 256u32;
pub const GOPHER_TYPE_TEXT_FILE: GOPHER_TYPE = 1u32;
pub const GOPHER_TYPE_TN3270: GOPHER_TYPE = 2048u32;
pub const GOPHER_TYPE_UNIX_UUENCODED: GOPHER_TYPE = 64u32;
pub const GOPHER_TYPE_UNKNOWN: GOPHER_TYPE = 536870912u32;
#[repr(C)]
pub struct GOPHER_UNKNOWN_ATTRIBUTE_TYPE {
pub Text: *mut i8,
}
impl ::core::marker::Copy for GOPHER_UNKNOWN_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_UNKNOWN_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct GOPHER_VERONICA_ATTRIBUTE_TYPE {
pub TreeWalk: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for GOPHER_VERONICA_ATTRIBUTE_TYPE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for GOPHER_VERONICA_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_VERSION_ATTRIBUTE_TYPE {
pub Version: *mut i8,
}
impl ::core::marker::Copy for GOPHER_VERSION_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_VERSION_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct GOPHER_VIEW_ATTRIBUTE_TYPE {
pub ContentType: *mut i8,
pub Language: *mut i8,
pub Size: u32,
}
impl ::core::marker::Copy for GOPHER_VIEW_ATTRIBUTE_TYPE {}
impl ::core::clone::Clone for GOPHER_VIEW_ATTRIBUTE_TYPE {
fn clone(&self) -> Self {
*self
}
}
pub const GROUPNAME_MAX_LENGTH: u32 = 120u32;
pub const GROUP_OWNER_STORAGE_SIZE: u32 = 4u32;
pub const HSR_ASYNC: u32 = 1u32;
pub const HSR_CHUNKED: u32 = 32u32;
pub const HSR_DOWNLOAD: u32 = 16u32;
pub const HSR_INITIATE: u32 = 8u32;
pub const HSR_SYNC: u32 = 4u32;
pub const HSR_USE_CONTEXT: u32 = 8u32;
pub const HTTP_1_1_CACHE_ENTRY: u32 = 64u32;
pub type HTTP_ADDREQ_FLAG = u32;
pub const HTTP_ADDREQ_FLAG_ADD: HTTP_ADDREQ_FLAG = 536870912u32;
pub const HTTP_ADDREQ_FLAG_ADD_IF_NEW: HTTP_ADDREQ_FLAG = 268435456u32;
pub const HTTP_ADDREQ_FLAG_COALESCE: HTTP_ADDREQ_FLAG = 1073741824u32;
pub const HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA: HTTP_ADDREQ_FLAG = 1073741824u32;
pub const HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON: HTTP_ADDREQ_FLAG = 16777216u32;
pub const HTTP_ADDREQ_FLAG_REPLACE: HTTP_ADDREQ_FLAG = 2147483648u32;
pub const HTTP_ADDREQ_FLAGS_MASK: u32 = 4294901760u32;
pub const HTTP_ADDREQ_FLAG_ALLOW_EMPTY_VALUES: u32 = 67108864u32;
pub const HTTP_ADDREQ_FLAG_RESPONSE_HEADERS: u32 = 33554432u32;
pub const HTTP_ADDREQ_INDEX_MASK: u32 = 65535u32;
pub const HTTP_COOKIES_SAME_SITE_LEVEL_CROSS_SITE: u32 = 3u32;
pub const HTTP_COOKIES_SAME_SITE_LEVEL_CROSS_SITE_LAX: u32 = 2u32;
pub const HTTP_COOKIES_SAME_SITE_LEVEL_MAX: u32 = 3u32;
pub const HTTP_COOKIES_SAME_SITE_LEVEL_SAME_SITE: u32 = 1u32;
pub const HTTP_COOKIES_SAME_SITE_LEVEL_UNKNOWN: u32 = 0u32;
pub const HTTP_MAJOR_VERSION: u32 = 1u32;
pub const HTTP_MINOR_VERSION: u32 = 0u32;
pub type HTTP_POLICY_EXTENSION_INIT = ::core::option::Option<unsafe extern "system" fn(version: HTTP_POLICY_EXTENSION_VERSION, r#type: HTTP_POLICY_EXTENSION_TYPE, pvdata: *const ::core::ffi::c_void, cbdata: u32) -> u32>;
pub type HTTP_POLICY_EXTENSION_SHUTDOWN = ::core::option::Option<unsafe extern "system" fn(r#type: HTTP_POLICY_EXTENSION_TYPE) -> u32>;
pub type HTTP_POLICY_EXTENSION_TYPE = i32;
pub const POLICY_EXTENSION_TYPE_NONE: HTTP_POLICY_EXTENSION_TYPE = 0i32;
pub const POLICY_EXTENSION_TYPE_WINHTTP: HTTP_POLICY_EXTENSION_TYPE = 1i32;
pub const POLICY_EXTENSION_TYPE_WININET: HTTP_POLICY_EXTENSION_TYPE = 2i32;
pub type HTTP_POLICY_EXTENSION_VERSION = i32;
pub const POLICY_EXTENSION_VERSION1: HTTP_POLICY_EXTENSION_VERSION = 1i32;
pub const HTTP_PROTOCOL_FLAG_HTTP2: u32 = 2u32;
pub const HTTP_PROTOCOL_MASK: u32 = 2u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct HTTP_PUSH_NOTIFICATION_STATUS {
pub ChannelStatusValid: super::super::Foundation::BOOL,
pub ChannelStatus: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for HTTP_PUSH_NOTIFICATION_STATUS {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for HTTP_PUSH_NOTIFICATION_STATUS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct HTTP_PUSH_TRANSPORT_SETTING {
pub TransportSettingId: ::windows_sys::core::GUID,
pub BrokerEventId: ::windows_sys::core::GUID,
}
impl ::core::marker::Copy for HTTP_PUSH_TRANSPORT_SETTING {}
impl ::core::clone::Clone for HTTP_PUSH_TRANSPORT_SETTING {
fn clone(&self) -> Self {
*self
}
}
pub type HTTP_PUSH_WAIT_HANDLE = isize;
pub type HTTP_PUSH_WAIT_TYPE = i32;
pub const HttpPushWaitEnableComplete: HTTP_PUSH_WAIT_TYPE = 0i32;
pub const HttpPushWaitReceiveComplete: HTTP_PUSH_WAIT_TYPE = 1i32;
pub const HttpPushWaitSendComplete: HTTP_PUSH_WAIT_TYPE = 2i32;
pub const HTTP_QUERY_ACCEPT: u32 = 24u32;
pub const HTTP_QUERY_ACCEPT_CHARSET: u32 = 25u32;
pub const HTTP_QUERY_ACCEPT_ENCODING: u32 = 26u32;
pub const HTTP_QUERY_ACCEPT_LANGUAGE: u32 = 27u32;
pub const HTTP_QUERY_ACCEPT_RANGES: u32 = 42u32;
pub const HTTP_QUERY_AGE: u32 = 48u32;
pub const HTTP_QUERY_ALLOW: u32 = 7u32;
pub const HTTP_QUERY_AUTHENTICATION_INFO: u32 = 76u32;
pub const HTTP_QUERY_AUTHORIZATION: u32 = 28u32;
pub const HTTP_QUERY_CACHE_CONTROL: u32 = 49u32;
pub const HTTP_QUERY_CONNECTION: u32 = 23u32;
pub const HTTP_QUERY_CONTENT_BASE: u32 = 50u32;
pub const HTTP_QUERY_CONTENT_DESCRIPTION: u32 = 4u32;
pub const HTTP_QUERY_CONTENT_DISPOSITION: u32 = 47u32;
pub const HTTP_QUERY_CONTENT_ENCODING: u32 = 29u32;
pub const HTTP_QUERY_CONTENT_ID: u32 = 3u32;
pub const HTTP_QUERY_CONTENT_LANGUAGE: u32 = 6u32;
pub const HTTP_QUERY_CONTENT_LENGTH: u32 = 5u32;
pub const HTTP_QUERY_CONTENT_LOCATION: u32 = 51u32;
pub const HTTP_QUERY_CONTENT_MD5: u32 = 52u32;
pub const HTTP_QUERY_CONTENT_RANGE: u32 = 53u32;
pub const HTTP_QUERY_CONTENT_TRANSFER_ENCODING: u32 = 2u32;
pub const HTTP_QUERY_CONTENT_TYPE: u32 = 1u32;
pub const HTTP_QUERY_COOKIE: u32 = 44u32;
pub const HTTP_QUERY_COST: u32 = 15u32;
pub const HTTP_QUERY_CUSTOM: u32 = 65535u32;
pub const HTTP_QUERY_DATE: u32 = 9u32;
pub const HTTP_QUERY_DEFAULT_STYLE: u32 = 84u32;
pub const HTTP_QUERY_DERIVED_FROM: u32 = 14u32;
pub const HTTP_QUERY_DO_NOT_TRACK: u32 = 88u32;
pub const HTTP_QUERY_ECHO_HEADERS: u32 = 73u32;
pub const HTTP_QUERY_ECHO_HEADERS_CRLF: u32 = 74u32;
pub const HTTP_QUERY_ECHO_REPLY: u32 = 72u32;
pub const HTTP_QUERY_ECHO_REQUEST: u32 = 71u32;
pub const HTTP_QUERY_ETAG: u32 = 54u32;
pub const HTTP_QUERY_EXPECT: u32 = 68u32;
pub const HTTP_QUERY_EXPIRES: u32 = 10u32;
pub const HTTP_QUERY_FLAG_COALESCE: u32 = 268435456u32;
pub const HTTP_QUERY_FLAG_COALESCE_WITH_COMMA: u32 = 67108864u32;
pub const HTTP_QUERY_FLAG_NUMBER: u32 = 536870912u32;
pub const HTTP_QUERY_FLAG_NUMBER64: u32 = 134217728u32;
pub const HTTP_QUERY_FLAG_REQUEST_HEADERS: u32 = 2147483648u32;
pub const HTTP_QUERY_FLAG_SYSTEMTIME: u32 = 1073741824u32;
pub const HTTP_QUERY_FORWARDED: u32 = 30u32;
pub const HTTP_QUERY_FROM: u32 = 31u32;
pub const HTTP_QUERY_HOST: u32 = 55u32;
pub const HTTP_QUERY_HTTP2_SETTINGS: u32 = 90u32;
pub const HTTP_QUERY_IF_MATCH: u32 = 56u32;
pub const HTTP_QUERY_IF_MODIFIED_SINCE: u32 = 32u32;
pub const HTTP_QUERY_IF_NONE_MATCH: u32 = 57u32;
pub const HTTP_QUERY_IF_RANGE: u32 = 58u32;
pub const HTTP_QUERY_IF_UNMODIFIED_SINCE: u32 = 59u32;
pub const HTTP_QUERY_INCLUDE_REFERER_TOKEN_BINDING_ID: u32 = 93u32;
pub const HTTP_QUERY_INCLUDE_REFERRED_TOKEN_BINDING_ID: u32 = 93u32;
pub const HTTP_QUERY_KEEP_ALIVE: u32 = 89u32;
pub const HTTP_QUERY_LAST_MODIFIED: u32 = 11u32;
pub const HTTP_QUERY_LINK: u32 = 16u32;
pub const HTTP_QUERY_LOCATION: u32 = 33u32;
pub const HTTP_QUERY_MAX: u32 = 95u32;
pub const HTTP_QUERY_MAX_FORWARDS: u32 = 60u32;
pub const HTTP_QUERY_MESSAGE_ID: u32 = 12u32;
pub const HTTP_QUERY_MIME_VERSION: u32 = 0u32;
pub const HTTP_QUERY_ORIG_URI: u32 = 34u32;
pub const HTTP_QUERY_P3P: u32 = 80u32;
pub const HTTP_QUERY_PASSPORT_CONFIG: u32 = 78u32;
pub const HTTP_QUERY_PASSPORT_URLS: u32 = 77u32;
pub const HTTP_QUERY_PRAGMA: u32 = 17u32;
pub const HTTP_QUERY_PROXY_AUTHENTICATE: u32 = 41u32;
pub const HTTP_QUERY_PROXY_AUTHORIZATION: u32 = 61u32;
pub const HTTP_QUERY_PROXY_CONNECTION: u32 = 69u32;
pub const HTTP_QUERY_PROXY_SUPPORT: u32 = 75u32;
pub const HTTP_QUERY_PUBLIC: u32 = 8u32;
pub const HTTP_QUERY_PUBLIC_KEY_PINS: u32 = 94u32;
pub const HTTP_QUERY_PUBLIC_KEY_PINS_REPORT_ONLY: u32 = 95u32;
pub const HTTP_QUERY_RANGE: u32 = 62u32;
pub const HTTP_QUERY_RAW_HEADERS: u32 = 21u32;
pub const HTTP_QUERY_RAW_HEADERS_CRLF: u32 = 22u32;
pub const HTTP_QUERY_REFERER: u32 = 35u32;
pub const HTTP_QUERY_REFRESH: u32 = 46u32;
pub const HTTP_QUERY_REQUEST_METHOD: u32 = 45u32;
pub const HTTP_QUERY_RETRY_AFTER: u32 = 36u32;
pub const HTTP_QUERY_SERVER: u32 = 37u32;
pub const HTTP_QUERY_SET_COOKIE: u32 = 43u32;
pub const HTTP_QUERY_SET_COOKIE2: u32 = 87u32;
pub const HTTP_QUERY_STATUS_CODE: u32 = 19u32;
pub const HTTP_QUERY_STATUS_TEXT: u32 = 20u32;
pub const HTTP_QUERY_STRICT_TRANSPORT_SECURITY: u32 = 91u32;
pub const HTTP_QUERY_TITLE: u32 = 38u32;
pub const HTTP_QUERY_TOKEN_BINDING: u32 = 92u32;
pub const HTTP_QUERY_TRANSFER_ENCODING: u32 = 63u32;
pub const HTTP_QUERY_TRANSLATE: u32 = 82u32;
pub const HTTP_QUERY_UNLESS_MODIFIED_SINCE: u32 = 70u32;
pub const HTTP_QUERY_UPGRADE: u32 = 64u32;
pub const HTTP_QUERY_URI: u32 = 13u32;
pub const HTTP_QUERY_USER_AGENT: u32 = 39u32;
pub const HTTP_QUERY_VARY: u32 = 65u32;
pub const HTTP_QUERY_VERSION: u32 = 18u32;
pub const HTTP_QUERY_VIA: u32 = 66u32;
pub const HTTP_QUERY_WARNING: u32 = 67u32;
pub const HTTP_QUERY_WWW_AUTHENTICATE: u32 = 40u32;
pub const HTTP_QUERY_X_CONTENT_TYPE_OPTIONS: u32 = 79u32;
pub const HTTP_QUERY_X_FRAME_OPTIONS: u32 = 85u32;
pub const HTTP_QUERY_X_P2P_PEERDIST: u32 = 81u32;
pub const HTTP_QUERY_X_UA_COMPATIBLE: u32 = 83u32;
pub const HTTP_QUERY_X_XSS_PROTECTION: u32 = 86u32;
#[repr(C)]
pub struct HTTP_REQUEST_TIMES {
pub cTimes: u32,
pub rgTimes: [u64; 32],
}
impl ::core::marker::Copy for HTTP_REQUEST_TIMES {}
impl ::core::clone::Clone for HTTP_REQUEST_TIMES {
fn clone(&self) -> Self {
*self
}
}
pub const HTTP_STATUS_MISDIRECTED_REQUEST: u32 = 421u32;
#[repr(C)]
pub struct HTTP_WEB_SOCKET_ASYNC_RESULT {
pub AsyncResult: INTERNET_ASYNC_RESULT,
pub Operation: HTTP_WEB_SOCKET_OPERATION,
pub BufferType: HTTP_WEB_SOCKET_BUFFER_TYPE,
pub dwBytesTransferred: u32,
}
impl ::core::marker::Copy for HTTP_WEB_SOCKET_ASYNC_RESULT {}
impl ::core::clone::Clone for HTTP_WEB_SOCKET_ASYNC_RESULT {
fn clone(&self) -> Self {
*self
}
}
pub type HTTP_WEB_SOCKET_BUFFER_TYPE = i32;
pub const HTTP_WEB_SOCKET_BINARY_MESSAGE_TYPE: HTTP_WEB_SOCKET_BUFFER_TYPE = 0i32;
pub const HTTP_WEB_SOCKET_BINARY_FRAGMENT_TYPE: HTTP_WEB_SOCKET_BUFFER_TYPE = 1i32;
pub const HTTP_WEB_SOCKET_UTF8_MESSAGE_TYPE: HTTP_WEB_SOCKET_BUFFER_TYPE = 2i32;
pub const HTTP_WEB_SOCKET_UTF8_FRAGMENT_TYPE: HTTP_WEB_SOCKET_BUFFER_TYPE = 3i32;
pub const HTTP_WEB_SOCKET_CLOSE_TYPE: HTTP_WEB_SOCKET_BUFFER_TYPE = 4i32;
pub const HTTP_WEB_SOCKET_PING_TYPE: HTTP_WEB_SOCKET_BUFFER_TYPE = 5i32;
pub type HTTP_WEB_SOCKET_CLOSE_STATUS = i32;
pub const HTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1000i32;
pub const HTTP_WEB_SOCKET_ENDPOINT_TERMINATED_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1001i32;
pub const HTTP_WEB_SOCKET_PROTOCOL_ERROR_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1002i32;
pub const HTTP_WEB_SOCKET_INVALID_DATA_TYPE_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1003i32;
pub const HTTP_WEB_SOCKET_EMPTY_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1005i32;
pub const HTTP_WEB_SOCKET_ABORTED_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1006i32;
pub const HTTP_WEB_SOCKET_INVALID_PAYLOAD_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1007i32;
pub const HTTP_WEB_SOCKET_POLICY_VIOLATION_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1008i32;
pub const HTTP_WEB_SOCKET_MESSAGE_TOO_BIG_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1009i32;
pub const HTTP_WEB_SOCKET_UNSUPPORTED_EXTENSIONS_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1010i32;
pub const HTTP_WEB_SOCKET_SERVER_ERROR_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1011i32;
pub const HTTP_WEB_SOCKET_SECURE_HANDSHAKE_ERROR_CLOSE_STATUS: HTTP_WEB_SOCKET_CLOSE_STATUS = 1015i32;
pub const HTTP_WEB_SOCKET_MAX_CLOSE_REASON_LENGTH: u32 = 123u32;
pub const HTTP_WEB_SOCKET_MIN_KEEPALIVE_VALUE: u32 = 10000u32;
pub type HTTP_WEB_SOCKET_OPERATION = i32;
pub const HTTP_WEB_SOCKET_SEND_OPERATION: HTTP_WEB_SOCKET_OPERATION = 0i32;
pub const HTTP_WEB_SOCKET_RECEIVE_OPERATION: HTTP_WEB_SOCKET_OPERATION = 1i32;
pub const HTTP_WEB_SOCKET_CLOSE_OPERATION: HTTP_WEB_SOCKET_OPERATION = 2i32;
pub const HTTP_WEB_SOCKET_SHUTDOWN_OPERATION: HTTP_WEB_SOCKET_OPERATION = 3i32;
pub const ICU_USERNAME: u32 = 1073741824u32;
pub const IDENTITY_CACHE_ENTRY: u32 = 2147483648u32;
pub const IDSI_FLAG_KEEP_ALIVE: u32 = 1u32;
pub const IDSI_FLAG_PROXY: u32 = 4u32;
pub const IDSI_FLAG_SECURE: u32 = 2u32;
pub const IDSI_FLAG_TUNNEL: u32 = 8u32;
pub type IDialBranding = *mut ::core::ffi::c_void;
pub type IDialEngine = *mut ::core::ffi::c_void;
pub type IDialEventSink = *mut ::core::ffi::c_void;
pub const IMMUTABLE_CACHE_ENTRY: u32 = 524288u32;
pub const INSTALLED_CACHE_ENTRY: u32 = 268435456u32;
pub const INTERENT_GOONLINE_MASK: u32 = 3u32;
pub const INTERENT_GOONLINE_NOPROMPT: u32 = 2u32;
pub const INTERENT_GOONLINE_REFRESH: u32 = 1u32;
pub type INTERNET_ACCESS_TYPE = u32;
pub const INTERNET_OPEN_TYPE_DIRECT: INTERNET_ACCESS_TYPE = 1u32;
pub const INTERNET_OPEN_TYPE_PRECONFIG: INTERNET_ACCESS_TYPE = 0u32;
pub const INTERNET_OPEN_TYPE_PROXY: INTERNET_ACCESS_TYPE = 3u32;
#[repr(C)]
pub struct INTERNET_ASYNC_RESULT {
pub dwResult: usize,
pub dwError: u32,
}
impl ::core::marker::Copy for INTERNET_ASYNC_RESULT {}
impl ::core::clone::Clone for INTERNET_ASYNC_RESULT {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct INTERNET_AUTH_NOTIFY_DATA {
pub cbStruct: u32,
pub dwOptions: u32,
pub pfnNotify: PFN_AUTH_NOTIFY,
pub dwContext: usize,
}
impl ::core::marker::Copy for INTERNET_AUTH_NOTIFY_DATA {}
impl ::core::clone::Clone for INTERNET_AUTH_NOTIFY_DATA {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_AUTH_SCHEME_BASIC: u32 = 0u32;
pub const INTERNET_AUTH_SCHEME_DIGEST: u32 = 1u32;
pub const INTERNET_AUTH_SCHEME_KERBEROS: u32 = 3u32;
pub const INTERNET_AUTH_SCHEME_NEGOTIATE: u32 = 4u32;
pub const INTERNET_AUTH_SCHEME_NTLM: u32 = 2u32;
pub const INTERNET_AUTH_SCHEME_PASSPORT: u32 = 5u32;
pub const INTERNET_AUTH_SCHEME_UNKNOWN: u32 = 6u32;
pub type INTERNET_AUTODIAL = u32;
pub const INTERNET_AUTODIAL_FAILIFSECURITYCHECK: INTERNET_AUTODIAL = 4u32;
pub const INTERNET_AUTODIAL_FORCE_ONLINE: INTERNET_AUTODIAL = 1u32;
pub const INTERNET_AUTODIAL_FORCE_UNATTENDED: INTERNET_AUTODIAL = 2u32;
pub const INTERNET_AUTODIAL_OVERRIDE_NET_PRESENT: INTERNET_AUTODIAL = 8u32;
pub const INTERNET_AUTOPROXY_INIT_DEFAULT: u32 = 1u32;
pub const INTERNET_AUTOPROXY_INIT_DOWNLOADSYNC: u32 = 2u32;
pub const INTERNET_AUTOPROXY_INIT_ONLYQUERY: u32 = 8u32;
pub const INTERNET_AUTOPROXY_INIT_QUERYSTATE: u32 = 4u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_BUFFERSA {
pub dwStructSize: u32,
pub Next: *mut INTERNET_BUFFERSA,
pub lpcszHeader: super::super::Foundation::PSTR,
pub dwHeadersLength: u32,
pub dwHeadersTotal: u32,
pub lpvBuffer: *mut ::core::ffi::c_void,
pub dwBufferLength: u32,
pub dwBufferTotal: u32,
pub dwOffsetLow: u32,
pub dwOffsetHigh: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_BUFFERSA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_BUFFERSA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_BUFFERSW {
pub dwStructSize: u32,
pub Next: *mut INTERNET_BUFFERSW,
pub lpcszHeader: super::super::Foundation::PWSTR,
pub dwHeadersLength: u32,
pub dwHeadersTotal: u32,
pub lpvBuffer: *mut ::core::ffi::c_void,
pub dwBufferLength: u32,
pub dwBufferTotal: u32,
pub dwOffsetLow: u32,
pub dwOffsetHigh: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_BUFFERSW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_BUFFERSW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_CONFIG_INFOA {
pub dwStructSize: u32,
pub dwContainer: u32,
pub dwQuota: u32,
pub dwReserved4: u32,
pub fPerUser: super::super::Foundation::BOOL,
pub dwSyncMode: u32,
pub dwNumCachePaths: u32,
pub Anonymous: INTERNET_CACHE_CONFIG_INFOA_0,
pub dwNormalUsage: u32,
pub dwExemptUsage: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_INFOA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_INFOA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INTERNET_CACHE_CONFIG_INFOA_0 {
pub Anonymous: INTERNET_CACHE_CONFIG_INFOA_0_0,
pub CachePaths: [INTERNET_CACHE_CONFIG_PATH_ENTRYA; 1],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_INFOA_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_INFOA_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_CONFIG_INFOA_0_0 {
pub CachePath: [super::super::Foundation::CHAR; 260],
pub dwCacheSize: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_INFOA_0_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_INFOA_0_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_CONFIG_INFOW {
pub dwStructSize: u32,
pub dwContainer: u32,
pub dwQuota: u32,
pub dwReserved4: u32,
pub fPerUser: super::super::Foundation::BOOL,
pub dwSyncMode: u32,
pub dwNumCachePaths: u32,
pub Anonymous: INTERNET_CACHE_CONFIG_INFOW_0,
pub dwNormalUsage: u32,
pub dwExemptUsage: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_INFOW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_INFOW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INTERNET_CACHE_CONFIG_INFOW_0 {
pub Anonymous: INTERNET_CACHE_CONFIG_INFOW_0_0,
pub CachePaths: [INTERNET_CACHE_CONFIG_PATH_ENTRYW; 1],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_INFOW_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_INFOW_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_CONFIG_INFOW_0_0 {
pub CachePath: [u16; 260],
pub dwCacheSize: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_INFOW_0_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_INFOW_0_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_CONFIG_PATH_ENTRYA {
pub CachePath: [super::super::Foundation::CHAR; 260],
pub dwCacheSize: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_PATH_ENTRYA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_PATH_ENTRYA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct INTERNET_CACHE_CONFIG_PATH_ENTRYW {
pub CachePath: [u16; 260],
pub dwCacheSize: u32,
}
impl ::core::marker::Copy for INTERNET_CACHE_CONFIG_PATH_ENTRYW {}
impl ::core::clone::Clone for INTERNET_CACHE_CONFIG_PATH_ENTRYW {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_CACHE_CONTAINER_AUTODELETE: u32 = 2u32;
pub const INTERNET_CACHE_CONTAINER_BLOOM_FILTER: u32 = 32u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_CONTAINER_INFOA {
pub dwCacheVersion: u32,
pub lpszName: super::super::Foundation::PSTR,
pub lpszCachePrefix: super::super::Foundation::PSTR,
pub lpszVolumeLabel: super::super::Foundation::PSTR,
pub lpszVolumeTitle: super::super::Foundation::PSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONTAINER_INFOA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONTAINER_INFOA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_CONTAINER_INFOW {
pub dwCacheVersion: u32,
pub lpszName: super::super::Foundation::PWSTR,
pub lpszCachePrefix: super::super::Foundation::PWSTR,
pub lpszVolumeLabel: super::super::Foundation::PWSTR,
pub lpszVolumeTitle: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_CONTAINER_INFOW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_CONTAINER_INFOW {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_CACHE_CONTAINER_MAP_ENABLED: u32 = 16u32;
pub const INTERNET_CACHE_CONTAINER_NODESKTOPINIT: u32 = 8u32;
pub const INTERNET_CACHE_CONTAINER_NOSUBDIRS: u32 = 1u32;
pub const INTERNET_CACHE_CONTAINER_RESERVED1: u32 = 4u32;
pub const INTERNET_CACHE_CONTAINER_SHARE_READ: u32 = 256u32;
pub const INTERNET_CACHE_CONTAINER_SHARE_READ_WRITE: u32 = 768u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_ENTRY_INFOA {
pub dwStructSize: u32,
pub lpszSourceUrlName: super::super::Foundation::PSTR,
pub lpszLocalFileName: super::super::Foundation::PSTR,
pub CacheEntryType: u32,
pub dwUseCount: u32,
pub dwHitRate: u32,
pub dwSizeLow: u32,
pub dwSizeHigh: u32,
pub LastModifiedTime: super::super::Foundation::FILETIME,
pub ExpireTime: super::super::Foundation::FILETIME,
pub LastAccessTime: super::super::Foundation::FILETIME,
pub LastSyncTime: super::super::Foundation::FILETIME,
pub lpHeaderInfo: super::super::Foundation::PSTR,
pub dwHeaderInfoSize: u32,
pub lpszFileExtension: super::super::Foundation::PSTR,
pub Anonymous: INTERNET_CACHE_ENTRY_INFOA_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_ENTRY_INFOA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_ENTRY_INFOA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INTERNET_CACHE_ENTRY_INFOA_0 {
pub dwReserved: u32,
pub dwExemptDelta: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_ENTRY_INFOA_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_ENTRY_INFOA_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_ENTRY_INFOW {
pub dwStructSize: u32,
pub lpszSourceUrlName: super::super::Foundation::PWSTR,
pub lpszLocalFileName: super::super::Foundation::PWSTR,
pub CacheEntryType: u32,
pub dwUseCount: u32,
pub dwHitRate: u32,
pub dwSizeLow: u32,
pub dwSizeHigh: u32,
pub LastModifiedTime: super::super::Foundation::FILETIME,
pub ExpireTime: super::super::Foundation::FILETIME,
pub LastAccessTime: super::super::Foundation::FILETIME,
pub LastSyncTime: super::super::Foundation::FILETIME,
pub lpHeaderInfo: super::super::Foundation::PWSTR,
pub dwHeaderInfoSize: u32,
pub lpszFileExtension: super::super::Foundation::PWSTR,
pub Anonymous: INTERNET_CACHE_ENTRY_INFOW_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_ENTRY_INFOW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_ENTRY_INFOW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INTERNET_CACHE_ENTRY_INFOW_0 {
pub dwReserved: u32,
pub dwExemptDelta: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_ENTRY_INFOW_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_ENTRY_INFOW_0 {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_CACHE_FLAG_ADD_FILENAME_ONLY: u32 = 2048u32;
pub const INTERNET_CACHE_FLAG_ALLOW_COLLISIONS: u32 = 256u32;
pub const INTERNET_CACHE_FLAG_ENTRY_OR_MAPPING: u32 = 1024u32;
pub const INTERNET_CACHE_FLAG_GET_STRUCT_ONLY: u32 = 4096u32;
pub const INTERNET_CACHE_FLAG_INSTALLED_ENTRY: u32 = 512u32;
pub const INTERNET_CACHE_GROUP_ADD: u32 = 0u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_GROUP_INFOA {
pub dwGroupSize: u32,
pub dwGroupFlags: u32,
pub dwGroupType: u32,
pub dwDiskUsage: u32,
pub dwDiskQuota: u32,
pub dwOwnerStorage: [u32; 4],
pub szGroupName: [super::super::Foundation::CHAR; 120],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_GROUP_INFOA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_GROUP_INFOA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct INTERNET_CACHE_GROUP_INFOW {
pub dwGroupSize: u32,
pub dwGroupFlags: u32,
pub dwGroupType: u32,
pub dwDiskUsage: u32,
pub dwDiskQuota: u32,
pub dwOwnerStorage: [u32; 4],
pub szGroupName: [u16; 120],
}
impl ::core::marker::Copy for INTERNET_CACHE_GROUP_INFOW {}
impl ::core::clone::Clone for INTERNET_CACHE_GROUP_INFOW {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_CACHE_GROUP_REMOVE: u32 = 1u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CACHE_TIMESTAMPS {
pub ftExpires: super::super::Foundation::FILETIME,
pub ftLastModified: super::super::Foundation::FILETIME,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CACHE_TIMESTAMPS {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CACHE_TIMESTAMPS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CALLBACK_COOKIE {
pub pcwszName: super::super::Foundation::PWSTR,
pub pcwszValue: super::super::Foundation::PWSTR,
pub pcwszDomain: super::super::Foundation::PWSTR,
pub pcwszPath: super::super::Foundation::PWSTR,
pub ftExpires: super::super::Foundation::FILETIME,
pub dwFlags: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CALLBACK_COOKIE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CALLBACK_COOKIE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CERTIFICATE_INFO {
pub ftExpiry: super::super::Foundation::FILETIME,
pub ftStart: super::super::Foundation::FILETIME,
pub lpszSubjectInfo: *mut i8,
pub lpszIssuerInfo: *mut i8,
pub lpszProtocolName: *mut i8,
pub lpszSignatureAlgName: *mut i8,
pub lpszEncryptionAlgName: *mut i8,
pub dwKeySize: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CERTIFICATE_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CERTIFICATE_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct INTERNET_CONNECTED_INFO {
pub dwConnectedState: INTERNET_STATE,
pub dwFlags: u32,
}
impl ::core::marker::Copy for INTERNET_CONNECTED_INFO {}
impl ::core::clone::Clone for INTERNET_CONNECTED_INFO {
fn clone(&self) -> Self {
*self
}
}
pub type INTERNET_CONNECTION = u32;
pub const INTERNET_CONNECTION_CONFIGURED: INTERNET_CONNECTION = 64u32;
pub const INTERNET_CONNECTION_LAN_: INTERNET_CONNECTION = 2u32;
pub const INTERNET_CONNECTION_MODEM: INTERNET_CONNECTION = 1u32;
pub const INTERNET_CONNECTION_MODEM_BUSY: INTERNET_CONNECTION = 8u32;
pub const INTERNET_CONNECTION_OFFLINE_: INTERNET_CONNECTION = 32u32;
pub const INTERNET_CONNECTION_PROXY: INTERNET_CONNECTION = 4u32;
pub const INTERNET_RAS_INSTALLED: INTERNET_CONNECTION = 16u32;
pub const INTERNET_CONNECTION_LAN: u32 = 2u32;
pub const INTERNET_CONNECTION_OFFLINE: u32 = 32u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_COOKIE {
pub cbSize: u32,
pub pszName: super::super::Foundation::PSTR,
pub pszData: super::super::Foundation::PSTR,
pub pszDomain: super::super::Foundation::PSTR,
pub pszPath: super::super::Foundation::PSTR,
pub pftExpires: *mut super::super::Foundation::FILETIME,
pub dwFlags: u32,
pub pszUrl: super::super::Foundation::PSTR,
pub pszP3PPolicy: super::super::Foundation::PSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_COOKIE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_COOKIE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_COOKIE2 {
pub pwszName: super::super::Foundation::PWSTR,
pub pwszValue: super::super::Foundation::PWSTR,
pub pwszDomain: super::super::Foundation::PWSTR,
pub pwszPath: super::super::Foundation::PWSTR,
pub dwFlags: u32,
pub ftExpires: super::super::Foundation::FILETIME,
pub fExpiresSet: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_COOKIE2 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_COOKIE2 {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_COOKIE_ALL_COOKIES: u32 = 536870912u32;
pub const INTERNET_COOKIE_APPLY_HOST_ONLY: u32 = 32768u32;
pub const INTERNET_COOKIE_APPLY_P3P: u32 = 128u32;
pub const INTERNET_COOKIE_ECTX_3RDPARTY: u32 = 2147483648u32;
pub const INTERNET_COOKIE_EDGE_COOKIES: u32 = 262144u32;
pub const INTERNET_COOKIE_EVALUATE_P3P: u32 = 64u32;
pub type INTERNET_COOKIE_FLAGS = u32;
pub const INTERNET_COOKIE_HTTPONLY: INTERNET_COOKIE_FLAGS = 8192u32;
pub const INTERNET_COOKIE_THIRD_PARTY: INTERNET_COOKIE_FLAGS = 16u32;
pub const INTERNET_FLAG_RESTRICTED_ZONE: INTERNET_COOKIE_FLAGS = 131072u32;
pub const INTERNET_COOKIE_HOST_ONLY: u32 = 16384u32;
pub const INTERNET_COOKIE_HOST_ONLY_APPLIED: u32 = 524288u32;
pub const INTERNET_COOKIE_IE6: u32 = 1024u32;
pub const INTERNET_COOKIE_IS_LEGACY: u32 = 2048u32;
pub const INTERNET_COOKIE_IS_RESTRICTED: u32 = 512u32;
pub const INTERNET_COOKIE_IS_SECURE: u32 = 1u32;
pub const INTERNET_COOKIE_IS_SESSION: u32 = 2u32;
pub const INTERNET_COOKIE_NON_SCRIPT: u32 = 4096u32;
pub const INTERNET_COOKIE_NO_CALLBACK: u32 = 1073741824u32;
pub const INTERNET_COOKIE_P3P_ENABLED: u32 = 256u32;
pub const INTERNET_COOKIE_PERSISTENT_HOST_ONLY: u32 = 65536u32;
pub const INTERNET_COOKIE_PROMPT_REQUIRED: u32 = 32u32;
pub const INTERNET_COOKIE_RESTRICTED_ZONE: u32 = 131072u32;
pub const INTERNET_COOKIE_SAME_SITE_LAX: u32 = 2097152u32;
pub const INTERNET_COOKIE_SAME_SITE_LEVEL_CROSS_SITE: u32 = 4194304u32;
pub const INTERNET_COOKIE_SAME_SITE_STRICT: u32 = 1048576u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CREDENTIALS {
pub lpcwszHostName: super::super::Foundation::PWSTR,
pub dwPort: u32,
pub dwScheme: u32,
pub lpcwszUrl: super::super::Foundation::PWSTR,
pub lpcwszRealm: super::super::Foundation::PWSTR,
pub fAuthIdentity: super::super::Foundation::BOOL,
pub Anonymous: INTERNET_CREDENTIALS_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CREDENTIALS {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CREDENTIALS {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INTERNET_CREDENTIALS_0 {
pub Anonymous: INTERNET_CREDENTIALS_0_0,
pub pAuthIdentityOpaque: *mut ::core::ffi::c_void,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CREDENTIALS_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CREDENTIALS_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_CREDENTIALS_0_0 {
pub lpcwszUserName: super::super::Foundation::PWSTR,
pub lpcwszPassword: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_CREDENTIALS_0_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_CREDENTIALS_0_0 {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_CUSTOMDIAL_CAN_HANGUP: u32 = 4u32;
pub const INTERNET_CUSTOMDIAL_CONNECT: u32 = 0u32;
pub const INTERNET_CUSTOMDIAL_DISCONNECT: u32 = 2u32;
pub const INTERNET_CUSTOMDIAL_SAFE_FOR_UNATTENDED: u32 = 1u32;
pub const INTERNET_CUSTOMDIAL_SHOWOFFLINE: u32 = 4u32;
pub const INTERNET_CUSTOMDIAL_UNATTENDED: u32 = 1u32;
pub const INTERNET_CUSTOMDIAL_WILL_SUPPLY_STATE: u32 = 2u32;
pub const INTERNET_DEFAULT_FTP_PORT: u32 = 21u32;
pub const INTERNET_DEFAULT_GOPHER_PORT: u32 = 70u32;
pub const INTERNET_DEFAULT_SOCKS_PORT: u32 = 1080u32;
#[repr(C)]
pub struct INTERNET_DIAGNOSTIC_SOCKET_INFO {
pub Socket: usize,
pub SourcePort: u32,
pub DestPort: u32,
pub Flags: u32,
}
impl ::core::marker::Copy for INTERNET_DIAGNOSTIC_SOCKET_INFO {}
impl ::core::clone::Clone for INTERNET_DIAGNOSTIC_SOCKET_INFO {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_DIALSTATE_DISCONNECTED: u32 = 1u32;
pub const INTERNET_DIAL_FORCE_PROMPT: u32 = 8192u32;
pub const INTERNET_DIAL_SHOW_OFFLINE: u32 = 16384u32;
pub const INTERNET_DIAL_UNATTENDED: u32 = 32768u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_DOWNLOAD_MODE_HANDLE {
pub pcwszFileName: super::super::Foundation::PWSTR,
pub phFile: *mut super::super::Foundation::HANDLE,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_DOWNLOAD_MODE_HANDLE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_DOWNLOAD_MODE_HANDLE {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct INTERNET_END_BROWSER_SESSION_DATA {
pub lpBuffer: *mut ::core::ffi::c_void,
pub dwBufferLength: u32,
}
impl ::core::marker::Copy for INTERNET_END_BROWSER_SESSION_DATA {}
impl ::core::clone::Clone for INTERNET_END_BROWSER_SESSION_DATA {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_ERROR_BASE: u32 = 12000u32;
pub const INTERNET_ERROR_LAST: u32 = 12192u32;
pub const INTERNET_ERROR_MASK_COMBINED_SEC_CERT: u32 = 2u32;
pub const INTERNET_ERROR_MASK_INSERT_CDROM: u32 = 1u32;
pub const INTERNET_ERROR_MASK_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: u32 = 8u32;
pub const INTERNET_ERROR_MASK_NEED_MSN_SSPI_PKG: u32 = 4u32;
pub const INTERNET_FIRST_OPTION: u32 = 1u32;
pub const INTERNET_FLAG_ASYNC: u32 = 268435456u32;
pub const INTERNET_FLAG_BGUPDATE: u32 = 8u32;
pub const INTERNET_FLAG_CACHE_ASYNC: u32 = 128u32;
pub const INTERNET_FLAG_CACHE_IF_NET_FAIL: u32 = 65536u32;
pub const INTERNET_FLAG_DONT_CACHE: u32 = 67108864u32;
pub const INTERNET_FLAG_EXISTING_CONNECT: u32 = 536870912u32;
pub const INTERNET_FLAG_FORMS_SUBMIT: u32 = 64u32;
pub const INTERNET_FLAG_FROM_CACHE: u32 = 16777216u32;
pub const INTERNET_FLAG_FTP_FOLDER_VIEW: u32 = 4u32;
pub const INTERNET_FLAG_FWD_BACK: u32 = 32u32;
pub const INTERNET_FLAG_HYPERLINK: u32 = 1024u32;
pub const INTERNET_FLAG_IDN_DIRECT: u32 = 1u32;
pub const INTERNET_FLAG_IDN_PROXY: u32 = 2u32;
pub const INTERNET_FLAG_IGNORE_CERT_CN_INVALID: u32 = 4096u32;
pub const INTERNET_FLAG_IGNORE_CERT_DATE_INVALID: u32 = 8192u32;
pub const INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP: u32 = 32768u32;
pub const INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS: u32 = 16384u32;
pub const INTERNET_FLAG_KEEP_CONNECTION: u32 = 4194304u32;
pub const INTERNET_FLAG_MAKE_PERSISTENT: u32 = 33554432u32;
pub const INTERNET_FLAG_MUST_CACHE_REQUEST: u32 = 16u32;
pub const INTERNET_FLAG_NEED_FILE: u32 = 16u32;
pub const INTERNET_FLAG_NO_AUTH: u32 = 262144u32;
pub const INTERNET_FLAG_NO_AUTO_REDIRECT: u32 = 2097152u32;
pub const INTERNET_FLAG_NO_CACHE_WRITE: u32 = 67108864u32;
pub const INTERNET_FLAG_NO_COOKIES: u32 = 524288u32;
pub const INTERNET_FLAG_NO_UI: u32 = 512u32;
pub const INTERNET_FLAG_OFFLINE: u32 = 16777216u32;
pub const INTERNET_FLAG_PASSIVE: u32 = 134217728u32;
pub const INTERNET_FLAG_PRAGMA_NOCACHE: u32 = 256u32;
pub const INTERNET_FLAG_RAW_DATA: u32 = 1073741824u32;
pub const INTERNET_FLAG_READ_PREFETCH: u32 = 1048576u32;
pub const INTERNET_FLAG_RELOAD: u32 = 2147483648u32;
pub const INTERNET_FLAG_RESYNCHRONIZE: u32 = 2048u32;
pub const INTERNET_FLAG_SECURE: u32 = 8388608u32;
pub const INTERNET_GLOBAL_CALLBACK_SENDING_HTTP_HEADERS: u32 = 1u32;
pub const INTERNET_HANDLE_TYPE_CONNECT_FTP: u32 = 2u32;
pub const INTERNET_HANDLE_TYPE_CONNECT_GOPHER: u32 = 3u32;
pub const INTERNET_HANDLE_TYPE_CONNECT_HTTP: u32 = 4u32;
pub const INTERNET_HANDLE_TYPE_FILE_REQUEST: u32 = 14u32;
pub const INTERNET_HANDLE_TYPE_FTP_FILE: u32 = 7u32;
pub const INTERNET_HANDLE_TYPE_FTP_FILE_HTML: u32 = 8u32;
pub const INTERNET_HANDLE_TYPE_FTP_FIND: u32 = 5u32;
pub const INTERNET_HANDLE_TYPE_FTP_FIND_HTML: u32 = 6u32;
pub const INTERNET_HANDLE_TYPE_GOPHER_FILE: u32 = 11u32;
pub const INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML: u32 = 12u32;
pub const INTERNET_HANDLE_TYPE_GOPHER_FIND: u32 = 9u32;
pub const INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML: u32 = 10u32;
pub const INTERNET_HANDLE_TYPE_HTTP_REQUEST: u32 = 13u32;
pub const INTERNET_HANDLE_TYPE_INTERNET: u32 = 1u32;
pub const INTERNET_IDENTITY_FLAG_CLEAR_CONTENT: u32 = 32u32;
pub const INTERNET_IDENTITY_FLAG_CLEAR_COOKIES: u32 = 8u32;
pub const INTERNET_IDENTITY_FLAG_CLEAR_DATA: u32 = 4u32;
pub const INTERNET_IDENTITY_FLAG_CLEAR_HISTORY: u32 = 16u32;
pub const INTERNET_IDENTITY_FLAG_PRIVATE_CACHE: u32 = 1u32;
pub const INTERNET_IDENTITY_FLAG_SHARED_CACHE: u32 = 2u32;
pub const INTERNET_INTERNAL_ERROR_BASE: u32 = 12900u32;
pub const INTERNET_INVALID_PORT_NUMBER: u32 = 0u32;
pub const INTERNET_KEEP_ALIVE_DISABLED: u32 = 0u32;
pub const INTERNET_KEEP_ALIVE_ENABLED: u32 = 1u32;
pub const INTERNET_KEEP_ALIVE_UNKNOWN: u32 = 4294967295u32;
pub const INTERNET_LAST_OPTION: u32 = 187u32;
pub const INTERNET_LAST_OPTION_INTERNAL: u32 = 191u32;
pub const INTERNET_MAX_HOST_NAME_LENGTH: u32 = 256u32;
pub const INTERNET_MAX_PASSWORD_LENGTH: u32 = 128u32;
pub const INTERNET_MAX_PORT_NUMBER_LENGTH: u32 = 5u32;
pub const INTERNET_MAX_PORT_NUMBER_VALUE: u32 = 65535u32;
pub const INTERNET_MAX_USER_NAME_LENGTH: u32 = 128u32;
pub const INTERNET_NO_CALLBACK: u32 = 0u32;
pub const INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY: u32 = 4u32;
pub const INTERNET_OPTION_ACTIVATE_WORKER_THREADS: u32 = 92u32;
pub const INTERNET_OPTION_ACTIVITY_ID: u32 = 185u32;
pub const INTERNET_OPTION_ALLOW_FAILED_CONNECT_CONTENT: u32 = 110u32;
pub const INTERNET_OPTION_ALLOW_INSECURE_FALLBACK: u32 = 161u32;
pub const INTERNET_OPTION_ALTER_IDENTITY: u32 = 80u32;
pub const INTERNET_OPTION_APP_CACHE: u32 = 130u32;
pub const INTERNET_OPTION_ASYNC: u32 = 30u32;
pub const INTERNET_OPTION_ASYNC_ID: u32 = 15u32;
pub const INTERNET_OPTION_ASYNC_PRIORITY: u32 = 16u32;
pub const INTERNET_OPTION_AUTH_FLAGS: u32 = 85u32;
pub const INTERNET_OPTION_AUTH_SCHEME_SELECTED: u32 = 183u32;
pub const INTERNET_OPTION_AUTODIAL_CONNECTION: u32 = 83u32;
pub const INTERNET_OPTION_AUTODIAL_HWND: u32 = 112u32;
pub const INTERNET_OPTION_AUTODIAL_MODE: u32 = 82u32;
pub const INTERNET_OPTION_BACKGROUND_CONNECTIONS: u32 = 121u32;
pub const INTERNET_OPTION_BYPASS_EDITED_ENTRY: u32 = 64u32;
pub const INTERNET_OPTION_CACHE_ENTRY_EXTRA_DATA: u32 = 139u32;
pub const INTERNET_OPTION_CACHE_PARTITION: u32 = 111u32;
pub const INTERNET_OPTION_CACHE_STREAM_HANDLE: u32 = 27u32;
pub const INTERNET_OPTION_CACHE_TIMESTAMPS: u32 = 69u32;
pub const INTERNET_OPTION_CALLBACK: u32 = 1u32;
pub const INTERNET_OPTION_CALLBACK_FILTER: u32 = 54u32;
pub const INTERNET_OPTION_CANCEL_CACHE_WRITE: u32 = 182u32;
pub const INTERNET_OPTION_CERT_ERROR_FLAGS: u32 = 98u32;
pub const INTERNET_OPTION_CHUNK_ENCODE_REQUEST: u32 = 150u32;
pub const INTERNET_OPTION_CLIENT_CERT_CONTEXT: u32 = 84u32;
pub const INTERNET_OPTION_CLIENT_CERT_ISSUER_LIST: u32 = 153u32;
pub const INTERNET_OPTION_CM_HANDLE_COPY_REF: u32 = 118u32;
pub const INTERNET_OPTION_CODEPAGE: u32 = 68u32;
pub const INTERNET_OPTION_CODEPAGE_EXTRA: u32 = 101u32;
pub const INTERNET_OPTION_CODEPAGE_PATH: u32 = 100u32;
pub const INTERNET_OPTION_COMPRESSED_CONTENT_LENGTH: u32 = 147u32;
pub const INTERNET_OPTION_CONNECTED_STATE: u32 = 50u32;
pub const INTERNET_OPTION_CONNECTION_FILTER: u32 = 162u32;
pub const INTERNET_OPTION_CONNECTION_INFO: u32 = 120u32;
pub const INTERNET_OPTION_CONNECT_BACKOFF: u32 = 4u32;
pub const INTERNET_OPTION_CONNECT_LIMIT: u32 = 46u32;
pub const INTERNET_OPTION_CONNECT_RETRIES: u32 = 3u32;
pub const INTERNET_OPTION_CONNECT_TIME: u32 = 55u32;
pub const INTERNET_OPTION_CONNECT_TIMEOUT: u32 = 2u32;
pub const INTERNET_OPTION_CONTEXT_VALUE: u32 = 45u32;
pub const INTERNET_OPTION_CONTEXT_VALUE_OLD: u32 = 10u32;
pub const INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT: u32 = 6u32;
pub const INTERNET_OPTION_CONTROL_SEND_TIMEOUT: u32 = 5u32;
pub const INTERNET_OPTION_COOKIES_3RD_PARTY: u32 = 86u32;
pub const INTERNET_OPTION_COOKIES_APPLY_HOST_ONLY: u32 = 179u32;
pub const INTERNET_OPTION_COOKIES_SAME_SITE_LEVEL: u32 = 187u32;
pub const INTERNET_OPTION_DATAFILE_EXT: u32 = 96u32;
pub const INTERNET_OPTION_DATAFILE_NAME: u32 = 33u32;
pub const INTERNET_OPTION_DATA_RECEIVE_TIMEOUT: u32 = 8u32;
pub const INTERNET_OPTION_DATA_SEND_TIMEOUT: u32 = 7u32;
pub const INTERNET_OPTION_DEPENDENCY_HANDLE: u32 = 131u32;
pub const INTERNET_OPTION_DETECT_POST_SEND: u32 = 71u32;
pub const INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO: u32 = 67u32;
pub const INTERNET_OPTION_DIGEST_AUTH_UNLOAD: u32 = 76u32;
pub const INTERNET_OPTION_DISABLE_AUTODIAL: u32 = 70u32;
pub const INTERNET_OPTION_DISABLE_INSECURE_FALLBACK: u32 = 160u32;
pub const INTERNET_OPTION_DISABLE_NTLM_PREAUTH: u32 = 72u32;
pub const INTERNET_OPTION_DISABLE_PASSPORT_AUTH: u32 = 87u32;
pub const INTERNET_OPTION_DISABLE_PROXY_LINK_LOCAL_NAME_RESOLUTION: u32 = 190u32;
pub const INTERNET_OPTION_DISALLOW_PREMATURE_EOF: u32 = 137u32;
pub const INTERNET_OPTION_DISCONNECTED_TIMEOUT: u32 = 49u32;
pub const INTERNET_OPTION_DOWNLOAD_MODE: u32 = 116u32;
pub const INTERNET_OPTION_DOWNLOAD_MODE_HANDLE: u32 = 165u32;
pub const INTERNET_OPTION_DO_NOT_TRACK: u32 = 123u32;
pub const INTERNET_OPTION_DUO_USED: u32 = 149u32;
pub const INTERNET_OPTION_EDGE_COOKIES: u32 = 166u32;
pub const INTERNET_OPTION_EDGE_COOKIES_TEMP: u32 = 175u32;
pub const INTERNET_OPTION_EDGE_MODE: u32 = 180u32;
pub const INTERNET_OPTION_ENABLE_DUO: u32 = 148u32;
pub const INTERNET_OPTION_ENABLE_HEADER_CALLBACKS: u32 = 168u32;
pub const INTERNET_OPTION_ENABLE_HTTP_PROTOCOL: u32 = 148u32;
pub const INTERNET_OPTION_ENABLE_PASSPORT_AUTH: u32 = 90u32;
pub const INTERNET_OPTION_ENABLE_REDIRECT_CACHE_READ: u32 = 122u32;
pub const INTERNET_OPTION_ENABLE_TEST_SIGNING: u32 = 189u32;
pub const INTERNET_OPTION_ENABLE_WBOEXT: u32 = 158u32;
pub const INTERNET_OPTION_ENABLE_ZLIB_DEFLATE: u32 = 173u32;
pub const INTERNET_OPTION_ENCODE_EXTRA: u32 = 155u32;
pub const INTERNET_OPTION_ENCODE_FALLBACK_FOR_REDIRECT_URI: u32 = 174u32;
pub const INTERNET_OPTION_END_BROWSER_SESSION: u32 = 42u32;
pub const INTERNET_OPTION_ENTERPRISE_CONTEXT: u32 = 159u32;
pub const INTERNET_OPTION_ERROR_MASK: u32 = 62u32;
pub const INTERNET_OPTION_EXEMPT_CONNECTION_LIMIT: u32 = 89u32;
pub const INTERNET_OPTION_EXTENDED_CALLBACKS: u32 = 108u32;
pub const INTERNET_OPTION_EXTENDED_ERROR: u32 = 24u32;
pub const INTERNET_OPTION_FAIL_ON_CACHE_WRITE_ERROR: u32 = 115u32;
pub const INTERNET_OPTION_FALSE_START: u32 = 141u32;
pub const INTERNET_OPTION_FLUSH_STATE: u32 = 135u32;
pub const INTERNET_OPTION_FORCE_DECODE: u32 = 178u32;
pub const INTERNET_OPTION_FROM_CACHE_TIMEOUT: u32 = 63u32;
pub const INTERNET_OPTION_GLOBAL_CALLBACK: u32 = 188u32;
pub const INTERNET_OPTION_HANDLE_TYPE: u32 = 9u32;
pub const INTERNET_OPTION_HIBERNATE_INACTIVE_WORKER_THREADS: u32 = 91u32;
pub const INTERNET_OPTION_HSTS: u32 = 157u32;
pub const INTERNET_OPTION_HTTP_09: u32 = 191u32;
pub const INTERNET_OPTION_HTTP_DECODING: u32 = 65u32;
pub const INTERNET_OPTION_HTTP_PROTOCOL_USED: u32 = 149u32;
pub const INTERNET_OPTION_HTTP_VERSION: u32 = 59u32;
pub const INTERNET_OPTION_IDENTITY: u32 = 78u32;
pub const INTERNET_OPTION_IDLE_STATE: u32 = 51u32;
pub const INTERNET_OPTION_IDN: u32 = 102u32;
pub const INTERNET_OPTION_IGNORE_CERT_ERROR_FLAGS: u32 = 99u32;
pub const INTERNET_OPTION_IGNORE_OFFLINE: u32 = 77u32;
pub const INTERNET_OPTION_KEEP_CONNECTION: u32 = 22u32;
pub const INTERNET_OPTION_LINE_STATE: u32 = 50u32;
pub const INTERNET_OPTION_LISTEN_TIMEOUT: u32 = 11u32;
pub const INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER: u32 = 74u32;
pub const INTERNET_OPTION_MAX_CONNS_PER_PROXY: u32 = 103u32;
pub const INTERNET_OPTION_MAX_CONNS_PER_SERVER: u32 = 73u32;
pub const INTERNET_OPTION_MAX_QUERY_BUFFER_SIZE: u32 = 140u32;
pub const INTERNET_OPTION_NET_SPEED: u32 = 61u32;
pub const INTERNET_OPTION_NOCACHE_WRITE_IN_PRIVATE: u32 = 184u32;
pub const INTERNET_OPTION_NOTIFY_SENDING_COOKIE: u32 = 152u32;
pub const INTERNET_OPTION_NO_HTTP_SERVER_AUTH: u32 = 167u32;
pub const INTERNET_OPTION_OFFLINE_MODE: u32 = 26u32;
pub const INTERNET_OPTION_OFFLINE_SEMANTICS: u32 = 52u32;
pub const INTERNET_OPTION_OFFLINE_TIMEOUT: u32 = 49u32;
pub const INTERNET_OPTION_OPT_IN_WEAK_SIGNATURE: u32 = 176u32;
pub const INTERNET_OPTION_ORIGINAL_CONNECT_FLAGS: u32 = 97u32;
pub const INTERNET_OPTION_PARENT_HANDLE: u32 = 21u32;
pub const INTERNET_OPTION_PARSE_LINE_FOLDING: u32 = 177u32;
pub const INTERNET_OPTION_PASSWORD: u32 = 29u32;
pub const INTERNET_OPTION_PER_CONNECTION_OPTION: u32 = 75u32;
pub const INTERNET_OPTION_POLICY: u32 = 48u32;
pub const INTERNET_OPTION_PRESERVE_REFERER_ON_HTTPS_TO_HTTP_REDIRECT: u32 = 170u32;
pub const INTERNET_OPTION_PRESERVE_REQUEST_SERVER_CREDENTIALS_ON_REDIRECT: u32 = 169u32;
pub const INTERNET_OPTION_PROXY: u32 = 38u32;
pub const INTERNET_OPTION_PROXY_AUTH_SCHEME: u32 = 144u32;
pub const INTERNET_OPTION_PROXY_CREDENTIALS: u32 = 107u32;
pub const INTERNET_OPTION_PROXY_FROM_REQUEST: u32 = 109u32;
pub const INTERNET_OPTION_PROXY_PASSWORD: u32 = 44u32;
pub const INTERNET_OPTION_PROXY_SETTINGS_CHANGED: u32 = 95u32;
pub const INTERNET_OPTION_PROXY_USERNAME: u32 = 43u32;
pub const INTERNET_OPTION_READ_BUFFER_SIZE: u32 = 12u32;
pub const INTERNET_OPTION_RECEIVE_THROUGHPUT: u32 = 57u32;
pub const INTERNET_OPTION_RECEIVE_TIMEOUT: u32 = 6u32;
pub const INTERNET_OPTION_REFERER_TOKEN_BINDING_HOSTNAME: u32 = 163u32;
pub const INTERNET_OPTION_REFRESH: u32 = 37u32;
pub const INTERNET_OPTION_REMOVE_IDENTITY: u32 = 79u32;
pub const INTERNET_OPTION_REQUEST_FLAGS: u32 = 23u32;
pub const INTERNET_OPTION_REQUEST_PRIORITY: u32 = 58u32;
pub const INTERNET_OPTION_REQUEST_TIMES: u32 = 186u32;
pub const INTERNET_OPTION_RESET: u32 = 154u32;
pub const INTERNET_OPTION_RESET_URLCACHE_SESSION: u32 = 60u32;
pub const INTERNET_OPTION_RESPONSE_RESUMABLE: u32 = 117u32;
pub const INTERNET_OPTION_RESTORE_WORKER_THREAD_DEFAULTS: u32 = 93u32;
pub const INTERNET_OPTION_SECONDARY_CACHE_KEY: u32 = 53u32;
pub const INTERNET_OPTION_SECURE_FAILURE: u32 = 151u32;
pub const INTERNET_OPTION_SECURITY_CERTIFICATE: u32 = 35u32;
pub const INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: u32 = 32u32;
pub const INTERNET_OPTION_SECURITY_CONNECTION_INFO: u32 = 66u32;
pub const INTERNET_OPTION_SECURITY_FLAGS: u32 = 31u32;
pub const INTERNET_OPTION_SECURITY_KEY_BITNESS: u32 = 36u32;
pub const INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT: u32 = 47u32;
pub const INTERNET_OPTION_SEND_THROUGHPUT: u32 = 56u32;
pub const INTERNET_OPTION_SEND_TIMEOUT: u32 = 5u32;
pub const INTERNET_OPTION_SEND_UTF8_SERVERNAME_TO_PROXY: u32 = 88u32;
pub const INTERNET_OPTION_SERVER_ADDRESS_INFO: u32 = 156u32;
pub const INTERNET_OPTION_SERVER_AUTH_SCHEME: u32 = 143u32;
pub const INTERNET_OPTION_SERVER_CERT_CHAIN_CONTEXT: u32 = 105u32;
pub const INTERNET_OPTION_SERVER_CREDENTIALS: u32 = 113u32;
pub const INTERNET_OPTION_SESSION_START_TIME: u32 = 106u32;
pub const INTERNET_OPTION_SETTINGS_CHANGED: u32 = 39u32;
pub const INTERNET_OPTION_SET_IN_PRIVATE: u32 = 164u32;
pub const INTERNET_OPTION_SOCKET_NODELAY: u32 = 129u32;
pub const INTERNET_OPTION_SOCKET_NOTIFICATION_IOCTL: u32 = 138u32;
pub const INTERNET_OPTION_SOCKET_SEND_BUFFER_LENGTH: u32 = 94u32;
pub const INTERNET_OPTION_SOURCE_PORT: u32 = 146u32;
pub const INTERNET_OPTION_SUPPRESS_BEHAVIOR: u32 = 81u32;
pub const INTERNET_OPTION_SUPPRESS_SERVER_AUTH: u32 = 104u32;
pub const INTERNET_OPTION_SYNC_MODE_AUTOMATIC_SESSION_DISABLED: u32 = 172u32;
pub const INTERNET_OPTION_TCP_FAST_OPEN: u32 = 171u32;
pub const INTERNET_OPTION_TIMED_CONNECTION_LIMIT_BYPASS: u32 = 133u32;
pub const INTERNET_OPTION_TOKEN_BINDING_PUBLIC_KEY: u32 = 181u32;
pub const INTERNET_OPTION_TUNNEL_ONLY: u32 = 145u32;
pub const INTERNET_OPTION_UNLOAD_NOTIFY_EVENT: u32 = 128u32;
pub const INTERNET_OPTION_UPGRADE_TO_WEB_SOCKET: u32 = 126u32;
pub const INTERNET_OPTION_URL: u32 = 34u32;
pub const INTERNET_OPTION_USERNAME: u32 = 28u32;
pub const INTERNET_OPTION_USER_AGENT: u32 = 41u32;
pub const INTERNET_OPTION_USER_PASS_SERVER_ONLY: u32 = 142u32;
pub const INTERNET_OPTION_USE_FIRST_AVAILABLE_CONNECTION: u32 = 132u32;
pub const INTERNET_OPTION_USE_MODIFIED_HEADER_FILTER: u32 = 124u32;
pub const INTERNET_OPTION_VERSION: u32 = 40u32;
pub const INTERNET_OPTION_WEB_SOCKET_CLOSE_TIMEOUT: u32 = 134u32;
pub const INTERNET_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL: u32 = 127u32;
pub const INTERNET_OPTION_WPAD_SLEEP: u32 = 114u32;
pub const INTERNET_OPTION_WRITE_BUFFER_SIZE: u32 = 13u32;
pub const INTERNET_OPTION_WWA_MODE: u32 = 125u32;
pub type INTERNET_PER_CONN = u32;
pub const INTERNET_PER_CONN_AUTOCONFIG_URL: INTERNET_PER_CONN = 4u32;
pub const INTERNET_PER_CONN_AUTODISCOVERY_FLAGS: INTERNET_PER_CONN = 5u32;
pub const INTERNET_PER_CONN_FLAGS: INTERNET_PER_CONN = 1u32;
pub const INTERNET_PER_CONN_PROXY_BYPASS: INTERNET_PER_CONN = 3u32;
pub const INTERNET_PER_CONN_PROXY_SERVER: INTERNET_PER_CONN = 2u32;
pub const INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL: INTERNET_PER_CONN = 6u32;
pub const INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS: INTERNET_PER_CONN = 7u32;
pub const INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME: INTERNET_PER_CONN = 8u32;
pub const INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL: INTERNET_PER_CONN = 9u32;
pub const INTERNET_PER_CONN_FLAGS_UI: u32 = 10u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_PER_CONN_OPTIONA {
pub dwOption: INTERNET_PER_CONN,
pub Value: INTERNET_PER_CONN_OPTIONA_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_PER_CONN_OPTIONA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_PER_CONN_OPTIONA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INTERNET_PER_CONN_OPTIONA_0 {
pub dwValue: u32,
pub pszValue: super::super::Foundation::PSTR,
pub ftValue: super::super::Foundation::FILETIME,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_PER_CONN_OPTIONA_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_PER_CONN_OPTIONA_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_PER_CONN_OPTIONW {
pub dwOption: INTERNET_PER_CONN,
pub Value: INTERNET_PER_CONN_OPTIONW_0,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_PER_CONN_OPTIONW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_PER_CONN_OPTIONW {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union INTERNET_PER_CONN_OPTIONW_0 {
pub dwValue: u32,
pub pszValue: super::super::Foundation::PWSTR,
pub ftValue: super::super::Foundation::FILETIME,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_PER_CONN_OPTIONW_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_PER_CONN_OPTIONW_0 {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_PER_CONN_OPTION_LISTA {
pub dwSize: u32,
pub pszConnection: super::super::Foundation::PSTR,
pub dwOptionCount: u32,
pub dwOptionError: u32,
pub pOptions: *mut INTERNET_PER_CONN_OPTIONA,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_PER_CONN_OPTION_LISTA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_PER_CONN_OPTION_LISTA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_PER_CONN_OPTION_LISTW {
pub dwSize: u32,
pub pszConnection: super::super::Foundation::PWSTR,
pub dwOptionCount: u32,
pub dwOptionError: u32,
pub pOptions: *mut INTERNET_PER_CONN_OPTIONW,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_PER_CONN_OPTION_LISTW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_PER_CONN_OPTION_LISTW {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_PREFETCH_ABORTED: u32 = 2u32;
pub const INTERNET_PREFETCH_COMPLETE: u32 = 1u32;
pub const INTERNET_PREFETCH_PROGRESS: u32 = 0u32;
#[repr(C)]
pub struct INTERNET_PREFETCH_STATUS {
pub dwStatus: u32,
pub dwSize: u32,
}
impl ::core::marker::Copy for INTERNET_PREFETCH_STATUS {}
impl ::core::clone::Clone for INTERNET_PREFETCH_STATUS {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_PRIORITY_FOREGROUND: u32 = 1000u32;
#[repr(C)]
pub struct INTERNET_PROXY_INFO {
pub dwAccessType: INTERNET_ACCESS_TYPE,
pub lpszProxy: *mut i8,
pub lpszProxyBypass: *mut i8,
}
impl ::core::marker::Copy for INTERNET_PROXY_INFO {}
impl ::core::clone::Clone for INTERNET_PROXY_INFO {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_REQFLAG_ASYNC: u32 = 2u32;
pub const INTERNET_REQFLAG_CACHE_WRITE_DISABLED: u32 = 64u32;
pub const INTERNET_REQFLAG_FROM_APP_CACHE: u32 = 256u32;
pub const INTERNET_REQFLAG_FROM_CACHE: u32 = 1u32;
pub const INTERNET_REQFLAG_NET_TIMEOUT: u32 = 128u32;
pub const INTERNET_REQFLAG_NO_HEADERS: u32 = 8u32;
pub const INTERNET_REQFLAG_PASSIVE: u32 = 16u32;
pub const INTERNET_REQFLAG_VIA_PROXY: u32 = 4u32;
pub const INTERNET_RFC1123_BUFSIZE: u32 = 30u32;
pub const INTERNET_RFC1123_FORMAT: u32 = 0u32;
pub type INTERNET_SCHEME = i32;
pub const INTERNET_SCHEME_PARTIAL: INTERNET_SCHEME = -2i32;
pub const INTERNET_SCHEME_UNKNOWN: INTERNET_SCHEME = -1i32;
pub const INTERNET_SCHEME_DEFAULT: INTERNET_SCHEME = 0i32;
pub const INTERNET_SCHEME_FTP: INTERNET_SCHEME = 1i32;
pub const INTERNET_SCHEME_GOPHER: INTERNET_SCHEME = 2i32;
pub const INTERNET_SCHEME_HTTP: INTERNET_SCHEME = 3i32;
pub const INTERNET_SCHEME_HTTPS: INTERNET_SCHEME = 4i32;
pub const INTERNET_SCHEME_FILE: INTERNET_SCHEME = 5i32;
pub const INTERNET_SCHEME_NEWS: INTERNET_SCHEME = 6i32;
pub const INTERNET_SCHEME_MAILTO: INTERNET_SCHEME = 7i32;
pub const INTERNET_SCHEME_SOCKS: INTERNET_SCHEME = 8i32;
pub const INTERNET_SCHEME_JAVASCRIPT: INTERNET_SCHEME = 9i32;
pub const INTERNET_SCHEME_VBSCRIPT: INTERNET_SCHEME = 10i32;
pub const INTERNET_SCHEME_RES: INTERNET_SCHEME = 11i32;
pub const INTERNET_SCHEME_FIRST: INTERNET_SCHEME = 1i32;
pub const INTERNET_SCHEME_LAST: INTERNET_SCHEME = 11i32;
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity"))]
pub struct INTERNET_SECURITY_CONNECTION_INFO {
pub dwSize: u32,
pub fSecure: super::super::Foundation::BOOL,
pub connectionInfo: super::super::Security::Authentication::Identity::SecPkgContext_ConnectionInfo,
pub cipherInfo: super::super::Security::Authentication::Identity::SecPkgContext_CipherInfo,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity"))]
impl ::core::marker::Copy for INTERNET_SECURITY_CONNECTION_INFO {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity"))]
impl ::core::clone::Clone for INTERNET_SECURITY_CONNECTION_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity", feature = "Win32_Security_Cryptography"))]
pub struct INTERNET_SECURITY_INFO {
pub dwSize: u32,
pub pCertificate: *mut super::super::Security::Cryptography::CERT_CONTEXT,
pub pcCertChain: *mut super::super::Security::Cryptography::CERT_CHAIN_CONTEXT,
pub connectionInfo: super::super::Security::Authentication::Identity::SecPkgContext_ConnectionInfo,
pub cipherInfo: super::super::Security::Authentication::Identity::SecPkgContext_CipherInfo,
pub pcUnverifiedCertChain: *mut super::super::Security::Cryptography::CERT_CHAIN_CONTEXT,
pub channelBindingToken: super::super::Security::Authentication::Identity::SecPkgContext_Bindings,
}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity", feature = "Win32_Security_Cryptography"))]
impl ::core::marker::Copy for INTERNET_SECURITY_INFO {}
#[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security_Authentication_Identity", feature = "Win32_Security_Cryptography"))]
impl ::core::clone::Clone for INTERNET_SECURITY_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct INTERNET_SERVER_CONNECTION_STATE {
pub lpcwszHostName: super::super::Foundation::PWSTR,
pub fProxy: super::super::Foundation::BOOL,
pub dwCounter: u32,
pub dwConnectionLimit: u32,
pub dwAvailableCreates: u32,
pub dwAvailableKeepAlives: u32,
pub dwActiveConnections: u32,
pub dwWaiters: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for INTERNET_SERVER_CONNECTION_STATE {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for INTERNET_SERVER_CONNECTION_STATE {
fn clone(&self) -> Self {
*self
}
}
pub const INTERNET_SERVICE_FTP: u32 = 1u32;
pub const INTERNET_SERVICE_GOPHER: u32 = 2u32;
pub const INTERNET_SERVICE_HTTP: u32 = 3u32;
pub const INTERNET_SERVICE_URL: u32 = 0u32;
pub type INTERNET_STATE = u32;
pub const INTERNET_STATE_CONNECTED: INTERNET_STATE = 1u32;
pub const INTERNET_STATE_DISCONNECTED: INTERNET_STATE = 2u32;
pub const INTERNET_STATE_DISCONNECTED_BY_USER: INTERNET_STATE = 16u32;
pub const INTERNET_STATE_IDLE: INTERNET_STATE = 256u32;
pub const INTERNET_STATE_BUSY: INTERNET_STATE = 512u32;
pub const INTERNET_STATUS_CLOSING_CONNECTION: u32 = 50u32;
pub const INTERNET_STATUS_CONNECTED_TO_SERVER: u32 = 21u32;
pub const INTERNET_STATUS_CONNECTING_TO_SERVER: u32 = 20u32;
pub const INTERNET_STATUS_CONNECTION_CLOSED: u32 = 51u32;
pub const INTERNET_STATUS_COOKIE: u32 = 430u32;
pub const INTERNET_STATUS_COOKIE_HISTORY: u32 = 327u32;
pub const INTERNET_STATUS_COOKIE_RECEIVED: u32 = 321u32;
pub const INTERNET_STATUS_COOKIE_SENT: u32 = 320u32;
pub const INTERNET_STATUS_CTL_RESPONSE_RECEIVED: u32 = 42u32;
pub const INTERNET_STATUS_DETECTING_PROXY: u32 = 80u32;
pub const INTERNET_STATUS_END_BROWSER_SESSION: u32 = 420u32;
pub const INTERNET_STATUS_FILTER_CLOSED: u32 = 512u32;
pub const INTERNET_STATUS_FILTER_CLOSING: u32 = 256u32;
pub const INTERNET_STATUS_FILTER_CONNECTED: u32 = 8u32;
pub const INTERNET_STATUS_FILTER_CONNECTING: u32 = 4u32;
pub const INTERNET_STATUS_FILTER_HANDLE_CLOSING: u32 = 2048u32;
pub const INTERNET_STATUS_FILTER_HANDLE_CREATED: u32 = 1024u32;
pub const INTERNET_STATUS_FILTER_PREFETCH: u32 = 4096u32;
pub const INTERNET_STATUS_FILTER_RECEIVED: u32 = 128u32;
pub const INTERNET_STATUS_FILTER_RECEIVING: u32 = 64u32;
pub const INTERNET_STATUS_FILTER_REDIRECT: u32 = 8192u32;
pub const INTERNET_STATUS_FILTER_RESOLVED: u32 = 2u32;
pub const INTERNET_STATUS_FILTER_RESOLVING: u32 = 1u32;
pub const INTERNET_STATUS_FILTER_SENDING: u32 = 16u32;
pub const INTERNET_STATUS_FILTER_SENT: u32 = 32u32;
pub const INTERNET_STATUS_FILTER_STATE_CHANGE: u32 = 16384u32;
pub const INTERNET_STATUS_HANDLE_CLOSING: u32 = 70u32;
pub const INTERNET_STATUS_HANDLE_CREATED: u32 = 60u32;
pub const INTERNET_STATUS_INTERMEDIATE_RESPONSE: u32 = 120u32;
pub const INTERNET_STATUS_NAME_RESOLVED: u32 = 11u32;
pub const INTERNET_STATUS_P3P_HEADER: u32 = 325u32;
pub const INTERNET_STATUS_P3P_POLICYREF: u32 = 326u32;
pub const INTERNET_STATUS_PREFETCH: u32 = 43u32;
pub const INTERNET_STATUS_PRIVACY_IMPACTED: u32 = 324u32;
pub const INTERNET_STATUS_PROXY_CREDENTIALS: u32 = 400u32;
pub const INTERNET_STATUS_RECEIVING_RESPONSE: u32 = 40u32;
pub const INTERNET_STATUS_REDIRECT: u32 = 110u32;
pub const INTERNET_STATUS_REQUEST_COMPLETE: u32 = 100u32;
pub const INTERNET_STATUS_REQUEST_HEADERS_SET: u32 = 329u32;
pub const INTERNET_STATUS_REQUEST_SENT: u32 = 31u32;
pub const INTERNET_STATUS_RESOLVING_NAME: u32 = 10u32;
pub const INTERNET_STATUS_RESPONSE_HEADERS_SET: u32 = 330u32;
pub const INTERNET_STATUS_RESPONSE_RECEIVED: u32 = 41u32;
pub const INTERNET_STATUS_SENDING_COOKIE: u32 = 328u32;
pub const INTERNET_STATUS_SENDING_REQUEST: u32 = 30u32;
pub const INTERNET_STATUS_SERVER_CONNECTION_STATE: u32 = 410u32;
pub const INTERNET_STATUS_SERVER_CREDENTIALS: u32 = 401u32;
pub const INTERNET_STATUS_STATE_CHANGE: u32 = 200u32;
pub const INTERNET_STATUS_USER_INPUT_REQUIRED: u32 = 140u32;
pub const INTERNET_SUPPRESS_COOKIE_PERSIST: u32 = 3u32;
pub const INTERNET_SUPPRESS_COOKIE_PERSIST_RESET: u32 = 4u32;
pub const INTERNET_SUPPRESS_COOKIE_POLICY: u32 = 1u32;
pub const INTERNET_SUPPRESS_COOKIE_POLICY_RESET: u32 = 2u32;
pub const INTERNET_SUPPRESS_RESET_ALL: u32 = 0u32;
#[repr(C)]
pub struct INTERNET_VERSION_INFO {
pub dwMajorVersion: u32,
pub dwMinorVersion: u32,
}
impl ::core::marker::Copy for INTERNET_VERSION_INFO {}
impl ::core::clone::Clone for INTERNET_VERSION_INFO {
fn clone(&self) -> Self {
*self
}
}
pub type IProofOfPossessionCookieInfoManager = *mut ::core::ffi::c_void;
pub type IProofOfPossessionCookieInfoManager2 = *mut ::core::ffi::c_void;
pub const IRF_ASYNC: u32 = 1u32;
pub const IRF_NO_WAIT: u32 = 8u32;
pub const IRF_SYNC: u32 = 4u32;
pub const IRF_USE_CONTEXT: u32 = 8u32;
pub const ISO_FORCE_DISCONNECTED: u32 = 1u32;
pub const ISO_FORCE_OFFLINE: u32 = 1u32;
pub const ISO_GLOBAL: u32 = 1u32;
pub const ISO_REGISTRY: u32 = 2u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct IncomingCookieState {
pub cSession: i32,
pub cPersistent: i32,
pub cAccepted: i32,
pub cLeashed: i32,
pub cDowngraded: i32,
pub cBlocked: i32,
pub pszLocation: super::super::Foundation::PSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for IncomingCookieState {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for IncomingCookieState {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct InternetCookieHistory {
pub fAccepted: super::super::Foundation::BOOL,
pub fLeashed: super::super::Foundation::BOOL,
pub fDowngraded: super::super::Foundation::BOOL,
pub fRejected: super::super::Foundation::BOOL,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for InternetCookieHistory {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for InternetCookieHistory {
fn clone(&self) -> Self {
*self
}
}
pub type InternetCookieState = i32;
pub const COOKIE_STATE_UNKNOWN: InternetCookieState = 0i32;
pub const COOKIE_STATE_ACCEPT: InternetCookieState = 1i32;
pub const COOKIE_STATE_PROMPT: InternetCookieState = 2i32;
pub const COOKIE_STATE_LEASH: InternetCookieState = 3i32;
pub const COOKIE_STATE_DOWNGRADE: InternetCookieState = 4i32;
pub const COOKIE_STATE_REJECT: InternetCookieState = 5i32;
pub const COOKIE_STATE_MAX: InternetCookieState = 5i32;
pub type LPINTERNET_STATUS_CALLBACK = ::core::option::Option<unsafe extern "system" fn(hinternet: *const ::core::ffi::c_void, dwcontext: usize, dwinternetstatus: u32, lpvstatusinformation: *const ::core::ffi::c_void, dwstatusinformationlength: u32)>;
pub const MAX_CACHE_ENTRY_INFO_SIZE: u32 = 4096u32;
pub const MAX_GOPHER_ATTRIBUTE_NAME: u32 = 128u32;
pub const MAX_GOPHER_CATEGORY_NAME: u32 = 128u32;
pub const MAX_GOPHER_DISPLAY_TEXT: u32 = 128u32;
pub const MAX_GOPHER_HOST_NAME: u32 = 256u32;
pub const MAX_GOPHER_SELECTOR_TEXT: u32 = 256u32;
pub const MIN_GOPHER_ATTRIBUTE_LENGTH: u32 = 256u32;
pub const MUST_REVALIDATE_CACHE_ENTRY: u32 = 256u32;
pub const MaxPrivacySettings: u32 = 16384u32;
pub const NORMAL_CACHE_ENTRY: u32 = 1u32;
pub const OTHER_USER_CACHE_ENTRY: u32 = 8388608u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct OutgoingCookieState {
pub cSent: i32,
pub cSuppressed: i32,
pub pszLocation: super::super::Foundation::PSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for OutgoingCookieState {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for OutgoingCookieState {
fn clone(&self) -> Self {
*self
}
}
pub const PENDING_DELETE_CACHE_ENTRY: u32 = 4194304u32;
pub type PFN_AUTH_NOTIFY = ::core::option::Option<unsafe extern "system" fn(param0: usize, param1: u32, param2: *mut ::core::ffi::c_void) -> u32>;
#[cfg(feature = "Win32_Foundation")]
pub type PFN_DIAL_HANDLER = ::core::option::Option<unsafe extern "system" fn(param0: super::super::Foundation::HWND, param1: super::super::Foundation::PSTR, param2: u32, param3: *mut u32) -> u32>;
pub const POST_CHECK_CACHE_ENTRY: u32 = 536870912u32;
pub const POST_RESPONSE_CACHE_ENTRY: u32 = 67108864u32;
pub const PRIVACY_IMPACTED_CACHE_ENTRY: u32 = 33554432u32;
pub const PRIVACY_MODE_CACHE_ENTRY: u32 = 131072u32;
pub const PRIVACY_TEMPLATE_ADVANCED: u32 = 101u32;
pub const PRIVACY_TEMPLATE_CUSTOM: u32 = 100u32;
pub const PRIVACY_TEMPLATE_HIGH: u32 = 1u32;
pub const PRIVACY_TEMPLATE_LOW: u32 = 5u32;
pub const PRIVACY_TEMPLATE_MAX: u32 = 5u32;
pub const PRIVACY_TEMPLATE_MEDIUM: u32 = 3u32;
pub const PRIVACY_TEMPLATE_MEDIUM_HIGH: u32 = 2u32;
pub const PRIVACY_TEMPLATE_MEDIUM_LOW: u32 = 4u32;
pub const PRIVACY_TEMPLATE_NO_COOKIES: u32 = 0u32;
pub const PRIVACY_TYPE_FIRST_PARTY: u32 = 0u32;
pub const PRIVACY_TYPE_THIRD_PARTY: u32 = 1u32;
pub type PROXY_AUTO_DETECT_TYPE = u32;
pub const PROXY_AUTO_DETECT_TYPE_DHCP: PROXY_AUTO_DETECT_TYPE = 1u32;
pub const PROXY_AUTO_DETECT_TYPE_DNS_A: PROXY_AUTO_DETECT_TYPE = 2u32;
pub const PROXY_TYPE_AUTO_DETECT: u32 = 8u32;
pub const PROXY_TYPE_AUTO_PROXY_URL: u32 = 4u32;
pub const PROXY_TYPE_DIRECT: u32 = 1u32;
pub const PROXY_TYPE_PROXY: u32 = 2u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct ProofOfPossessionCookieInfo {
pub name: super::super::Foundation::PWSTR,
pub data: super::super::Foundation::PWSTR,
pub flags: u32,
pub p3pHeader: super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for ProofOfPossessionCookieInfo {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for ProofOfPossessionCookieInfo {
fn clone(&self) -> Self {
*self
}
}
pub const ProofOfPossessionCookieInfoManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2844950405, data2: 41732, data3: 17296, data4: [139, 35, 167, 95, 28, 102, 134, 0] };
pub const REDIRECT_CACHE_ENTRY: u32 = 2048u32;
pub type REQUEST_TIMES = i32;
pub const NameResolutionStart: REQUEST_TIMES = 0i32;
pub const NameResolutionEnd: REQUEST_TIMES = 1i32;
pub const ConnectionEstablishmentStart: REQUEST_TIMES = 2i32;
pub const ConnectionEstablishmentEnd: REQUEST_TIMES = 3i32;
pub const TLSHandshakeStart: REQUEST_TIMES = 4i32;
pub const TLSHandshakeEnd: REQUEST_TIMES = 5i32;
pub const HttpRequestTimeMax: REQUEST_TIMES = 32i32;
pub const SECURITY_FLAG_128BIT: u32 = 536870912u32;
pub const SECURITY_FLAG_40BIT: u32 = 268435456u32;
pub const SECURITY_FLAG_56BIT: u32 = 1073741824u32;
pub const SECURITY_FLAG_FORTEZZA: u32 = 134217728u32;
pub const SECURITY_FLAG_IETFSSL4: u32 = 32u32;
pub const SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP: u32 = 32768u32;
pub const SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS: u32 = 16384u32;
pub const SECURITY_FLAG_IGNORE_REVOCATION: u32 = 128u32;
pub const SECURITY_FLAG_IGNORE_WEAK_SIGNATURE: u32 = 65536u32;
pub const SECURITY_FLAG_IGNORE_WRONG_USAGE: u32 = 512u32;
pub const SECURITY_FLAG_NORMALBITNESS: u32 = 268435456u32;
pub const SECURITY_FLAG_OPT_IN_WEAK_SIGNATURE: u32 = 131072u32;
pub const SECURITY_FLAG_PCT: u32 = 8u32;
pub const SECURITY_FLAG_PCT4: u32 = 16u32;
pub const SECURITY_FLAG_SSL: u32 = 2u32;
pub const SECURITY_FLAG_SSL3: u32 = 4u32;
pub const SECURITY_FLAG_UNKNOWNBIT: u32 = 2147483648u32;
pub const SHORTPATH_CACHE_ENTRY: u32 = 512u32;
pub const SPARSE_CACHE_ENTRY: u32 = 65536u32;
pub const STATIC_CACHE_ENTRY: u32 = 128u32;
pub const STICKY_CACHE_ENTRY: u32 = 4u32;
pub const TRACK_OFFLINE_CACHE_ENTRY: u32 = 16u32;
pub const TRACK_ONLINE_CACHE_ENTRY: u32 = 32u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct URLCACHE_ENTRY_INFO {
pub pwszSourceUrlName: super::super::Foundation::PWSTR,
pub pwszLocalFileName: super::super::Foundation::PWSTR,
pub dwCacheEntryType: u32,
pub dwUseCount: u32,
pub dwHitRate: u32,
pub dwSizeLow: u32,
pub dwSizeHigh: u32,
pub ftLastModifiedTime: super::super::Foundation::FILETIME,
pub ftExpireTime: super::super::Foundation::FILETIME,
pub ftLastAccessTime: super::super::Foundation::FILETIME,
pub ftLastSyncTime: super::super::Foundation::FILETIME,
pub pbHeaderInfo: *mut u8,
pub cbHeaderInfoSize: u32,
pub pbExtraData: *mut u8,
pub cbExtraDataSize: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for URLCACHE_ENTRY_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for URLCACHE_ENTRY_INFO {
fn clone(&self) -> Self {
*self
}
}
pub const URLHISTORY_CACHE_ENTRY: u32 = 2097152u32;
pub type URL_CACHE_LIMIT_TYPE = i32;
pub const UrlCacheLimitTypeIE: URL_CACHE_LIMIT_TYPE = 0i32;
pub const UrlCacheLimitTypeIETotal: URL_CACHE_LIMIT_TYPE = 1i32;
pub const UrlCacheLimitTypeAppContainer: URL_CACHE_LIMIT_TYPE = 2i32;
pub const UrlCacheLimitTypeAppContainerTotal: URL_CACHE_LIMIT_TYPE = 3i32;
pub const UrlCacheLimitTypeNum: URL_CACHE_LIMIT_TYPE = 4i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct URL_COMPONENTSA {
pub dwStructSize: u32,
pub lpszScheme: super::super::Foundation::PSTR,
pub dwSchemeLength: u32,
pub nScheme: INTERNET_SCHEME,
pub lpszHostName: super::super::Foundation::PSTR,
pub dwHostNameLength: u32,
pub nPort: u16,
pub lpszUserName: super::super::Foundation::PSTR,
pub dwUserNameLength: u32,
pub lpszPassword: super::super::Foundation::PSTR,
pub dwPasswordLength: u32,
pub lpszUrlPath: super::super::Foundation::PSTR,
pub dwUrlPathLength: u32,
pub lpszExtraInfo: super::super::Foundation::PSTR,
pub dwExtraInfoLength: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for URL_COMPONENTSA {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for URL_COMPONENTSA {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct URL_COMPONENTSW {
pub dwStructSize: u32,
pub lpszScheme: super::super::Foundation::PWSTR,
pub dwSchemeLength: u32,
pub nScheme: INTERNET_SCHEME,
pub lpszHostName: super::super::Foundation::PWSTR,
pub dwHostNameLength: u32,
pub nPort: u16,
pub lpszUserName: super::super::Foundation::PWSTR,
pub dwUserNameLength: u32,
pub lpszPassword: super::super::Foundation::PWSTR,
pub dwPasswordLength: u32,
pub lpszUrlPath: super::super::Foundation::PWSTR,
pub dwUrlPathLength: u32,
pub lpszExtraInfo: super::super::Foundation::PWSTR,
pub dwExtraInfoLength: u32,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for URL_COMPONENTSW {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for URL_COMPONENTSW {
fn clone(&self) -> Self {
*self
}
}
pub const WININET_API_FLAG_ASYNC: u32 = 1u32;
pub const WININET_API_FLAG_SYNC: u32 = 4u32;
pub const WININET_API_FLAG_USE_CONTEXT: u32 = 8u32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct WININET_PROXY_INFO {
pub fProxy: super::super::Foundation::BOOL,
pub fBypass: super::super::Foundation::BOOL,
pub ProxyScheme: INTERNET_SCHEME,
pub pwszProxy: super::super::Foundation::PWSTR,
pub ProxyPort: u16,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for WININET_PROXY_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for WININET_PROXY_INFO {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct WININET_PROXY_INFO_LIST {
pub dwProxyInfoCount: u32,
pub pProxyInfo: *mut WININET_PROXY_INFO,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for WININET_PROXY_INFO_LIST {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for WININET_PROXY_INFO_LIST {
fn clone(&self) -> Self {
*self
}
}
pub type WININET_SYNC_MODE = i32;
pub const WININET_SYNC_MODE_NEVER: WININET_SYNC_MODE = 0i32;
pub const WININET_SYNC_MODE_ON_EXPIRY: WININET_SYNC_MODE = 1i32;
pub const WININET_SYNC_MODE_ONCE_PER_SESSION: WININET_SYNC_MODE = 2i32;
pub const WININET_SYNC_MODE_ALWAYS: WININET_SYNC_MODE = 3i32;
pub const WININET_SYNC_MODE_AUTOMATIC: WININET_SYNC_MODE = 4i32;
pub const WININET_SYNC_MODE_DEFAULT: WININET_SYNC_MODE = 4i32;
pub type WPAD_CACHE_DELETE = i32;
pub const WPAD_CACHE_DELETE_CURRENT: WPAD_CACHE_DELETE = 0i32;
pub const WPAD_CACHE_DELETE_ALL: WPAD_CACHE_DELETE = 1i32;
pub const XDR_CACHE_ENTRY: u32 = 262144u32;
#[cfg(feature = "Win32_Foundation")]
pub type pfnInternetDeInitializeAutoProxyDll = ::core::option::Option<unsafe extern "system" fn(lpszmime: super::super::Foundation::PSTR, dwreserved: u32) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type pfnInternetGetProxyInfo = ::core::option::Option<unsafe extern "system" fn(lpszurl: super::super::Foundation::PSTR, dwurllength: u32, lpszurlhostname: super::super::Foundation::PSTR, dwurlhostnamelength: u32, lplpszproxyhostname: *mut super::super::Foundation::PSTR, lpdwproxyhostnamelength: *mut u32) -> super::super::Foundation::BOOL>;
#[cfg(feature = "Win32_Foundation")]
pub type pfnInternetInitializeAutoProxyDll = ::core::option::Option<unsafe extern "system" fn(dwversion: u32, lpszdownloadedtempfile: super::super::Foundation::PSTR, lpszmime: super::super::Foundation::PSTR, lpautoproxycallbacks: *mut AutoProxyHelperFunctions, lpautoproxyscriptbuffer: *mut AUTO_PROXY_SCRIPT_BUFFER) -> super::super::Foundation::BOOL>;
|
use quickcheck::{quickcheck, TestResult};
use std::fmt::{Debug, UpperHex, Write};
use std::mem;
use std::collections::HashSet;
use super::*;
fn setup(rom: Vec<u8>) -> (Cpu, Cpu) {
use crate::cart::CartConfig;
use crate::cart_header::CartType;
let rom_size = rom.len();
let cart_config = CartConfig { cart_type: CartType::NoMbc, rom_size, ram_size: 0 };
let mut actual = Cpu::new(Cart::new(rom.into_boxed_slice(), None, &cart_config).unwrap());
let mut expected = actual.clone();
actual.regs.pc.set(0);
expected.regs.pc.set(rom_size as u16);
(actual, expected)
}
/// Check if the actual and expected results are the same, pretty-printing any differences, and
/// panicking (failing the test) if there are any differences.
fn check_diff(actual: &Cpu, expected: &Cpu) -> TestResult {
let mut err = String::new();
diff_hex("AF", &actual.regs.get_16(Reg16::AF), &expected.regs.get_16(Reg16::AF), &mut err);
diff_hex("BC", &actual.regs.get_16(Reg16::BC), &expected.regs.get_16(Reg16::BC), &mut err);
diff_hex("DE", &actual.regs.get_16(Reg16::DE), &expected.regs.get_16(Reg16::DE), &mut err);
diff_hex("HL", &actual.regs.get_16(Reg16::HL), &expected.regs.get_16(Reg16::HL), &mut err);
diff_hex("SP", &actual.regs.get_16(Reg16::SP), &expected.regs.get_16(Reg16::SP), &mut err);
diff_hex("PC", &actual.regs.get_16(Reg16::PC), &expected.regs.get_16(Reg16::PC), &mut err);
diff(
"interrupts_enabled",
&actual.interrupts_enabled,
&expected.interrupts_enabled,
&mut err,
);
diff(
"pending_disable_interrupts",
&actual.pending_disable_interrupts,
&expected.pending_disable_interrupts,
&mut err,
);
diff(
"pending_enable_interrupts",
&actual.pending_enable_interrupts,
&expected.pending_enable_interrupts,
&mut err,
);
let actual_work_ram = actual.work_ram.iter();
let expected_work_ram = expected.work_ram.iter();
for (i, (actual_cell, expected_cell)) in actual_work_ram.zip(expected_work_ram).enumerate() {
let name = format!("work_ram location 0x{:02X}", i);
diff_hex(&name, actual_cell, expected_cell, &mut err);
}
let actual_rom = actual.cart.rom().iter();
let expected_rom = expected.cart.rom().iter();
for (i, (actual_cell, expected_cell)) in actual_rom.zip(expected_rom).enumerate() {
let name = format!("ROM location 0x{:02X}", i);
diff_hex(&name, actual_cell, expected_cell, &mut err);
}
if err.is_empty() {
TestResult::passed()
} else {
TestResult::error(err)
}
}
/// Returns whether the actual and expected numbers are the same. Pretty-prints the numbers in
/// hex if they differ.
fn diff_hex<T: Debug + Eq + UpperHex>(name: &str, actual: &T, expected: &T, err: &mut String) {
if actual != expected {
let width = mem::size_of::<T>() * 2; // Number of hex digits for type T.
writeln!(err, "\ndifference in {}:", name).unwrap();
writeln!(err, " actual: 0x{0:01$X} ({0:?})", actual, width).unwrap();
writeln!(err, " expected: 0x{0:01$X} ({0:?})", expected, width).unwrap();
}
}
/// Returns whether the actual and expected values are the same. Pretty-prints the values if
/// they differ.
fn diff<T: Debug + Eq>(name: &str, actual: &T, expected: &T, err: &mut String) {
if actual != expected {
writeln!(err, "\ndifference in {}:", name).unwrap();
writeln!(err, " actual: {:?}", actual).unwrap();
writeln!(err, " expected: {:?}", expected).unwrap();
}
}
/// A helper for the `cpu_tests!` macro. This handles the `setup` and `expect` sections, which
/// set fields on the initial and expected `Cpu`s, respectively.
macro_rules! setup_cpu {
(
$cpu:ident,
{
$( reg8 { $( $reg8:ident = $reg8val:expr ),* $(,)* } )*
$( reg16 { $( $reg16:ident = $reg16val:expr ),* $(,)* } )*
}
) => ({
$( $( $cpu.regs.set_8(Reg8::$reg8, $reg8val); )* )*
$( $( $cpu.regs.set_16(Reg16::$reg16, $reg16val); )* )*
})
}
/// A macro for writing concise machine code CPU tests.
///
/// # Format
///
/// ```
/// test_name(var1: var1_ty, var2: var2_ty, ...) {
/// rom = [0x00, 0x01, ...],
/// setup {
/// reg8 {
/// A = 0,
/// B = 1,
/// ...
/// }
/// reg16 {
/// AF = 0,
/// DE = 1,
/// ...
/// }
/// }
/// expect {
/// reg8 {
/// A = 0,
/// B = 1,
/// ...
/// }
/// reg16 {
/// AF = 0,
/// DE = 1,
/// ...
/// }
/// }
/// }
/// ```
///
/// The arguments (`var1`, `var2`, ...) are randomly generated values of their repective types
/// from quickcheck. The argument types must each implement quickcheck's `Arbitrary` trait.
/// Many primitive and standard library types already do.
///
/// The `setup` and `expect` sections are optional, as are their `reg8` and `reg16`
/// subsections. The `reg8` and `reg16` sections must use identifiers matching the `Reg8` and
/// `Reg16` enum variants, respectively.
macro_rules! cpu_tests {
(
$(
$name:ident(
$($var:ident : $var_ty:ty),* $(,)*
) {
rom = [ $( $rom:expr ),* $(,)* ] $(,)*
$(setup $setup:tt)*
$(expect $expect:tt)*
}
)*
) => (
$(
quickcheck! {
#[allow(unused_mut)]
fn $name(
$($var : $var_ty),*
) -> TestResult {
let rom = vec![ $( $rom ),* ];
let rom_size = rom.len();
let (mut actual, mut expected) = setup(rom);
$( setup_cpu!(actual, $setup); )*
$( setup_cpu!(expected, $expect); )*
while actual.regs.pc.get() as usize != rom_size {
actual.step(false, false, &HashSet::new());
}
check_diff(&actual, &expected)
}
}
)*
);
}
// Helper functions for putting low/high bytes of 16-bit values into test ROMs.
fn low(x: u16) -> u8 {
(x & 0xFF) as u8
}
fn high(x: u16) -> u8 {
((x >> 8) & 0xFF) as u8
}
// The actual tests.
cpu_tests! {
test_nop() {
rom = [0x00], // nop
}
test_ld_reg8_imm8(a: u8, b: u8, c: u8, d: u8, e: u8, h: u8, l: u8) {
rom = [
0x3E, a, // ld a, $a
0x06, b, // ld b, $b
0x0E, c, // ld c, $c
0x16, d, // ld d, $d
0x1E, e, // ld e, $e
0x26, h, // ld h, $h
0x2E, l, // ld l, $l
],
setup { reg8 { A = 0, B = 0, C = 0, D = 0, E = 0, H = 0, L = 0 } }
expect { reg8 { A = a, B = b, C = c, D = d, E = e, H = h, L = l } }
}
test_ld_reg16_imm16(bc: u16, de: u16, hl: u16, sp: u16) {
rom = [
0x01, low(bc), high(bc), // ld bc, $bc
0x11, low(de), high(de), // ld de, $de
0x21, low(hl), high(hl), // ld hl, $hl
0x31, low(sp), high(sp), // ld sp, $sp
],
setup { reg16 { BC = 0, DE = 0, HL = 0, SP = 0 } }
expect { reg16 { BC = bc, DE = de, HL = hl, SP = sp } }
}
test_jp_imm16_unconditional() {
// Test that we can jump past a halt instruction without stopping.
rom = [
0xC3, 0x04, 0x00, // jp 0x0004
0x76, // halt
],
}
}
|
use ::TypeContainer;
pub use ::errors::*;
pub trait CompilePass {
fn run(typ: &mut TypeContainer) -> Result<()>;
}
pub mod assign_parent;
pub mod assign_ident;
pub mod resolve_reference;
|
use std::fs;
use std::time::Instant;
use std::collections::HashMap;
fn process_mask(mask: &String, value: u64) -> u64 {
let repr = format!("{:036b}", value);
let mut res = String::new();
for it in mask.chars().zip(repr.chars()) {
let (m, r) = it;
let r = match m {
'1' => { '1' }
'0' => { '0' }
_ => { r }
};
res.push(r);
}
let res = u64::from_str_radix(&*res, 2).unwrap();
res
}
fn part1(puzzle: Vec<String>) -> usize {
let mut map: HashMap<u64, u64> = HashMap::new();
let mut mask = String::new();
for p in puzzle {
if p.starts_with("mask = ") {
mask = p.replace("mask = ", "");
} else {
let mut it = p.split("] = ");
let address = it.next().unwrap().replace("mem[", "").parse::<u64>().unwrap();
let value = it.next().unwrap().parse::<u64>().unwrap();
map.insert(address, process_mask(&mask, value));
}
}
let mut s: u64 = 0;
map.retain(|_key, value| {
s += *value;
false
});
s as usize
}
fn process_mask2(mask: &String, value: u64) -> Vec<u64> {
let repr = format!("{:036b}", value);
let count = 1usize << mask.matches('X').count();
let mut res: Vec<String> = vec![String::new(); count];
for it in mask.chars().zip(repr.chars()) {
let (m, r) = it;
for re in res.iter_mut() {
let r = match m {
'1' => { '1' }
'0' => { r }
_ => {
'X'
}
};
re.push(r);
}
}
let mut fin: Vec<u64> = vec![];
for (i, pair) in res.iter_mut().enumerate() {
let number=format!("{:0width$b}", i,width=mask.matches('X').count());
let mut temp =pair.clone();
for el in number.chars(){
temp=temp.replacen('X', &*el.to_string(), 1);
}
fin.push(u64::from_str_radix(&*temp, 2).unwrap());
}
fin
}
fn part2(puzzle: Vec<String>) -> usize {
let mut map: HashMap<u64, u64> = HashMap::new();
let mut mask = String::new();
for p in puzzle {
if p.starts_with("mask = ") {
mask = p.replace("mask = ", "");
} else {
let mut it = p.split("] = ");
let address = it.next().unwrap().replace("mem[", "").parse::<u64>().unwrap();
let value = it.next().unwrap().parse::<u64>().unwrap();
let addresses = process_mask2(&mask, address);
for add in addresses {
map.insert(add, value);
}
}
}
let mut s: u64 = 0;
map.retain(|_key, value| {
s += *value;
false
});
s as usize
}
fn main() {
let input = fs::read_to_string("input/input.txt")
.expect("Something went wrong reading the file");
let lines = input.lines();
let mut puzzle: Vec<String> = vec![];
for line in lines {
puzzle.push(line.parse::<String>().expect("Ouf that's not a string !"))
}
println!("Running part1");
let now = Instant::now();
println!("Found {}", part1(puzzle.clone()));
println!("Took {}us", now.elapsed().as_micros());
println!("Running part2");
let now = Instant::now();
println!("Found {}", part2(puzzle.clone()));
println!("Took {}ms", now.elapsed().as_millis());
} |
use serde::Deserialize;
#[derive(Deserialize, Debug)]
pub struct AircraftModelRaw {
pub code: Option<String>,
pub text: Option<String>,
} |
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Write;
use common_expression::types::*;
use common_expression::FromData;
use goldenfile::Mint;
use super::run_ast;
#[test]
fn test_variant() {
let mut mint = Mint::new("tests/it/scalars/testdata");
let file = &mut mint.new_goldenfile("variant.txt").unwrap();
test_parse_json(file);
test_try_parse_json(file);
test_check_json(file);
test_length(file);
test_json_object_keys(file);
test_get(file);
test_get_ignore_case(file);
test_get_path(file);
test_json_extract_path_text(file);
test_as_type(file);
test_to_type(file);
test_try_to_type(file);
test_json_object(file);
test_json_object_keep_null(file);
}
fn test_parse_json(file: &mut impl Write) {
run_ast(file, "parse_json(NULL)", &[]);
run_ast(file, "parse_json('nuLL')", &[]);
run_ast(file, "parse_json('null')", &[]);
run_ast(file, "parse_json(' \t')", &[]);
run_ast(file, "parse_json('true')", &[]);
run_ast(file, "parse_json('false')", &[]);
run_ast(file, "parse_json('\"测试\"')", &[]);
run_ast(file, "parse_json('1234')", &[]);
run_ast(file, "parse_json('[1,2,3,4]')", &[]);
run_ast(file, "parse_json('{\"a\":\"b\",\"c\":\"d\"}')", &[]);
run_ast(file, "parse_json(s)", &[(
"s",
StringType::from_data(vec![
r#"null"#,
r#"true"#,
r#"9223372036854775807"#,
r#"-32768"#,
r#"1234.5678"#,
r#"1.912e2"#,
r#""\\\"abc\\\"""#,
r#""databend""#,
r#"{"k":"v","a":"b"}"#,
r#"[1,2,3,["a","b","c"]]"#,
]),
)]);
run_ast(file, "parse_json(s)", &[(
"s",
StringType::from_data_with_validity(&["true", "false", "", "1234"], vec![
true, true, false, true,
]),
)]);
}
fn test_try_parse_json(file: &mut impl Write) {
run_ast(file, "try_parse_json(NULL)", &[]);
run_ast(file, "try_parse_json('nuLL')", &[]);
run_ast(file, "try_parse_json('null')", &[]);
run_ast(file, "try_parse_json('true')", &[]);
run_ast(file, "try_parse_json('false')", &[]);
run_ast(file, "try_parse_json('\"测试\"')", &[]);
run_ast(file, "try_parse_json('1234')", &[]);
run_ast(file, "try_parse_json('[1,2,3,4]')", &[]);
run_ast(file, "try_parse_json('{\"a\":\"b\",\"c\":\"d\"}')", &[]);
run_ast(file, "try_parse_json(s)", &[(
"s",
StringType::from_data(vec![
r#"null"#,
r#"true"#,
r#"9223372036854775807"#,
r#"-32768"#,
r#"1234.5678"#,
r#"1.912e2"#,
r#""\\\"abc\\\"""#,
r#""databend""#,
r#"{"k":"v","a":"b"}"#,
r#"[1,2,3,["a","b","c"]]"#,
]),
)]);
run_ast(file, "try_parse_json(s)", &[(
"s",
StringType::from_data_with_validity(&["true", "ttt", "", "1234"], vec![
true, true, false, true,
]),
)]);
}
fn test_check_json(file: &mut impl Write) {
run_ast(file, "check_json(NULL)", &[]);
run_ast(file, "check_json('true')", &[]);
run_ast(file, "check_json('nuLL')", &[]);
run_ast(file, "check_json(s)", &[(
"s",
StringType::from_data(vec![r#"null"#, r#"abc"#, r#"true"#]),
)]);
run_ast(file, "check_json(s)", &[(
"s",
StringType::from_data_with_validity(&["true", "ttt", "", "1234"], vec![
true, true, false, true,
]),
)]);
}
fn test_length(file: &mut impl Write) {
run_ast(file, "length(parse_json('1234'))", &[]);
run_ast(file, "length(parse_json('[1,2,3,4]'))", &[]);
run_ast(file, "length(parse_json('{\"k\":\"v\"}'))", &[]);
run_ast(file, "length(parse_json(s))", &[(
"s",
StringType::from_data(vec!["true", "[1,2,3,4]", "[\"a\",\"b\",\"c\"]"]),
)]);
run_ast(file, "length(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(
&["true", "[1,2,3,4]", "", "[\"a\",\"b\",\"c\"]"],
vec![true, true, false, true],
),
)]);
}
fn test_json_object_keys(file: &mut impl Write) {
run_ast(file, "json_object_keys(parse_json('[1,2,3,4]'))", &[]);
run_ast(
file,
"json_object_keys(parse_json('{\"k1\":\"v1\",\"k2\":\"v2\"}'))",
&[],
);
run_ast(file, "json_object_keys(parse_json(s))", &[(
"s",
StringType::from_data(vec![
"[1,2,3,4]",
"{\"a\":\"b\",\"c\":\"d\"}",
"{\"k1\":\"v1\",\"k2\":\"v2\"}",
]),
)]);
run_ast(file, "json_object_keys(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(
&[
"[1,2,3,4]",
"{\"a\":\"b\",\"c\":\"d\"}",
"",
"{\"k1\":\"v1\",\"k2\":\"v2\"}",
],
vec![true, true, false, true],
),
)]);
}
fn test_get(file: &mut impl Write) {
run_ast(file, "parse_json('null')[1]", &[]);
run_ast(file, "parse_json('null')['k']", &[]);
run_ast(file, "parse_json('[1,2,3,4]')[1]", &[]);
run_ast(file, "parse_json('[1,2,3,4]')[2+3]", &[]);
run_ast(file, "parse_json('{\"k\":\"v\"}')['k']", &[]);
run_ast(file, "parse_json('{\"k\":\"v\"}')['x']", &[]);
run_ast(file, "CAST(('a', 'b') AS VARIANT)['2']", &[]);
run_ast(file, "parse_json(s)[i]", &[
(
"s",
StringType::from_data(vec!["true", "[1,2,3,4]", "[\"a\",\"b\",\"c\"]"]),
),
("i", UInt64Type::from_data(vec![0u64, 0, 1])),
]);
run_ast(file, "parse_json(s)[i]", &[
(
"s",
StringType::from_data_with_validity(
&["true", "[1,2,3,4]", "", "[\"a\",\"b\",\"c\"]"],
vec![true, true, false, true],
),
),
(
"i",
UInt64Type::from_data_with_validity(vec![0u64, 2, 0, 1], vec![
false, true, false, true,
]),
),
]);
run_ast(file, "parse_json(s)[k]", &[
(
"s",
StringType::from_data(vec!["true", "{\"k\":1}", "{\"a\":\"b\"}"]),
),
("k", StringType::from_data(vec!["k", "k", "x"])),
]);
run_ast(file, "parse_json(s)[k]", &[
(
"s",
StringType::from_data_with_validity(&["true", "{\"k\":1}", "", "{\"a\":\"b\"}"], vec![
true, true, false, true,
]),
),
("k", StringType::from_data(vec!["", "k", "", "a"])),
]);
}
fn test_get_ignore_case(file: &mut impl Write) {
run_ast(
file,
"get_ignore_case(parse_json('{\"Aa\":1, \"aA\":2, \"aa\":3}'), 'AA')",
&[],
);
run_ast(
file,
"get_ignore_case(parse_json('{\"Aa\":1, \"aA\":2, \"aa\":3}'), 'aa')",
&[],
);
run_ast(
file,
"get_ignore_case(parse_json('{\"Aa\":1, \"aA\":2, \"aa\":3}'), 'bb')",
&[],
);
run_ast(file, "get_ignore_case(parse_json(s), k)", &[
(
"s",
StringType::from_data(vec!["true", "{\"k\":1}", "{\"a\":\"b\"}"]),
),
("k", StringType::from_data(vec!["k", "K", "A"])),
]);
run_ast(file, "get_ignore_case(parse_json(s), k)", &[
(
"s",
StringType::from_data_with_validity(&["true", "{\"k\":1}", "", "{\"a\":\"b\"}"], vec![
true, true, false, true,
]),
),
("k", StringType::from_data(vec!["", "K", "", "A"])),
]);
}
fn test_get_path(file: &mut impl Write) {
run_ast(file, "get_path(parse_json('[[1,2],3]'), '[0]')", &[]);
run_ast(file, "get_path(parse_json('[[1,2],3]'), '[0][1]')", &[]);
run_ast(file, "get_path(parse_json('[1,2,3]'), '[0]')", &[]);
run_ast(file, "get_path(parse_json('[1,2,3]'), 'k2:k3')", &[]);
run_ast(
file,
"get_path(parse_json('{\"a\":{\"b\":2}}'), '[\"a\"][\"b\"]')",
&[],
);
run_ast(file, "get_path(parse_json('{\"a\":{\"b\":2}}'), 'a:b')", &[
]);
run_ast(
file,
"get_path(parse_json('{\"a\":{\"b\":2}}'), '[\"a\"]')",
&[],
);
run_ast(file, "get_path(parse_json('{\"a\":{\"b\":2}}'), 'a')", &[]);
run_ast(file, "get_path(parse_json(s), k)", &[
(
"s",
StringType::from_data(vec!["true", "{\"k\":1}", "[\"a\",\"b\"]"]),
),
("k", StringType::from_data(vec!["k", "[\"k\"]", "[\"a\"]"])),
]);
run_ast(file, "get_path(parse_json(s), k)", &[
(
"s",
StringType::from_data_with_validity(&["true", "{\"k\":1}", "", "[\"a\",\"b\"]"], vec![
true, true, false, true,
]),
),
(
"k",
StringType::from_data(vec!["[0]", "[\"k\"]", "", "[0]"]),
),
]);
}
fn test_json_extract_path_text(file: &mut impl Write) {
run_ast(file, "json_extract_path_text('[[1,2],3]', '[0]')", &[]);
run_ast(file, "json_extract_path_text('[[1,2],3]', '[0][1]')", &[]);
run_ast(file, "json_extract_path_text('[1,2,3]', '[0]')", &[]);
run_ast(file, "json_extract_path_text('[1,2,3]', 'k2:k3')", &[]);
run_ast(
file,
"json_extract_path_text('{\"a\":{\"b\":2}}', '[\"a\"][\"b\"]')",
&[],
);
run_ast(
file,
"json_extract_path_text('{\"a\":{\"b\":2}}', 'a:b')",
&[],
);
run_ast(
file,
"json_extract_path_text('{\"a\":{\"b\":2}}', '[\"a\"]')",
&[],
);
run_ast(file, "json_extract_path_text('{\"a\":{\"b\":2}}', 'a')", &[
]);
run_ast(file, "json_extract_path_text(s, k)", &[
(
"s",
StringType::from_data(vec!["true", "{\"k\":1}", "[\"a\",\"b\"]"]),
),
("k", StringType::from_data(vec!["k", "[\"k\"]", "[\"a\"]"])),
]);
run_ast(file, "json_extract_path_text(s, k)", &[
(
"s",
StringType::from_data_with_validity(&["true", "{\"k\":1}", "", "[\"a\",\"b\"]"], vec![
true, true, false, true,
]),
),
(
"k",
StringType::from_data(vec!["[0]", "[\"k\"]", "", "[0]"]),
),
]);
}
fn test_as_type(file: &mut impl Write) {
run_ast(file, "as_boolean(parse_json('true'))", &[]);
run_ast(file, "as_boolean(parse_json('123'))", &[]);
run_ast(file, "as_integer(parse_json('true'))", &[]);
run_ast(file, "as_integer(parse_json('123'))", &[]);
run_ast(file, "as_float(parse_json('\"ab\"'))", &[]);
run_ast(file, "as_float(parse_json('12.34'))", &[]);
run_ast(file, "as_string(parse_json('\"ab\"'))", &[]);
run_ast(file, "as_string(parse_json('12.34'))", &[]);
run_ast(file, "as_array(parse_json('[1,2,3]'))", &[]);
run_ast(file, "as_array(parse_json('{\"a\":\"b\"}'))", &[]);
run_ast(file, "as_object(parse_json('[1,2,3]'))", &[]);
run_ast(file, "as_object(parse_json('{\"a\":\"b\"}'))", &[]);
let columns = &[(
"s",
StringType::from_data(vec![
"true",
"123",
"12.34",
"\"ab\"",
"[1,2,3]",
"{\"a\":\"b\"}",
]),
)];
run_ast(file, "as_boolean(parse_json(s))", columns);
run_ast(file, "as_boolean(try_parse_json(s))", columns);
run_ast(file, "as_integer(parse_json(s))", columns);
run_ast(file, "as_integer(try_parse_json(s))", columns);
run_ast(file, "as_float(parse_json(s))", columns);
run_ast(file, "as_float(try_parse_json(s))", columns);
run_ast(file, "as_string(parse_json(s))", columns);
run_ast(file, "as_string(try_parse_json(s))", columns);
run_ast(file, "as_array(parse_json(s))", columns);
run_ast(file, "as_array(try_parse_json(s))", columns);
run_ast(file, "as_object(parse_json(s))", columns);
run_ast(file, "as_object(try_parse_json(s))", columns);
}
fn test_to_type(file: &mut impl Write) {
run_ast(file, "to_boolean(parse_json('true'))", &[]);
run_ast(file, "to_boolean(parse_json('123'))", &[]);
run_ast(file, "to_boolean(parse_json('\"abc\"'))", &[]);
run_ast(file, "to_uint64(parse_json('123'))", &[]);
run_ast(file, "to_uint64(parse_json('-123'))", &[]);
run_ast(file, "to_uint64(parse_json('\"abc\"'))", &[]);
run_ast(file, "to_int64(parse_json('123'))", &[]);
run_ast(file, "to_int64(parse_json('-123'))", &[]);
run_ast(file, "to_int64(parse_json('\"abc\"'))", &[]);
run_ast(file, "to_float64(parse_json('12.34'))", &[]);
run_ast(file, "to_float64(parse_json('\"abc\"'))", &[]);
run_ast(file, "to_date(parse_json('\"2023-01-01\"'))", &[]);
run_ast(file, "to_date(parse_json('\"abc\"'))", &[]);
run_ast(
file,
"to_timestamp(parse_json('\"2023-01-01 00:00:00\"'))",
&[],
);
run_ast(file, "to_timestamp(parse_json('\"abc\"'))", &[]);
run_ast(file, "to_string(parse_json('12.34'))", &[]);
run_ast(file, "to_string(parse_json('\"abc\"'))", &[]);
run_ast(file, "to_boolean(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(&["true", "", "true"], vec![true, false, true]),
)]);
run_ast(file, "to_int64(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(&["1", "", "-10"], vec![true, false, true]),
)]);
run_ast(file, "to_uint64(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(&["1", "", "20"], vec![true, false, true]),
)]);
run_ast(file, "to_float64(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(&["1.2", "", "100.2"], vec![true, false, true]),
)]);
run_ast(file, "to_date(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(&["\"2020-01-01\"", "", "\"2023-10-01\""], vec![
true, false, true,
]),
)]);
run_ast(file, "to_timestamp(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(
&["\"2020-01-01 00:00:00\"", "", "\"2023-10-01 10:11:12\""],
vec![true, false, true],
),
)]);
run_ast(file, "to_string(parse_json(s))", &[(
"s",
StringType::from_data_with_validity(&["\"abc\"", "", "123"], vec![true, false, true]),
)]);
}
fn test_try_to_type(file: &mut impl Write) {
run_ast(file, "try_to_boolean(parse_json('true'))", &[]);
run_ast(file, "try_to_boolean(parse_json('123'))", &[]);
run_ast(file, "try_to_boolean(parse_json('\"abc\"'))", &[]);
run_ast(file, "try_to_uint64(parse_json('123'))", &[]);
run_ast(file, "try_to_uint64(parse_json('-123'))", &[]);
run_ast(file, "try_to_uint64(parse_json('\"abc\"'))", &[]);
run_ast(file, "try_to_int64(parse_json('123'))", &[]);
run_ast(file, "try_to_int64(parse_json('-123'))", &[]);
run_ast(file, "try_to_int64(parse_json('\"abc\"'))", &[]);
run_ast(file, "try_to_float64(parse_json('12.34'))", &[]);
run_ast(file, "try_to_float64(parse_json('\"abc\"'))", &[]);
run_ast(file, "try_to_date(parse_json('\"2023-01-01\"'))", &[]);
run_ast(file, "try_to_date(parse_json('\"abc\"'))", &[]);
run_ast(
file,
"try_to_timestamp(parse_json('\"2023-01-01 00:00:00\"'))",
&[],
);
run_ast(file, "try_to_timestamp(parse_json('\"abc\"'))", &[]);
run_ast(file, "try_to_string(parse_json('12.34'))", &[]);
run_ast(file, "try_to_string(parse_json('\"abc\"'))", &[]);
let columns = &[(
"s",
StringType::from_data_with_validity(
&[
"true",
"123",
"-100",
"12.34",
"",
"\"2020-01-01\"",
"\"2021-01-01 20:00:00\"",
"\"abc\"",
],
vec![true, true, true, true, false, true, true, true],
),
)];
run_ast(file, "try_to_boolean(parse_json(s))", columns);
run_ast(file, "try_to_int64(parse_json(s))", columns);
run_ast(file, "try_to_uint64(parse_json(s))", columns);
run_ast(file, "try_to_float64(parse_json(s))", columns);
run_ast(file, "try_to_date(parse_json(s))", columns);
run_ast(file, "try_to_timestamp(parse_json(s))", columns);
run_ast(file, "try_to_string(parse_json(s))", columns);
}
fn test_json_object(file: &mut impl Write) {
run_ast(file, "json_object()", &[]);
run_ast(
file,
"json_object('a', true, 'b', 1, 'c', 'str', 'd', [1,2], 'e', {'k':'v'})",
&[],
);
run_ast(
file,
"json_object('k1', 1, 'k2', null, 'k3', 2, null, 3)",
&[],
);
run_ast(file, "json_object('k1', 1, 'k1')", &[]);
run_ast(file, "json_object('k1', 1, 'k1', 2)", &[]);
run_ast(file, "json_object(1, 'k1', 2, 'k2')", &[]);
run_ast(file, "json_object(k1, v1, k2, v2)", &[
(
"k1",
StringType::from_data_with_validity(&["a1", "b1", "", "d1"], vec![
true, true, false, true,
]),
),
(
"v1",
StringType::from_data_with_validity(&["j1", "k1", "l1", ""], vec![
true, true, true, false,
]),
),
(
"k2",
StringType::from_data_with_validity(&["a2", "", "c2", "d2"], vec![
true, false, true, true,
]),
),
(
"v2",
StringType::from_data_with_validity(&["j2", "k2", "l2", "m2"], vec![
true, true, true, true,
]),
),
]);
}
fn test_json_object_keep_null(file: &mut impl Write) {
run_ast(file, "json_object_keep_null()", &[]);
run_ast(
file,
"json_object_keep_null('a', true, 'b', 1, 'c', 'str', 'd', [1,2], 'e', {'k':'v'})",
&[],
);
run_ast(
file,
"json_object_keep_null('k1', 1, 'k2', null, 'k3', 2, null, 3)",
&[],
);
run_ast(file, "json_object_keep_null('k1', 1, 'k1')", &[]);
run_ast(file, "json_object_keep_null('k1', 1, 'k1', 2)", &[]);
run_ast(file, "json_object_keep_null(1, 'k1', 2, 'k2')", &[]);
run_ast(file, "json_object_keep_null(k1, v1, k2, v2)", &[
(
"k1",
StringType::from_data_with_validity(&["a1", "b1", "", "d1"], vec![
true, true, false, true,
]),
),
(
"v1",
StringType::from_data_with_validity(&["j1", "k1", "l1", ""], vec![
true, true, true, false,
]),
),
(
"k2",
StringType::from_data_with_validity(&["a2", "", "c2", "d2"], vec![
true, false, true, true,
]),
),
(
"v2",
StringType::from_data_with_validity(&["j2", "k2", "l2", "m2"], vec![
true, true, true, true,
]),
),
]);
}
|
pub mod client;
pub mod jwt;
pub mod validator;
lazy_static! {
static ref HASH_ROUNDS: String = std::env::var("HASH_ROUNDS").unwrap();
}
/*
pub fn hash_password(plain: &str) -> Result<String, ServiceError> {
// get the hashing cost from the env variable or use default
/*
let hashing_cost: u32 = match HASH_ROUNDS {
Ok(cost) => cost.parse().unwrap_or(DEFAULT_COST),
_ => DEFAULT_COST,
};
*/
let hashing_cost: u32 = HASH_ROUNDS.parse().unwrap_or(DEFAULT_COST);
println!("{}", &hashing_cost);
hash(plain, hashing_cost).map_err(|_| ServiceError::InternalServerError)
}
*/
|
extern crate proc_macro;
use proc_macro::{TokenStream};
use syn::{parse_macro_input};
use quote::quote;
use syn::parse::{Parse, ParseStream};
struct ConcatImplInfo {
generics1: Vec<syn::Ident>,
generics2: Vec<syn::Ident>,
}
impl Parse for ConcatImplInfo {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut generics1 = Vec::new();
loop {
generics1.push(input.parse::<syn::Ident>()?);
if let Err(_) = input.parse::<syn::Token![,]>() {
input.parse::<syn::Token![;]>()?;
break;
}
}
let mut generics2 = Vec::new();
loop {
generics2.push(input.parse::<syn::Ident>()?);
if let Err(_) = input.parse::<syn::Token![,]>() {
input.parse::<syn::Token![;]>()?;
break;
}
}
Ok(ConcatImplInfo {
generics1,
generics2,
})
}
}
/// Generate impls of `fntools::tuple::concat::TupleConcat`
#[proc_macro]
pub fn concat_impls(input: TokenStream) -> TokenStream {
let ConcatImplInfo { generics1, generics2 } = parse_macro_input!(input as ConcatImplInfo);
let mut streams = Vec::new();
for i in 0..generics1.len() {
let first = &generics1[..=i];
for j in 0..generics2.len() {
let second = &generics2[..=j];
if first.len() + second.len() > 12 { break; }
streams.push(quote! {
impl<#(#first,)* #(#second,)*> TupleConcat<(#(#second,)*)> for (#(#first,)*) {
type Res = (#(#first,)* #(#second,)*);
#[inline]
#[allow(non_snake_case)]
fn concat(self, other: (#(#second,)*)) -> Self::Res {
let (#(#first,)*) = self;
let (#(#second,)*) = other;
(#(#first,)* #(#second,)*)
}
}
});
}
}
let tokens = quote! {
#(#streams)*
};
tokens.into()
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use fidl_fuchsia_netstack as fidl;
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum IpAddressConfig {
StaticIp(fidl_fuchsia_net_ext::Subnet),
Dhcp,
}
impl Into<fidl::IpAddressConfig> for IpAddressConfig {
fn into(self) -> fidl::IpAddressConfig {
match self {
IpAddressConfig::Dhcp => fidl::IpAddressConfig::Dhcp(false),
IpAddressConfig::StaticIp(subnet) => fidl::IpAddressConfig::StaticIp(subnet.into()),
}
}
}
pub struct RouteTableEntry2 {
pub destination: fidl_fuchsia_net_ext::IpAddress,
pub netmask: fidl_fuchsia_net_ext::IpAddress,
pub gateway: Option<fidl_fuchsia_net_ext::IpAddress>,
pub nicid: u32,
pub metric: u32,
}
impl From<fidl::RouteTableEntry2> for RouteTableEntry2 {
fn from(
fidl::RouteTableEntry2 {
destination, netmask, gateway, nicid, metric
}: fidl::RouteTableEntry2,
) -> Self {
let destination = destination.into();
let netmask = netmask.into();
let gateway = gateway.map(|gateway| (*gateway).into());
Self { destination, netmask, gateway, nicid, metric }
}
}
|
use std::fmt;
use std::ops::Deref;
use std::os::unix::io::AsRawFd;
use super::{acpi, IoCtlIterator};
use crate::platform::traits::{BatteryIterator, BatteryManager};
use crate::{Error, Result};
pub struct IoCtlManager(acpi::AcpiDevice);
impl BatteryManager for IoCtlManager {
type Iterator = IoCtlIterator;
fn new() -> Result<Self> {
Ok(Self(acpi::AcpiDevice::new()?))
}
fn refresh(&self, device: &mut <Self::Iterator as BatteryIterator>::Device) -> Result<()> {
let bif = self.0.bif(device.unit())?;
let bst = self.0.bst(device.unit())?;
match (bif, bst) {
(Some(bif), Some(bst)) => device.refresh(bif, bst),
(None, _) => Err(Error::invalid_data("Returned bif struct is invalid")),
(_, None) => Err(Error::invalid_data("Returned bst struct is invalid")),
}
}
}
impl Deref for IoCtlManager {
type Target = acpi::AcpiDevice;
fn deref(&self) -> &acpi::AcpiDevice {
&self.0
}
}
impl fmt::Debug for IoCtlManager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("FreeBSD").field("fd", &self.0.as_raw_fd()).finish()
}
}
|
use bevy::math::{vec2, Vec2};
use noise::*;
use rand::Rng;
use utils::{NoiseMapBuilder, PlaneMapBuilder};
use crate::texture_atlas::Rectangle;
#[derive(Debug)]
pub struct Graph {
pub nodes: Vec<Node>,
pub connections: Vec<Connection>,
}
impl Graph {
pub fn new(_node_count: i32, width: i32, height: i32, seed: u32) -> Self {
let mut rng = rand::thread_rng();
let mut nodes = Vec::new();
let mut connections = Vec::new();
let noise = noise::Perlin::new().set_seed(seed);
let map = PlaneMapBuilder::new(&noise)
.set_size(10000, 10000)
.set_x_bounds(-500.0, 500.0)
.set_y_bounds(-500.0, 500.0)
.build();
for h in (-height)..(height) {
for w in (-width)..(width) {
if map.get_value((w + width) as usize, (h + height) as usize) > 0.0 {
nodes.push(Node::new(
vec2((w * 500) as f32, (h * 500) as f32),
rng.gen_range(0, 227),
// model 512
// 125,
));
}
}
}
for (i, _node) in nodes.iter().enumerate() {
if i + 1 != nodes.len() {
connections.push(Connection(i as i32, (i + 1) as i32))
}
}
Self { nodes, connections }
}
}
#[derive(Debug)]
pub struct Node {
pub position: Vec2,
pub size: Rectangle,
pub texture: u32,
}
impl Node {
fn new(position: Vec2, texture: u32) -> Self {
Node {
position,
size: Rectangle::default(),
texture,
}
}
}
#[derive(Debug)]
pub struct Connection(pub i32, pub i32);
pub struct Ship {
pub vert_indices: std::ops::Range<u32>,
pub texture_index: f32,
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_catalog::table_context::TableContext;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::DataSchema;
use common_expression::DataSchemaRef;
use common_pipeline_sources::AsyncSourcer;
use common_sql::plans::InsertInputSource;
use common_sql::plans::Plan;
use common_sql::plans::Replace;
use common_sql::NameResolutionContext;
use crate::interpreters::interpreter_insert::ValueSource;
use crate::interpreters::Interpreter;
use crate::interpreters::InterpreterPtr;
use crate::interpreters::SelectInterpreter;
use crate::pipelines::processors::TransformCastSchema;
use crate::pipelines::processors::TransformResortAddOn;
use crate::pipelines::PipelineBuildResult;
use crate::sessions::QueryContext;
#[allow(dead_code)]
pub struct ReplaceInterpreter {
ctx: Arc<QueryContext>,
plan: Replace,
}
impl ReplaceInterpreter {
pub fn try_create(ctx: Arc<QueryContext>, plan: Replace) -> Result<InterpreterPtr> {
Ok(Arc::new(ReplaceInterpreter { ctx, plan }))
}
}
#[async_trait::async_trait]
impl Interpreter for ReplaceInterpreter {
fn name(&self) -> &str {
"ReplaceIntoInterpreter"
}
async fn execute2(&self) -> Result<PipelineBuildResult> {
self.check_on_conflicts()?;
let plan = &self.plan;
let table = self
.ctx
.get_table(&plan.catalog, &plan.database, &plan.table)
.await?;
if table.get_table_info().meta.default_cluster_key_id.is_some() {
return Err(ErrorCode::StorageOther(
"replace into table with cluster key definition is not supported yet",
));
}
let mut pipeline = self
.connect_input_source(self.ctx.clone(), &self.plan.source, self.plan.schema())
.await?;
pipeline
.main_pipeline
.add_transform(|transform_input_port, transform_output_port| {
TransformResortAddOn::try_create(
self.ctx.clone(),
transform_input_port,
transform_output_port,
self.plan.schema(),
table.clone(),
)
})?;
let on_conflict_fields = plan.on_conflict_fields.clone();
table
.replace_into(
self.ctx.clone(),
&mut pipeline.main_pipeline,
on_conflict_fields,
)
.await?;
Ok(pipeline)
}
}
impl ReplaceInterpreter {
fn check_on_conflicts(&self) -> Result<()> {
if self.plan.on_conflict_fields.is_empty() {
Err(ErrorCode::BadArguments(
"at least one column must be specified in the replace into .. on [conflict] statement",
))
} else {
Ok(())
}
}
async fn connect_input_source<'a>(
&'a self,
ctx: Arc<QueryContext>,
source: &'a InsertInputSource,
schema: DataSchemaRef,
) -> Result<PipelineBuildResult> {
match source {
InsertInputSource::Values(data) => {
self.connect_value_source(ctx.clone(), schema.clone(), data)
}
InsertInputSource::SelectPlan(plan) => {
self.connect_query_plan_source(ctx.clone(), schema.clone(), plan)
.await
}
_ => Err(ErrorCode::Unimplemented(
"input source other than literal VALUES and sub queries are NOT supported yet.",
)),
}
}
fn connect_value_source(
&self,
ctx: Arc<QueryContext>,
schema: DataSchemaRef,
value_data: &str,
) -> Result<PipelineBuildResult> {
let mut build_res = PipelineBuildResult::create();
let settings = ctx.get_settings();
build_res.main_pipeline.add_source(
|output| {
let name_resolution_ctx = NameResolutionContext::try_from(settings.as_ref())?;
let inner = ValueSource::new(
value_data.to_string(),
ctx.clone(),
name_resolution_ctx,
schema.clone(),
);
AsyncSourcer::create(ctx.clone(), output, inner)
},
1,
)?;
Ok(build_res)
}
async fn connect_query_plan_source<'a>(
&'a self,
ctx: Arc<QueryContext>,
self_schema: DataSchemaRef,
query_plan: &Plan,
) -> Result<PipelineBuildResult> {
let (s_expr, metadata, bind_context, formatted_ast) = match query_plan {
Plan::Query {
s_expr,
metadata,
bind_context,
formatted_ast,
..
} => (s_expr, metadata, bind_context, formatted_ast),
v => unreachable!("Input plan must be Query, but it's {}", v),
};
let select_interpreter = SelectInterpreter::try_create(
ctx.clone(),
*(bind_context.clone()),
*s_expr.clone(),
metadata.clone(),
formatted_ast.clone(),
false,
)?;
let mut build_res = select_interpreter.execute2().await?;
let select_schema = query_plan.schema();
let target_schema = self_schema;
if self.check_schema_cast(query_plan)? {
let func_ctx = ctx.get_function_context()?;
build_res.main_pipeline.add_transform(
|transform_input_port, transform_output_port| {
TransformCastSchema::try_create(
transform_input_port,
transform_output_port,
select_schema.clone(),
target_schema.clone(),
func_ctx,
)
},
)?;
}
Ok(build_res)
}
// TODO duplicated
fn check_schema_cast(&self, plan: &Plan) -> Result<bool> {
let output_schema = &self.plan.schema;
let select_schema = plan.schema();
// validate schema
if select_schema.fields().len() < output_schema.fields().len() {
return Err(ErrorCode::BadArguments(
"Fields in select statement is less than expected",
));
}
// check if cast needed
let cast_needed = select_schema != DataSchema::from(output_schema.as_ref()).into();
Ok(cast_needed)
}
}
|
use horrorshow::prelude::*;
use miri::Frame;
use regex::Regex;
use rustc::ty::TyCtxt;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Color, ThemeSet};
use syntect::html::{styles_to_coloured_html, IncludeBackground};
use syntect::parsing::{SyntaxDefinition, SyntaxSet};
thread_local! {
/// Loading the syntax every time is very heavy and causes noticable slowdown
/// This is a thread local as a `SyntaxDefinition` is neither `Send` nor `Sync`
static RUST_SYNTAX: SyntaxDefinition = {
let ps = SyntaxSet::load_defaults_nonewlines();
ps.find_syntax_by_extension("rs").unwrap().to_owned()
};
static THEME_SET: ThemeSet = {
ThemeSet::load_defaults()
};
}
// These are costly to create
lazy_static! {
static ref BEG_REGEX: Regex =
Regex::new(r#"<span style="[\w\d#:;]+">/\*BEG_HIGHLIGHT\*/</span>"#).unwrap();
static ref END_REGEX: Regex =
Regex::new(r#"<span style="[\w\d#:;]+">/\*END_HIGHLIGHT\*/(\s*)</span>"#).unwrap();
static ref BOTH_REGEX: Regex = Regex::new(
r#"<span style="[\w\d#:;]+">/\*BEG_HIGHLIGHT\*//\*END_HIGHLIGHT\*/(\s*)</span>"#
).unwrap();
}
pub fn render_source(tcx: TyCtxt, frame: Option<&Frame>) -> Box<RenderBox + Send> {
if frame.is_none() {
return Box::new(FnRenderer::new(|_| {}));
}
let frame = frame.unwrap();
let codemap = tcx.sess.codemap();
let mut instr_spans = vec![if frame.stmt == frame.mir[frame.block].statements.len() {
frame.mir[frame.block].terminator().source_info.span
} else {
frame.mir[frame.block].statements[frame.stmt]
.source_info
.span
}];
// Get the original macro caller
while let Some(span) = instr_spans
.last()
.unwrap()
.macro_backtrace()
.get(0)
.map(|b| b.call_site)
{
instr_spans.push(span);
}
let (bg_color, highlighted_sources) = THEME_SET.with(|ts| {
let t = &ts.themes["Solarized (light)"];
let bg_color = t.settings.background.unwrap_or(Color::WHITE);
let mut h = RUST_SYNTAX.with(|syntax| HighlightLines::new(syntax, t));
let highlighted_sources = instr_spans
.iter()
.rev()
.map(|sp| {
let _ = codemap.span_to_snippet(*sp); // Ensure file src is loaded
let mut src: String = if let Ok(file_lines) = codemap.span_to_lines(*sp) {
if let Some(ref src) = file_lines.file.src {
src.to_string()
} else if let Some(src) = file_lines.file.external_src.borrow().get_source() {
src.to_string()
} else {
return (format!("{:?}", sp), "<no source info for span>".to_string());
}
} else {
return (
format!("{:?}", sp),
"<couldnt get lines for span>".to_string(),
);
};
let lo = codemap.bytepos_to_file_charpos(sp.lo()).0;
let hi = codemap.bytepos_to_file_charpos(sp.hi()).0;
src.insert_str(hi as usize, "/*END_HIGHLIGHT*/");
src.insert_str(lo as usize, "/*BEG_HIGHLIGHT*/");
let src = src
.split('\n')
.into_iter()
.map(|l| {
let highlighted =
styles_to_coloured_html(&h.highlight(&l), IncludeBackground::No);
let highlighted = BEG_REGEX.replace(
&highlighted,
"<span style='background-color: lightcoral; border-radius: 5px; padding: 1px;'>",
);
let highlighted = END_REGEX.replace(&highlighted, "</span>$1");
let highlighted = BOTH_REGEX.replace(
&highlighted,
"<span style='background-color: lightcoral; border-radius: 5px; padding: 1px;'>←</span>"
);
highlighted.into_owned()
})
.fold(String::new(), |acc, x| acc + "\n" + &x);
(format!("{:?}", sp), src)
})
.collect::<Vec<_>>();
(bg_color, highlighted_sources)
});
box_html! {
pre {
code(id="the_code", style=format!("background-color: #{:02x}{:02x}{:02x}; display: block;", bg_color.r, bg_color.g, bg_color.b)) {
@ for (sp, source) in highlighted_sources {
: sp;
: Raw(source);
br; br;
}
}
}
}
}
|
use crate::ast::{BinaryOperator, Expression, Program, Statement, UnaryOperator};
use crate::utils::{EvalError, Type, Value};
use std::collections::HashMap;
use std::io::{stdout, stdin, Write};
type EvalResult<T> = Result<T, EvalError>;
type GlobalVar = (Type, Option<Value>);
pub struct Evaluator {
global_scope: HashMap<String, GlobalVar>,
program: Program,
}
impl Evaluator {
pub fn new(program: Program) -> Self {
Evaluator {
global_scope: HashMap::new(),
program,
}
}
pub fn evaluate_program(&mut self) -> EvalResult<()> {
for statement in self.program.statements.clone() {
self.evaluate_statement(statement)?;
}
Ok(())
}
fn evaluate_statement(&mut self, statement: Statement) -> EvalResult<()> {
match statement {
Statement::NewAssignment(id, type_def, exp) => {
self.evaluate_new_assignment(id, type_def, exp)
}
Statement::VarInitialization(id, type_def) => self.evaluate_var_init(id, type_def),
Statement::Assignment(id, exp) => self.evaluate_assignment(id, exp),
Statement::Print(exp) => self.evaluate_print(exp),
Statement::Assert(exp) => self.evaluate_assert(exp),
Statement::Read(id) => self.evaluate_read(id),
Statement::For(id, start, end, stmts) => self.evaluate_for(id, start, end, stmts),
}
}
fn evaluate_new_assignment(
&mut self,
identifier: String,
type_def: Type,
exp: Expression,
) -> EvalResult<()> {
let val = self.evaluate_expression(exp)?;
self.check_type_conformance(&type_def, &val)?;
self.add_new_variable(identifier, (type_def, Some(val)))?;
Ok(())
}
fn evaluate_var_init(&mut self, id: String, type_def: Type) -> EvalResult<()> {
self.global_scope.insert(id, (type_def, None));
Ok(())
}
fn evaluate_assignment(&mut self, identifier: String, exp: Expression) -> EvalResult<()> {
let (type_def, _) = self.find_assigned_variable(&identifier)?;
let val = self.evaluate_expression(exp)?;
self.check_type_conformance(&type_def, &val)?;
self.global_scope.insert(identifier, (type_def, Some(val)));
Ok(())
}
fn evaluate_print(&mut self, exp: Expression) -> EvalResult<()> {
let val = self.evaluate_expression(exp)?;
print!("{}", val);
stdout().flush().unwrap();
Ok(())
}
fn evaluate_read(&mut self, id: String) -> EvalResult<()> {
let (type_def, _) = self.find_assigned_variable(&id)?;
let input = self.get_input()?;
match type_def {
Type::String => {
let val = Value::String(input);
self.global_scope.insert(id, (type_def, Some(val)));
}
Type::Integer => {
let parsed = input.trim().parse::<i32>();
match parsed {
Ok(int) => {
let val = Value::Integer(int);
self.global_scope.insert(id, (type_def, Some(val)));
}
Err(_) => return Err(EvalError::MismatchedTypes),
}
}
_ => return Err(EvalError::MismatchedTypes),
};
Ok(())
}
fn evaluate_assert(&mut self, exp: Expression) -> EvalResult<()> {
let val = self.evaluate_expression(exp.clone())?;
match val {
Value::Bool(boolean) if !boolean => {
println!("Assertion failed: {}", &exp);
Ok(())
}
Value::Bool(_) => Ok(()),
_ => return Err(EvalError::MismatchedTypes),
}
}
fn evaluate_for(
&mut self,
id: String,
exp1: Expression,
exp2: Expression,
stmts: Vec<Box<Statement>>,
) -> EvalResult<()> {
let start = match self.evaluate_expression(exp1) {
Ok(Value::Integer(int)) => int,
_ => return Err(EvalError::MismatchedTypes),
};
let end = match self.evaluate_expression(exp2) {
Ok(Value::Integer(int)) => int,
_ => return Err(EvalError::MismatchedTypes),
};
let (type_def, _) = self.find_assigned_variable(&id)?;
if type_def != Type::Integer {
return Err(EvalError::MismatchedTypes);
}
for i in start..=end {
let loop_val = Value::Integer(i);
self.global_scope
.insert(id.clone(), (Type::Integer, Some(loop_val)));
for stmt in stmts.clone() {
self.evaluate_statement(*stmt)?;
}
}
Ok(())
}
fn evaluate_expression(&mut self, exp: Expression) -> EvalResult<Value> {
match exp {
Expression::IntegerConstant(val) => Ok(Value::Integer(val)),
Expression::StringValue(string) => Ok(Value::String(string.clone())),
Expression::Boolean(boolean) => Ok(Value::Bool(boolean)),
Expression::Binary(exp1, op, exp2) => self.evaluate_binary(exp1, op, exp2),
Expression::Unary(op, exp) => self.evaluate_unary(op, *exp),
Expression::Identifier(id) => {
let (_, opt) = self.find_assigned_variable(&id)?;
match opt {
Some(val) => Ok(val.clone()),
None => Err(EvalError::VariableNotInitialized(id.clone())),
}
}
}
}
fn evaluate_binary(
&mut self,
left: Box<Expression>,
op: BinaryOperator,
right: Box<Expression>,
) -> EvalResult<Value> {
let left = self.evaluate_expression(*left)?;
let right = self.evaluate_expression(*right)?;
match (left, right) {
(Value::Integer(val1), Value::Integer(val2)) => match op {
BinaryOperator::Plus => Ok(Value::Integer(val1 + val2)),
BinaryOperator::Minus => Ok(Value::Integer(val1 - val2)),
BinaryOperator::Multiplication => Ok(Value::Integer(val1 * val2)),
BinaryOperator::Division => Ok(Value::Integer(val1 / val2)),
BinaryOperator::Equals => Ok(Value::Bool(val1 == val2)),
BinaryOperator::LessThan => Ok(Value::Bool(val1 < val2)),
BinaryOperator::GreaterThan => Ok(Value::Bool(val1 > val2)),
_ => Err(EvalError::UnsupportedOperation),
},
(Value::Bool(bool1), Value::Bool(bool2)) => match op {
BinaryOperator::And => Ok(Value::Bool(bool1 && bool2)),
BinaryOperator::Equals => Ok(Value::Bool(bool1 == bool2)),
BinaryOperator::LessThan => Ok(Value::Bool(bool1 < bool2)),
BinaryOperator::GreaterThan => Ok(Value::Bool(bool1 > bool2)),
_ => Err(EvalError::UnsupportedOperation),
},
(Value::String(str1), Value::String(str2)) => match op {
BinaryOperator::Plus => Ok(Value::String(str1 + &str2)),
BinaryOperator::Equals => Ok(Value::Bool(str1 == str2)),
BinaryOperator::LessThan => Ok(Value::Bool(str1 < str2)),
BinaryOperator::GreaterThan => Ok(Value::Bool(str1 > str2)),
_ => Err(EvalError::UnsupportedOperation),
},
_ => Err(EvalError::MismatchedTypes),
}
}
fn evaluate_unary(&mut self, op: UnaryOperator, exp: Expression) -> EvalResult<Value> {
let val = self.evaluate_expression(exp)?;
match val {
Value::Bool(boolean) => match op {
UnaryOperator::Not => Ok(Value::Bool(!boolean)),
},
_ => Err(EvalError::MismatchedTypes),
}
}
fn find_assigned_variable(&mut self, id: &String) -> EvalResult<GlobalVar> {
match self.global_scope.get(id) {
Some((type_def, val)) => Ok((type_def.clone(), val.clone())),
None => Err(EvalError::VariableNotInitialized(id.clone())),
}
}
fn add_new_variable(&mut self, id: String, var: GlobalVar) -> EvalResult<()> {
let (type_def, val) = var;
match self.global_scope.get(&id) {
Some(_) => Err(EvalError::VariableAlreadyInitialized(id)),
None => {
self.global_scope.insert(id, (type_def, val));
Ok(())
}
}
}
fn get_input(&mut self) -> EvalResult<String> {
let mut input = String::new();
match stdin().read_line(&mut input) {
Ok(_) => Ok(input),
Err(err) => Err(EvalError::IOError(err.to_string())),
}
}
fn check_type_conformance(&self, type_def: &Type, val: &Value) -> EvalResult<()> {
match val {
Value::Bool(_) => match type_def {
Type::Boolean => Ok(()),
_ => Err(EvalError::MismatchedTypes),
},
Value::Integer(_) => match type_def {
Type::Integer => Ok(()),
_ => Err(EvalError::MismatchedTypes),
},
Value::String(_) => match type_def {
Type::String => Ok(()),
_ => Err(EvalError::MismatchedTypes),
},
}
}
}
|
//! File holding the ResponseJSON type and associated tests
//!
//! Author: [Boris](mailto:boris@humanenginuity.com)
//! Version: 1.1
//!
//! ## Release notes
//! - v1.1 : changed `data` to Value instead of &Value
//! - v1.0 : creation
// =======================================================================
// LIBRARY IMPORTS
// =======================================================================
use std::error::Error;
use std::io::Read;
use std::string::ToString;
use hyper;
use rocket;
use rocket::{ Data, Request, Response };
use rocket::response::content;
use rocket::data::{ FromData, Outcome };
use rocket::http::Status;
use rocket::outcome::IntoOutcome;
use rocket::response::Responder;
use serde_json;
use serde_json::Value;
use error::GenericError;
use util::ContainsKeys;
// =======================================================================
// STRUCT & TRAIT DEFINITION
// =======================================================================
/// JSON wrapper for a JSON response from a REST route
/// It wraps an optional generic type `T` that just needs to implement [serde's Deserialize](https://docs.serde.rs/serde/de/trait.Deserializer.html)
///
/// It derives Rocket's [Responder trait](https://api.rocket.rs/rocket/response/trait.Responder.html) so it can be used as such in a Rocket's route as illustrated below
///
/// ```rust,ignore
/// #[get("/")]
/// fn index() -> ResponseJSON<T> { ... }
/// ```
#[derive(Clone, Debug)]
pub struct ResponseJSON {
pub success: bool,
pub http_code: u16,
pub data: Value,
pub message: Option<String>, // required for error JSON
pub resource: Option<String>,
pub method: Option<String>,
}
/// Test if the underlying structure is a valid ResponseJSON
pub trait IsResponseJSON {
fn is_valid_json(&self) -> bool;
fn is_ok_json(&self) -> bool;
fn is_error_json(&self) -> bool;
}
// =======================================================================
// STRUCT IMPLEMENTATION
// =======================================================================
impl ResponseJSON {
// Create an empty OK ResponseJSON
pub fn ok() -> ResponseJSON {
ResponseJSON {
success: true,
http_code: 200,
data: Value::Null,
message: None,
resource: None,
method: None,
}
}
// Create an empty OK ResponseJSON
pub fn error() -> ResponseJSON {
ResponseJSON {
success: false,
http_code: 500,
data: Value::Null,
message: Some("Unexpected error".to_string()),
resource: None,
method: None,
}
}
/// Set the HTTP Code of this ResponseJSON
pub fn http_code(mut self, code: u16) -> ResponseJSON {
self.http_code = code;
self
}
/// Set the data of this ResponseJSON
pub fn data(mut self, data: Value) -> ResponseJSON {
self.data = data;
self
}
/// Set the error message.
/// For Error JSON only (does nothing if `success == ok`)
pub fn message(mut self, string: String) -> ResponseJSON {
if !self.success {
self.message = Some(string);
} else {
warn!("::AMIWO::CONTRIB::ROCKET::RESPONSEJSON::MESSAGE::WARNING Trying to set `message` on an Ok JSON => ignored")
}
self
}
/// Set the resource that we tried to access.
/// For Error JSON only (does nothing if `success == ok`)
pub fn resource(mut self, string: String) -> ResponseJSON {
if !self.success {
self.resource = Some(string);
} else {
warn!("::AMIWO::CONTRIB::ROCKET::RESPONSEJSON::RESOURCE::WARNING Trying to set `resource` on an Ok JSON => ignored")
}
self
}
/// Set the method that was used (GET, POST, ...).
/// For Error JSON only (does nothing if `success == ok`)
pub fn method(mut self, string: String) -> ResponseJSON {
if !self.success {
self.method = Some(string);
} else {
warn!("::AMIWO::CONTRIB::ROCKET::RESPONSEJSON::METHOD::WARNING Trying to set `method` on an Ok JSON => ignored")
}
self
}
/// ResponseJSON<T> can be created from a `serde_json::Value`, consuming the original object
/// If the input is a valid ResponseJSON it duplicates it
/// Else it creates an Ok ResponseJSON with it's data property set to the input JSON
pub fn from_serde_value(json: Value) -> ResponseJSON {
if json.is_object() {
if json.is_ok_json() {
ResponseJSON::ok()
.http_code(json["http_code"].as_u64().unwrap() as u16)
.data(json.get("data").unwrap_or(&Value::Null).clone())
} else if json.is_error_json() {
let mut rjson = ResponseJSON::error()
.http_code(json["http_code"].as_u64().unwrap() as u16)
.data(json.get("data").unwrap_or(&Value::Null).clone());
if !json["message"].is_null() { rjson = rjson.message(json["message"].as_str().unwrap().to_string()); }
if !json["resource"].is_null() { rjson = rjson.resource(json["resource"].as_str().unwrap().to_string()); }
if !json["method"].is_null() { rjson = rjson.method(json["method"].as_str().unwrap().to_string()); }
rjson
} else {
ResponseJSON::ok()
.data(json.pointer("").unwrap().clone())
}
} else {
ResponseJSON::ok()
.data(json.pointer("").unwrap().clone())
}
}
/// Deserialize a ResponseJSON from a string of JSON text
pub fn from_str<'s>(s: &'s str) -> Result<ResponseJSON, GenericError> {
serde_json::from_str(s)
.map( |value : Value| Self::from_serde_value(value) )
.map_err( |serde_err| GenericError::Serde(serde_err) )
}
/// Deserialize a ResponseJSON from an IO stream of JSON
pub fn from_reader<R: Read>(reader: R) -> Result<ResponseJSON, GenericError> {
serde_json::from_reader(reader)
.map( |value : Value| Self::from_serde_value(value) )
.map_err( |serde_err| GenericError::Serde(serde_err) )
}
/// Consumes the ResponseJSON wrapper and returns the wrapped item.
// Note: Contrary to `serde_json::to_string()`, serialization can't fail.
pub fn into_string(self) -> String {
self.to_string()
}
}
// =======================================================================
// TRAIT IMPLEMENTATION
// ======================================================================
/// Serialize the given ResponseJSON as a String
impl ToString for ResponseJSON {
// Note: Contrary to `serde_json::to_string()`, serialization can't fail.
fn to_string(&self) -> String {
json!({
"success": self.success,
"http_code": self.http_code,
"data": &self.data,
"message": &self.message,
"resource": &self.resource,
"method": &self.method
}).as_object_mut()
.map_or(
"{\"http_code\":500,\"message\":\"Invalid ResponseJSON\",\"success\":false}".to_string(),
|map| {
if map["data"].is_null() { map.remove("data"); };
if map["message"].is_null() { map.remove("message"); };
if map["resource"].is_null() { map.remove("resource"); };
if map["method"].is_null() { map.remove("method"); };
serde_json::to_string(map).unwrap()
}
)
}
}
/// Parse a ResponseJSON from incoming POST/... form data.
/// If the content type of the request data is not
/// `application/json`, `Forward`s the request.
///
/// All relevant warnings and errors are written to the console
impl FromData for ResponseJSON {
type Error = GenericError;
fn from_data<'r>(request: &'r Request, data: Data) -> Outcome<Self, GenericError> {
if !request.content_type().map_or(false, |ct| ct.is_json()) {
error!("::AMIWO::CONTRIB::ROCKET::RESPONSEJSON::FROM_DATA::ERROR Content-Type is not JSON.");
return rocket::Outcome::Forward(data);
}
let size_limit = rocket::config::active()
.and_then(|c| c.extras.get("limits.json")) // TODO: remove placeholder when upgrading to rocket version > 0.2.6
// .and_then(|c| c.limits.get("json") // In next version
.and_then(|limit| limit.as_integer())
.unwrap_or(1 << 20) as u64; // default limit is 1MB for JSON
// ResponseJSON::from_reader(data.open().take(size_limit))
serde_json::from_reader(data.open().take(size_limit))
.map_err(|serde_err| { error!("::AMIWO::CONTRIB::ROCKET::RESPONSEJSON::FROM_DATA::ERROR Unable to create JSON from reader => {:?}", serde_err); GenericError::Serde(serde_err) })
.map( |value| ResponseJSON::from_serde_value(value) )
.into_outcome()
}
}
/// Serializes the wrapped value into a ResponseJSON. Returns a response with Content-Type
/// JSON and a fixed-size body with the serialized value. If serialization
/// fails, an `Err` of `Status::InternalServerError` is returned.
impl<'r> Responder<'r> for ResponseJSON {
fn respond(self) -> Result<Response<'r>, Status> {
content::JSON(self.into_string()).respond()
}
}
/// Sugar to convert a valid Hyper Response into a ResponseJSON
/// Since `From` can't fail it will return an error ResponseJSON when it can't parse
/// it's body into a valid ResponseJSON
///
/// ```rust
/// extern crate hyper;
/// extern crate amiwo;
///
/// hyper::client::Client::new()
/// .get("http://some/url")
/// .send()
/// .map(::std::convert::From::from)
/// .map(|json : amiwo::ResponseJSON| println!("JSON received from request = {:?}", json) );
/// ```
impl From<hyper::client::response::Response> for ResponseJSON {
fn from(response: hyper::client::response::Response) -> Self {
ResponseJSON::from_reader(response)
.unwrap_or_else( |err| ResponseJSON::error().data(Value::String(format!("Error converting response into a ResponseJSON > {}", err.description()))) )
}
}
impl IsResponseJSON for ResponseJSON {
/// Check if the JSON described as a String is a valid ResponseJSON
fn is_valid_json(&self) -> bool {
true
}
/// Check if the JSON described as a String is an Error JSON
fn is_error_json(&self) -> bool
{
self.success == false
}
/// Check if the JSON described as a String is an OK JSON
fn is_ok_json(&self) -> bool {
self.success == true &&
self.method.is_none() &&
self.message.is_none() &&
self.resource.is_none()
}
}
impl IsResponseJSON for serde_json::map::Map<String, Value> {
fn is_valid_json(&self) -> bool {
self.contains_keys(&["success", "http_code"])
}
fn is_ok_json(&self) -> bool {
self.is_valid_json() &&
self["success"] == Value::Bool(true) &&
self["http_code"].is_number() &&
self["method"].is_null() &&
self["resource"].is_null() &&
self["message"].is_null()
}
fn is_error_json(&self) -> bool {
self.is_valid_json() &&
self["success"] == Value::Bool(false) &&
self["http_code"].is_number() &&
(self.get("message").is_none() || self["message"].is_string()) &&
(self.get("resource").is_none() || self["resource"].is_string()) &&
(self.get("method").is_none() || self["method"].is_string())
}
}
impl IsResponseJSON for Value {
fn is_valid_json(&self) -> bool {
self.contains_keys(&["success", "http_code"])
}
fn is_ok_json(&self) -> bool {
self.is_valid_json() &&
self["success"] == Value::Bool(true) &&
self["http_code"].is_number() &&
self["method"].is_null() &&
self["resource"].is_null() &&
self["message"].is_null()
}
fn is_error_json(&self) -> bool {
self.is_valid_json() &&
self["success"] == Value::Bool(false) &&
self["http_code"].is_number() &&
(self.get("message").is_none() || self["message"].is_string()) &&
(self.get("resource").is_none() || self["resource"].is_string()) &&
(self.get("method").is_none() || self["method"].is_string())
}
}
impl IsResponseJSON for String {
fn is_valid_json(&self) -> bool{
serde_json::from_str(&self)
.ok()
.map_or(
false,
|json : Value| json.is_valid_json()
)
}
fn is_ok_json(&self) -> bool {
serde_json::from_str(&self)
.ok()
.map_or(
false,
|json : Value| json.is_ok_json()
)
}
fn is_error_json(&self) -> bool {
serde_json::from_str(&self)
.ok()
.map_or(
false,
|json : Value| json.is_error_json()
)
}
}
impl IsResponseJSON for str {
fn is_valid_json(&self) -> bool{
serde_json::from_str(&self)
.ok()
.map_or(
false,
|json : Value| json.is_valid_json()
)
}
fn is_ok_json(&self) -> bool {
serde_json::from_str(&self)
.ok()
.map_or(
false,
|json : Value| json.is_ok_json()
)
}
fn is_error_json(&self) -> bool {
serde_json::from_str(&self)
.ok()
.map_or(
false,
|json : Value| json.is_error_json()
)
}
}
impl<T: ToString> PartialEq<T> for ResponseJSON {
fn eq(&self, other: &T) -> bool {
self.to_string() == other.to_string()
}
}
macro_rules! __impl_rjson_partial_eq {
(to_string @ $other:ty) => { __impl_rjson_partial_eq!(to_string @ $other, ResponseJSON); };
(to_string @ $other:ty, <$($args:tt),* $(,)*> ) => { __impl_rjson_partial_eq!(to_string @ $other, ResponseJSON, [$($args),*]); };
(to_string @ $Lhs:ty, $Rhs:ty) => {
impl PartialEq<$Rhs> for $Lhs
where
$Lhs: ToString,
$Rhs: ToString
{
fn eq(&self, other: &$Rhs) -> bool {
self.to_string() == other.to_string()
}
}
};
(to_string @ $Lhs:ty, $Rhs:ty, [$($args:tt),* $(,)*] ) => { // Note: changed from '<>' to '[]' to avoid infinite macro recursion
impl<$($args),*> PartialEq<$Rhs> for $Lhs
where
$Lhs: ToString,
$Rhs: ToString
{
fn eq(&self, other: &$Rhs) -> bool {
self.to_string() == other.to_string()
}
}
};
}
__impl_rjson_partial_eq!(to_string @ Value);
__impl_rjson_partial_eq!(to_string @ String);
__impl_rjson_partial_eq!(to_string @ &'r str, <'r>);
// =======================================================================
// UNIT TESTS
// =======================================================================
#[cfg(test)]
mod tests {
#![allow(non_snake_case)]
#![allow(unmounted_route)]
use super::ResponseJSON;
use super::IsResponseJSON;
use serde_json;
use serde_json::Value;
use rocket;
use rocket::testing::MockRequest;
use rocket::http::{ ContentType, Method, Status };
use contrib::rocket::FormHashMap;
#[test]
fn ResponseJSON_test_IsResponseJSON_implem() {
let json = r#"{
"success": false,
"http_code": 500,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#;
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), false);
assert_eq!(json.is_error_json(), true);
let json = r#"{
"success": true,
"http_code": 200,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#;
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_error_json(), false);
assert_eq!(json.is_ok_json(), false);
let json = r#"{
"http_code": 200,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#;
assert_eq!(json.is_valid_json(), false);
assert_eq!(json.is_error_json(), false);
assert_eq!(json.is_ok_json(), false);
let json = r#"{
"success": true,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#;
assert_eq!(json.is_valid_json(), false);
assert_eq!(json.is_error_json(), false);
assert_eq!(json.is_ok_json(), false);
}
#[test]
fn ResponseJSON_test_builder_ok() {
let json : ResponseJSON = ResponseJSON::ok();
assert_eq!(json.success, true);
assert_eq!(json.http_code, 200);
assert!(json.data.is_null());
assert_eq!(json.message, None);
assert_eq!(json.method, None);
assert_eq!(json.resource, None);
let json : ResponseJSON = ResponseJSON::ok()
.http_code(201)
.data("Some data".into())
.method("GET".to_string())
.resource("some path".to_string())
.message("error message".to_string());
assert_eq!(json.http_code, 201);
assert_eq!(json.data.as_str(), Some("Some data"));
assert_eq!(json.message, None);
assert_eq!(json.method, None);
assert_eq!(json.resource, None);
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), true);
assert_eq!(json.is_error_json(), false);
}
#[test]
fn ResponseJSON_test_builder_error() {
let json : ResponseJSON = ResponseJSON::error();
assert_eq!(json.success, false);
assert_eq!(json.http_code, 500);
assert!(json.data.is_null());
assert_eq!(json.message, Some("Unexpected error".to_string()));
assert_eq!(json.method, None);
assert_eq!(json.resource, None);
let json : ResponseJSON = ResponseJSON::error()
.http_code(401)
.data("Some data".into())
.method("GET".to_string())
.resource("some path".to_string())
.message("error message".to_string());
assert_eq!(json.http_code, 401);
assert_eq!(json.data.as_str(), Some("Some data"));
assert_eq!(json.message, Some("error message".to_string()));
assert_eq!(json.method, Some("GET".to_string()));
assert_eq!(json.resource, Some("some path".to_string()));
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), false);
assert_eq!(json.is_error_json(), true);
}
#[test]
fn ResponseJSON_test_from_str() {
// Simple non ResponseJSON
let json = ResponseJSON::from_str(r#"{
"test1": "value1",
"test2": "value2",
"test3": [ 1, 2, 3 ]
}"#).unwrap();
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), true);
assert_eq!(json.is_error_json(), false);
assert_eq!(json.data["test2"], Value::String("value2".to_string()));
// ok json without data
let json = ResponseJSON::from_str(r#"{
"success": true,
"http_code": 204
}"#).unwrap();
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), true);
assert_eq!(json.is_error_json(), false);
assert_eq!(json.http_code, 204);
assert_eq!(json.method.is_none(), true);
assert_eq!(json.resource.is_none(), true);
assert_eq!(json.message.is_none(), true);
assert_eq!(json.data.is_null(), true);
// improper ok json (yet still parsed but everything will be moved in data)
let json = ResponseJSON::from_str(r#"{
"success": true,
"http_code": 201,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#).unwrap();
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), true);
assert_eq!(json.is_error_json(), false);
assert_eq!(json.http_code, 200);
assert_eq!(json.method.is_none(), true);
assert_eq!(json.resource.is_none(), true);
assert_eq!(json.message.is_none(), true);
let val : Value = serde_json::from_str("201").unwrap();
assert_eq!(json.data["http_code"], val);
// ok json with data
let json = ResponseJSON::from_str(r#"{
"success": true,
"http_code": 202,
"data": {
"test1": "value1",
"test2": "value2",
"test3": [ 1, 2, 3 ]
}
}"#).unwrap();
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), true);
assert_eq!(json.is_error_json(), false);
assert_eq!(json.http_code, 202);
assert_eq!(json.data["test2"], Value::String("value2".to_string()));
// error json without data
let json = ResponseJSON::from_str(r#"{
"success": false,
"http_code": 501,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#).unwrap();
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), false);
assert_eq!(json.is_error_json(), true);
assert_eq!(json.http_code, 501);
assert_eq!(json.resource.unwrap(), "some resource requested".to_string());
// error json with data
let json = ResponseJSON::from_str(r#"{
"success": false,
"http_code": 502,
"data": {
"test1": "value1",
"test2": "value2",
"test3": [ 1, 2, 3 ]
},
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#).unwrap();
assert_eq!(json.data["test2"], Value::String("value2".to_string()));
assert_eq!(json.is_valid_json(), true);
assert_eq!(json.is_ok_json(), false);
assert_eq!(json.is_error_json(), true);
assert_eq!(json.http_code, 502);
assert_eq!(json.resource.unwrap(), "some resource requested".to_string());
assert_eq!(json.data["test1"], Value::String("value1".to_string()));
}
#[test]
fn ResponseJSON_test_from_serde_json() {
// Simple non ResponseJSON
let json = serde_json::from_str(r#"{
"test1": "value1",
"test2": "value2",
"test3": [ 1, 2, 3 ]
}"#).unwrap();
let rjson = ResponseJSON::from_serde_value(json);
assert_eq!(rjson.is_valid_json(), true);
assert_eq!(rjson.is_ok_json(), true);
assert_eq!(rjson.is_error_json(), false);
assert_eq!(rjson.data["test2"], Value::String("value2".to_string()));
// ok json without data
let json = serde_json::from_str(r#"{
"success": true,
"http_code": 204
}"#).unwrap();
let rjson = ResponseJSON::from_serde_value(json);
assert_eq!(rjson.is_valid_json(), true);
assert_eq!(rjson.is_ok_json(), true);
assert_eq!(rjson.is_error_json(), false);
assert_eq!(rjson.http_code, 204);
assert_eq!(rjson.method.is_none(), true);
assert_eq!(rjson.resource.is_none(), true);
assert_eq!(rjson.message.is_none(), true);
assert_eq!(rjson.data.is_null(), true);
// improper ok json (yet still parsed but everything will be moved in data)
let json = serde_json::from_str(r#"{
"success": true,
"http_code": 201,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#).unwrap();
let rjson = ResponseJSON::from_serde_value(json);
assert_eq!(rjson.is_valid_json(), true);
assert_eq!(rjson.is_ok_json(), true);
assert_eq!(rjson.is_error_json(), false);
assert_eq!(rjson.http_code, 200);
assert_eq!(rjson.method.is_none(), true);
assert_eq!(rjson.resource.is_none(), true);
assert_eq!(rjson.message.is_none(), true);
let val : Value = serde_json::from_str("201").unwrap();
assert_eq!(rjson.data["http_code"], val);
// ok json with data
let json = serde_json::from_str(r#"{
"success": true,
"http_code": 202,
"data": {
"test1": "value1",
"test2": "value2",
"test3": [ 1, 2, 3 ]
}
}"#).unwrap();
let rjson = ResponseJSON::from_serde_value(json);
assert_eq!(rjson.is_valid_json(), true);
assert_eq!(rjson.is_ok_json(), true);
assert_eq!(rjson.is_error_json(), false);
assert_eq!(rjson.http_code, 202);
assert_eq!(rjson.data["test2"], Value::String("value2".to_string()));
// error json without data
let json = serde_json::from_str(r#"{
"success": false,
"http_code": 501,
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#).unwrap();
let rjson = ResponseJSON::from_serde_value(json);
assert_eq!(rjson.is_valid_json(), true);
assert_eq!(rjson.is_ok_json(), false);
assert_eq!(rjson.is_error_json(), true);
assert_eq!(rjson.http_code, 501);
assert_eq!(rjson.resource.unwrap(), "some resource requested".to_string());
// error json with data
let json : Value = serde_json::from_str(r#"{
"success": false,
"http_code": 502,
"data": {
"test1": "value1",
"test2": "value2",
"test3": [ 1, 2, 3 ]
},
"resource": "some resource requested",
"method": "GET",
"message": "error message"
}"#).unwrap();
assert_eq!(json["data"]["test2"], Value::String("value2".to_string()));
let rjson = ResponseJSON::from_serde_value(json);
assert_eq!(rjson.is_valid_json(), true);
assert_eq!(rjson.is_ok_json(), false);
assert_eq!(rjson.is_error_json(), true);
assert_eq!(rjson.http_code, 502);
assert_eq!(rjson.resource.unwrap(), "some resource requested".to_string());
assert_eq!(rjson.data["test1"], Value::String("value1".to_string()));
// should not compile
// assert_eq!(json["data"]["test2"], Value::String("value2".to_string()));
}
#[test]
fn ResponseJSON_test_into_string() {
let json = ResponseJSON::ok()
.http_code(201)
.data("Some data".into());
let ref_json : Value = json!({
"success": true,
"http_code": 201,
"data": "Some data"
});
let string = json.into_string();
let test_json : Value = serde_json::from_str(&string).unwrap();
assert_eq!(ref_json, test_json);
}
#[test]
fn ResponseJSON_test_to_string() {
let json = ResponseJSON::ok()
.http_code(201)
.data("Some data".into());
let ref_json : Value = json!({
"success": true,
"http_code": 201,
"data": "Some data"
});
assert_eq!(json.to_string(), ref_json.to_string());
assert_eq!(json.is_ok_json(), true); // ensure value is not moved
}
#[test]
fn ResponseJSON_test_eq() {
let json = ResponseJSON::ok()
.http_code(201)
.data("Some data".into());
let ref_json : Value = json!({
"success": true,
"http_code": 201,
"data": "Some data"
});
assert_eq!(json, ref_json);
assert_eq!(ref_json, json);
assert_eq!(json, json);
let string = ref_json.to_string();
assert_eq!(json, string);
assert_eq!(string, json);
let str_slice : &str = string.as_ref();
assert_eq!(json, str_slice);
assert_eq!(str_slice, json);
}
#[test]
fn ResponseJSON_test_route_with_ok_response_json() {
let input_rjson = ResponseJSON::from_str(r#"{
"success": true,
"http_code": 200,
"data": {
"test1": "value1",
"test2": [ 1, 2, 3 ]
}
}"#).unwrap();
#[post("/test", data="<params>")]
fn test_route(params: ResponseJSON) -> &'static str {
assert_eq!(params.success, true);
assert_eq!(params.http_code, 200);
assert_eq!(params.data["test1"], Value::String("value1".to_string()));
"It's working !"
}
let rocket = rocket::ignite()
.mount("/post", routes![test_route]);
let mut req = MockRequest::new(Method::Post, "/post/test")
.header(ContentType::JSON)
.body(input_rjson.clone().to_string());
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|b| b.into_string());
assert_eq!(response.status(), Status::Ok);
assert_eq!(body_str, Some("It's working !".to_string()));
}
#[test]
fn ResponseJSON_test_route_with_error_response_json() {
let input_rjson = ResponseJSON::from_str(r#"{
"success": false,
"http_code": 500,
"data": {
"test1": "value1",
"test2": [ 1, 2, 3 ]
},
"method": "GET",
"resource": "/back/test",
"message": "Unexpected error"
}"#).unwrap();
#[post("/test", data="<params>")]
fn test_route(params: ResponseJSON) -> &'static str {
assert_eq!(params.success, false);
assert_eq!(params.http_code, 500);
assert_eq!(params.method.unwrap(), "GET");
assert_eq!(params.resource.unwrap(), "/back/test");
assert_eq!(params.message.unwrap(), "Unexpected error");
"It's working !"
}
let rocket = rocket::ignite()
.mount("/post", routes![test_route]);
let mut req = MockRequest::new(Method::Post, "/post/test")
.header(ContentType::JSON)
.body(input_rjson.clone().to_string());
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|b| b.into_string());
assert_eq!(response.status(), Status::Ok);
assert_eq!(body_str, Some("It's working !".to_string()));
}
#[test]
fn ResponseJSON_test_route_with_returned_response_json() {
#[get("/test?<params>")]
fn test_route(params: FormHashMap) -> ResponseJSON {
let json = json!({
"success": true,
"http_code": 200,
"data": {
"message": params["message"]
}
});
ResponseJSON::from_serde_value(json)
}
let rocket = rocket::ignite()
.mount("/get", routes![test_route]);
let message = "hello_world";
let mut req = MockRequest::new(Method::Get, "/get/test?message=".to_string() + message);
let mut response = req.dispatch_with(&rocket);
let body_str = response.body().and_then(|b| b.into_string()).unwrap();
assert_eq!(response.status(), Status::Ok);
assert_eq!(ResponseJSON::from_str(&body_str).unwrap(), ResponseJSON::from_serde_value(json!({
"success": true,
"http_code": 200,
"data": {
"message": message
}
})));
}
// TODO add test with Errors being generated
} |
use super::*;
/// A trait object used in method that access map entries without replacing them.
#[derive(StableAbi)]
#[repr(C)]
pub struct MapQuery<'a, K> {
_marker: NotCopyNotClone,
is_equal: extern "C" fn(&K, RRef<'_, ErasedObject>) -> bool,
hash: extern "C" fn(RRef<'_, ErasedObject>, HasherObject<'_>),
query: RRef<'a, ErasedObject>,
}
impl<'a, K> MapQuery<'a, K> {
#[inline]
pub(super) fn new<Q>(query: &'a &'a Q) -> Self
where
K: Borrow<Q>,
Q: Hash + Eq + 'a + ?Sized,
{
MapQuery {
_marker: NotCopyNotClone,
is_equal: is_equal::<K, Q>,
hash: hash::<Q>,
query: unsafe { RRef::new(query).transmute() },
}
}
#[inline]
pub(super) unsafe fn as_static(&self) -> &MapQuery<'static, K> {
unsafe { crate::utils::transmute_reference(self) }
}
}
impl<'a, K> MapQuery<'a, K> {
#[inline]
pub(super) fn is_equal(&self, other: &K) -> bool {
(self.is_equal)(other, self.query)
}
#[inline]
pub(super) unsafe fn as_mapkey(&self) -> MapKey<K> {
MapKey::Query(NonNull::from(unsafe { self.as_static() }))
}
}
impl<'a, K> Hash for MapQuery<'a, K> {
#[inline]
fn hash<H>(&self, hasher: &mut H)
where
H: Hasher,
{
(self.hash)(self.query, HasherObject::new(hasher))
}
}
extern "C" fn is_equal<K, Q>(key: &K, query: RRef<'_, ErasedObject>) -> bool
where
K: Borrow<Q>,
Q: Eq + ?Sized,
{
extern_fn_panic_handling! {
let query = unsafe{ query.transmute_into_ref::<&Q>() };
key.borrow() == *query
}
}
extern "C" fn hash<Q>(query: RRef<'_, ErasedObject>, mut hasher: HasherObject<'_>)
where
Q: Hash + ?Sized,
{
extern_fn_panic_handling! {
let query = unsafe{ query.transmute_into_ref::<&Q>() };
query.hash(&mut hasher);
}
}
|
pub mod algo;
pub mod arena_tree;
pub mod graph;
pub mod node;
pub mod safe_tree;
pub mod topology;
pub mod tree;
pub mod mcts_tree;
#[cfg(test)]
mod tests {
use std::borrow::BorrowMut;
use std::sync::Arc;
use rpool::{Pool, PoolScaleMode, Poolable};
#[derive(Debug)]
struct TestContext {
test: &'static str,
}
#[derive(Debug)]
struct TestItem {
test: String,
}
impl Poolable<TestContext> for TestItem {
fn new(context: &TestContext) -> TestItem {
TestItem {
test: format!("{}_{}", context.test, "testing item"),
}
}
fn reset(&mut self) -> bool {
self.borrow_mut().test.clear();
self.borrow_mut().test.push_str("fds");
return true;
}
}
#[test]
fn test_get() {
let pool: Arc<Pool<TestContext, TestItem>> = Pool::new(
PoolScaleMode::Static { count: 6 },
TestContext {
test: "testing context",
},
);
let mut x = vec![];
for _ in 0..5 {
let item = pool.get().expect("oups");
println!("{:?}", item);
x.push(item);
}
for _ in 0..10 {
let item = pool.get().expect("oups");
println!("{:?}", item);
}
}
}
|
use crate::backend::c;
use crate::backend::conv::borrowed_fd;
use crate::backend::fd::{AsFd, AsRawFd, BorrowedFd, LibcFd};
use bitflags::bitflags;
use core::marker::PhantomData;
#[cfg(windows)]
use {
crate::backend::fd::{AsSocket, RawFd},
core::fmt,
};
bitflags! {
/// `POLL*` flags for use with [`poll`].
///
/// [`poll`]: crate::io::poll
#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct PollFlags: c::c_short {
/// `POLLIN`
const IN = c::POLLIN;
/// `POLLPRI`
#[cfg(not(target_os = "wasi"))]
const PRI = c::POLLPRI;
/// `POLLOUT`
const OUT = c::POLLOUT;
/// `POLLRDNORM`
const RDNORM = c::POLLRDNORM;
/// `POLLWRNORM`
#[cfg(not(target_os = "l4re"))]
const WRNORM = c::POLLWRNORM;
/// `POLLRDBAND`
#[cfg(not(any(target_os = "l4re", target_os = "wasi")))]
const RDBAND = c::POLLRDBAND;
/// `POLLWRBAND`
#[cfg(not(any(target_os = "l4re", target_os = "wasi")))]
const WRBAND = c::POLLWRBAND;
/// `POLLERR`
const ERR = c::POLLERR;
/// `POLLHUP`
const HUP = c::POLLHUP;
/// `POLLNVAL`
#[cfg(not(target_os = "espidf"))]
const NVAL = c::POLLNVAL;
/// `POLLRDHUP`
#[cfg(all(
linux_kernel,
not(any(target_arch = "sparc", target_arch = "sparc64"))),
)]
const RDHUP = c::POLLRDHUP;
}
}
/// `struct pollfd`—File descriptor and flags for use with [`poll`].
///
/// [`poll`]: crate::event::poll
#[doc(alias = "pollfd")]
#[derive(Clone)]
#[cfg_attr(not(windows), derive(Debug))]
#[repr(transparent)]
pub struct PollFd<'fd> {
pollfd: c::pollfd,
_phantom: PhantomData<BorrowedFd<'fd>>,
}
#[cfg(windows)]
impl<'fd> fmt::Debug for PollFd<'fd> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("pollfd")
.field("fd", &self.pollfd.fd)
.field("events", &self.pollfd.events)
.field("revents", &self.pollfd.revents)
.finish()
}
}
impl<'fd> PollFd<'fd> {
/// Constructs a new `PollFd` holding `fd` and `events`.
#[inline]
pub fn new<Fd: AsFd>(fd: &'fd Fd, events: PollFlags) -> Self {
Self::from_borrowed_fd(fd.as_fd(), events)
}
/// Sets the contained file descriptor to `fd`.
#[inline]
pub fn set_fd<Fd: AsFd>(&mut self, fd: &'fd Fd) {
self.pollfd.fd = fd.as_fd().as_raw_fd() as LibcFd;
}
/// Clears the ready events.
#[inline]
pub fn clear_revents(&mut self) {
self.pollfd.revents = 0;
}
/// Constructs a new `PollFd` holding `fd` and `events`.
///
/// This is the same as `new`, but can be used to avoid borrowing the
/// `BorrowedFd`, which can be tricky in situations where the `BorrowedFd`
/// is a temporary.
#[inline]
pub fn from_borrowed_fd(fd: BorrowedFd<'fd>, events: PollFlags) -> Self {
Self {
pollfd: c::pollfd {
fd: borrowed_fd(fd),
events: events.bits(),
revents: 0,
},
_phantom: PhantomData,
}
}
/// Returns the ready events.
#[inline]
pub fn revents(&self) -> PollFlags {
// Use `unwrap()` here because in theory we know we know all the bits
// the OS might set here, but OS's have added extensions in the past.
PollFlags::from_bits(self.pollfd.revents).unwrap()
}
}
#[cfg(not(windows))]
impl<'fd> AsFd for PollFd<'fd> {
#[inline]
fn as_fd(&self) -> BorrowedFd<'_> {
// SAFETY: Our constructors and `set_fd` require `pollfd.fd` to be
// valid for the `fd lifetime.
unsafe { BorrowedFd::borrow_raw(self.pollfd.fd) }
}
}
#[cfg(windows)]
impl<'fd> AsSocket for PollFd<'fd> {
#[inline]
fn as_socket(&self) -> BorrowedFd<'_> {
// SAFETY: Our constructors and `set_fd` require `pollfd.fd` to be
// valid for the `fd lifetime.
unsafe { BorrowedFd::borrow_raw(self.pollfd.fd as RawFd) }
}
}
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use self::ImportDirectiveSubclass::*;
use {AmbiguityError, CrateLint, Module, ModuleOrUniformRoot, PerNS};
use Namespace::{self, TypeNS, MacroNS, ValueNS};
use {NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
use Resolver;
use {names_to_string, module_to_string};
use {resolve_error, ResolutionError};
use rustc_data_structures::ptr_key::PtrKey;
use rustc::ty;
use rustc::lint::builtin::BuiltinLintDiagnostics;
use rustc::lint::builtin::{DUPLICATE_MACRO_EXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE};
use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
use rustc::hir::def::*;
use rustc::session::DiagnosticMessageId;
use rustc::util::nodemap::{FxHashMap, FxHashSet};
use syntax::ast::{Ident, Name, NodeId, CRATE_NODE_ID};
use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
use syntax::ext::hygiene::Mark;
use syntax::symbol::keywords;
use syntax::util::lev_distance::find_best_match_for_name;
use syntax_pos::Span;
use std::cell::{Cell, RefCell};
use std::{mem, ptr};
/// Contains data for specific types of import directives.
#[derive(Clone, Debug)]
pub enum ImportDirectiveSubclass<'a> {
SingleImport {
target: Ident,
source: Ident,
result: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
type_ns_only: bool,
},
GlobImport {
is_prelude: bool,
max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
// n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
},
ExternCrate(Option<Name>),
MacroUse,
}
/// One import directive.
#[derive(Debug,Clone)]
pub struct ImportDirective<'a> {
/// The id of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
///
/// In the case where the `ImportDirective` was expanded from a "nested" use tree,
/// this id is the id of the leaf tree. For example:
///
/// ```ignore (pacify the mercilous tidy)
/// use foo::bar::{a, b}
/// ```
///
/// If this is the import directive for `foo::bar::a`, we would have the id of the `UseTree`
/// for `a` in this field.
pub id: NodeId,
/// The `id` of the "root" use-kind -- this is always the same as
/// `id` except in the case of "nested" use trees, in which case
/// it will be the `id` of the root use tree. e.g., in the example
/// from `id`, this would be the id of the `use foo::bar`
/// `UseTree` node.
pub root_id: NodeId,
/// Span of this use tree.
pub span: Span,
/// Span of the *root* use tree (see `root_id`).
pub root_span: Span,
pub parent: Module<'a>,
pub module_path: Vec<Ident>,
/// The resolution of `module_path`.
pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
pub subclass: ImportDirectiveSubclass<'a>,
pub vis: Cell<ty::Visibility>,
pub expansion: Mark,
pub used: Cell<bool>,
/// Whether this import is a "canary" for the `uniform_paths` feature,
/// i.e. `use x::...;` results in an `use self::x as _;` canary.
/// This flag affects diagnostics: an error is reported if and only if
/// the import resolves successfully and an external crate with the same
/// name (`x` above) also exists; any resolution failures are ignored.
pub is_uniform_paths_canary: bool,
}
impl<'a> ImportDirective<'a> {
pub fn is_glob(&self) -> bool {
match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
}
crate fn crate_lint(&self) -> CrateLint {
CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
}
}
#[derive(Clone, Default, Debug)]
/// Records information about the resolution of a name in a namespace of a module.
pub struct NameResolution<'a> {
/// Single imports that may define the name in the namespace.
/// Import directives are arena-allocated, so it's ok to use pointers as keys.
single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
/// The least shadowable known binding for this name, or None if there are no known bindings.
pub binding: Option<&'a NameBinding<'a>>,
shadowed_glob: Option<&'a NameBinding<'a>>,
}
impl<'a> NameResolution<'a> {
// Returns the binding for the name if it is known or None if it not known.
fn binding(&self) -> Option<&'a NameBinding<'a>> {
self.binding.and_then(|binding| {
if !binding.is_glob_import() ||
self.single_imports.is_empty() { Some(binding) } else { None }
})
}
}
impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
-> &'a RefCell<NameResolution<'a>> {
*module.resolutions.borrow_mut().entry((ident.modern(), ns))
.or_insert_with(|| self.arenas.alloc_name_resolution())
}
/// Attempts to resolve `ident` in namespaces `ns` of `module`.
/// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
pub fn resolve_ident_in_module_unadjusted(&mut self,
module: ModuleOrUniformRoot<'a>,
ident: Ident,
ns: Namespace,
restricted_shadowing: bool,
record_used: bool,
path_span: Span)
-> Result<&'a NameBinding<'a>, Determinacy> {
let module = match module {
ModuleOrUniformRoot::Module(module) => module,
ModuleOrUniformRoot::UniformRoot(root) => {
// HACK(eddyb): `resolve_path` uses `keywords::Invalid` to indicate
// paths of length 0, and currently these are relative `use` paths.
let can_be_relative = !ident.is_path_segment_keyword() &&
root == keywords::Invalid.name();
if can_be_relative {
// Relative paths should only get here if the feature-gate is on.
assert!(self.session.rust_2018() &&
self.session.features_untracked().uniform_paths);
// Try first to resolve relatively.
let mut ctxt = ident.span.ctxt().modern();
let self_module = self.resolve_self(&mut ctxt, self.current_module);
let binding = self.resolve_ident_in_module_unadjusted(
ModuleOrUniformRoot::Module(self_module),
ident,
ns,
restricted_shadowing,
record_used,
path_span,
);
// FIXME(eddyb) This may give false negatives, specifically
// if a crate with the same name is found in `extern_prelude`,
// preventing the check below this one from returning `binding`
// in all cases.
//
// That is, if there's no crate with the same name, `binding`
// is always returned, which is the result of doing the exact
// same lookup of `ident`, in the `self` module.
// But when a crate does exist, it will get chosen even when
// macro expansion could result in a success from the lookup
// in the `self` module, later on.
//
// NB. This is currently alleviated by the "ambiguity canaries"
// (see `is_uniform_paths_canary`) that get introduced for the
// maybe-relative imports handled here: if the false negative
// case were to arise, it would *also* cause an ambiguity error.
if binding.is_ok() {
return binding;
}
// Fall back to resolving to an external crate.
if !(ns == TypeNS && self.extern_prelude.contains(&ident.name)) {
// ... unless the crate name is not in the `extern_prelude`.
return binding;
}
}
let crate_root = if
ns == TypeNS &&
root != keywords::Extern.name() &&
(
ident.name == keywords::Crate.name() ||
ident.name == keywords::DollarCrate.name()
)
{
self.resolve_crate_root(ident)
} else if ns == TypeNS && !ident.is_path_segment_keyword() {
let crate_id =
self.crate_loader.process_path_extern(ident.name, ident.span);
self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
} else {
return Err(Determined);
};
self.populate_module_if_necessary(crate_root);
let binding = (crate_root, ty::Visibility::Public,
ident.span, Mark::root()).to_name_binding(self.arenas);
return Ok(binding);
}
};
self.populate_module_if_necessary(module);
let resolution = self.resolution(module, ident, ns)
.try_borrow_mut()
.map_err(|_| Determined)?; // This happens when there is a cycle of imports
if let Some(binding) = resolution.binding {
if !restricted_shadowing && binding.expansion != Mark::root() {
if let NameBindingKind::Def(_, true) = binding.kind {
self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
}
}
}
if record_used {
if let Some(binding) = resolution.binding {
if let Some(shadowed_glob) = resolution.shadowed_glob {
let name = ident.name;
// Forbid expanded shadowing to avoid time travel.
if restricted_shadowing &&
binding.expansion != Mark::root() &&
ns != MacroNS && // In MacroNS, `try_define` always forbids this shadowing
binding.def() != shadowed_glob.def() {
self.ambiguity_errors.push(AmbiguityError {
span: path_span,
name,
lexical: false,
b1: binding,
b2: shadowed_glob,
});
}
}
if self.record_use(ident, ns, binding, path_span) {
return Ok(self.dummy_binding);
}
if !self.is_accessible(binding.vis) {
self.privacy_errors.push(PrivacyError(path_span, ident.name, binding));
}
}
return resolution.binding.ok_or(Determined);
}
let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
// `extern crate` are always usable for backwards compatibility, see issue #37020.
let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
if usable { Ok(binding) } else { Err(Determined) }
};
// Items and single imports are not shadowable, if we have one, then it's determined.
if let Some(binding) = resolution.binding {
if !binding.is_glob_import() {
return check_usable(self, binding);
}
}
// --- From now on we either have a glob resolution or no resolution. ---
// Check if one of single imports can still define the name,
// if it can then our result is not determined and can be invalidated.
for single_import in &resolution.single_imports {
if !self.is_accessible(single_import.vis.get()) {
continue;
}
let module = unwrap_or!(single_import.imported_module.get(), return Err(Undetermined));
let ident = match single_import.subclass {
SingleImport { source, .. } => source,
_ => unreachable!(),
};
match self.resolve_ident_in_module(module, ident, ns, false, path_span) {
Err(Determined) => continue,
Ok(_) | Err(Undetermined) => return Err(Undetermined),
}
}
// So we have a resolution that's from a glob import. This resolution is determined
// if it cannot be shadowed by some new item/import expanded from a macro.
// This happens either if there are no unexpanded macros, or expanded names cannot
// shadow globs (that happens in macro namespace or with restricted shadowing).
//
// Additionally, any macro in any module can plant names in the root module if it creates
// `macro_export` macros, so the root module effectively has unresolved invocations if any
// module has unresolved invocations.
// However, it causes resolution/expansion to stuck too often (#53144), so, to make
// progress, we have to ignore those potential unresolved invocations from other modules
// and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
// shadowing is enabled, see `macro_expanded_macro_export_errors`).
let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
if let Some(binding) = resolution.binding {
if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
return check_usable(self, binding);
} else {
return Err(Undetermined);
}
}
// --- From now on we have no resolution. ---
// Now we are in situation when new item/import can appear only from a glob or a macro
// expansion. With restricted shadowing names from globs and macro expansions cannot
// shadow names from outer scopes, so we can freely fallback from module search to search
// in outer scopes. To continue search in outer scopes we have to lie a bit and return
// `Determined` to `resolve_lexical_macro_path_segment` even if the correct answer
// for in-module resolution could be `Undetermined`.
if restricted_shadowing {
return Err(Determined);
}
// Check if one of unexpanded macros can still define the name,
// if it can then our "no resolution" result is not determined and can be invalidated.
if unexpanded_macros {
return Err(Undetermined);
}
// Check if one of glob imports can still define the name,
// if it can then our "no resolution" result is not determined and can be invalidated.
for glob_import in module.globs.borrow().iter() {
if !self.is_accessible(glob_import.vis.get()) {
continue
}
let module = match glob_import.imported_module.get() {
Some(ModuleOrUniformRoot::Module(module)) => module,
Some(ModuleOrUniformRoot::UniformRoot(_)) => continue,
None => return Err(Undetermined),
};
let (orig_current_module, mut ident) = (self.current_module, ident.modern());
match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
Some(Some(def)) => self.current_module = self.macro_def_scope(def),
Some(None) => {}
None => continue,
};
let result = self.resolve_ident_in_module_unadjusted(
ModuleOrUniformRoot::Module(module),
ident,
ns,
false,
false,
path_span,
);
self.current_module = orig_current_module;
match result {
Err(Determined) => continue,
Ok(_) | Err(Undetermined) => return Err(Undetermined),
}
}
// No resolution and no one else can define the name - determinate error.
Err(Determined)
}
// Add an import directive to the current module.
pub fn add_import_directive(&mut self,
module_path: Vec<Ident>,
subclass: ImportDirectiveSubclass<'a>,
span: Span,
id: NodeId,
root_span: Span,
root_id: NodeId,
vis: ty::Visibility,
expansion: Mark,
is_uniform_paths_canary: bool) {
let current_module = self.current_module;
let directive = self.arenas.alloc_import_directive(ImportDirective {
parent: current_module,
module_path,
imported_module: Cell::new(None),
subclass,
span,
id,
root_span,
root_id,
vis: Cell::new(vis),
expansion,
used: Cell::new(false),
is_uniform_paths_canary,
});
debug!("add_import_directive({:?})", directive);
self.indeterminate_imports.push(directive);
match directive.subclass {
SingleImport { target, type_ns_only, .. } => {
self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
resolution.single_imports.insert(PtrKey(directive));
});
}
// We don't add prelude imports to the globs since they only affect lexical scopes,
// which are not relevant to import resolution.
GlobImport { is_prelude: true, .. } => {}
GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
_ => unreachable!(),
}
}
// Given a binding and an import directive that resolves to it,
// return the corresponding binding defined by the import directive.
pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
-> &'a NameBinding<'a> {
let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
// c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
!directive.is_glob() && binding.is_extern_crate() {
directive.vis.get()
} else {
binding.pseudo_vis()
};
if let GlobImport { ref max_vis, .. } = directive.subclass {
if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
max_vis.set(vis)
}
}
self.arenas.alloc_name_binding(NameBinding {
kind: NameBindingKind::Import {
binding,
directive,
used: Cell::new(false),
},
span: directive.span,
vis,
expansion: directive.expansion,
})
}
// Define the name or return the existing binding if there is a collision.
pub fn try_define(&mut self,
module: Module<'a>,
ident: Ident,
ns: Namespace,
binding: &'a NameBinding<'a>)
-> Result<(), &'a NameBinding<'a>> {
self.update_resolution(module, ident, ns, |this, resolution| {
if let Some(old_binding) = resolution.binding {
if binding.is_glob_import() {
if !old_binding.is_glob_import() &&
!(ns == MacroNS && old_binding.expansion != Mark::root()) {
resolution.shadowed_glob = Some(binding);
} else if binding.def() != old_binding.def() {
resolution.binding = Some(this.ambiguity(old_binding, binding));
} else if !old_binding.vis.is_at_least(binding.vis, &*this) {
// We are glob-importing the same item but with greater visibility.
resolution.binding = Some(binding);
}
} else if old_binding.is_glob_import() {
if ns == MacroNS && binding.expansion != Mark::root() &&
binding.def() != old_binding.def() {
resolution.binding = Some(this.ambiguity(binding, old_binding));
} else {
resolution.binding = Some(binding);
resolution.shadowed_glob = Some(old_binding);
}
} else if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
(&old_binding.kind, &binding.kind) {
this.session.buffer_lint_with_diagnostic(
DUPLICATE_MACRO_EXPORTS,
CRATE_NODE_ID,
binding.span,
&format!("a macro named `{}` has already been exported", ident),
BuiltinLintDiagnostics::DuplicatedMacroExports(
ident, old_binding.span, binding.span));
resolution.binding = Some(binding);
} else {
return Err(old_binding);
}
} else {
resolution.binding = Some(binding);
}
Ok(())
})
}
pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
-> &'a NameBinding<'a> {
self.arenas.alloc_name_binding(NameBinding {
kind: NameBindingKind::Ambiguity { b1, b2 },
vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
span: b1.span,
expansion: Mark::root(),
})
}
// Use `f` to mutate the resolution of the name in the module.
// If the resolution becomes a success, define it in the module's glob importers.
fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
-> T
where F: FnOnce(&mut Resolver<'a, 'crateloader>, &mut NameResolution<'a>) -> T
{
// Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
// during which the resolution might end up getting re-defined via a glob cycle.
let (binding, t) = {
let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
let old_binding = resolution.binding();
let t = f(self, resolution);
match resolution.binding() {
_ if old_binding.is_some() => return t,
None => return t,
Some(binding) => match old_binding {
Some(old_binding) if ptr::eq(old_binding, binding) => return t,
_ => (binding, t),
}
}
};
// Define `binding` in `module`s glob importers.
for directive in module.glob_importers.borrow_mut().iter() {
let mut ident = ident.modern();
let scope = match ident.span.reverse_glob_adjust(module.expansion,
directive.span.ctxt().modern()) {
Some(Some(def)) => self.macro_def_scope(def),
Some(None) => directive.parent,
None => continue,
};
if self.is_accessible_from(binding.vis, scope) {
let imported_binding = self.import(binding, directive);
let _ = self.try_define(directive.parent, ident, ns, imported_binding);
}
}
t
}
// Define a "dummy" resolution containing a Def::Err as a placeholder for a
// failed resolution
fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
if let SingleImport { target, .. } = directive.subclass {
let dummy_binding = self.dummy_binding;
let dummy_binding = self.import(dummy_binding, directive);
self.per_ns(|this, ns| {
let _ = this.try_define(directive.parent, target, ns, dummy_binding);
});
}
}
}
pub struct ImportResolver<'a, 'b: 'a, 'c: 'a + 'b> {
pub resolver: &'a mut Resolver<'b, 'c>,
}
impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::Deref for ImportResolver<'a, 'b, 'c> {
type Target = Resolver<'b, 'c>;
fn deref(&self) -> &Resolver<'b, 'c> {
self.resolver
}
}
impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::DerefMut for ImportResolver<'a, 'b, 'c> {
fn deref_mut(&mut self) -> &mut Resolver<'b, 'c> {
self.resolver
}
}
impl<'a, 'b: 'a, 'c: 'a + 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b, 'c> {
fn parent(self, id: DefId) -> Option<DefId> {
self.resolver.parent(id)
}
}
impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
// Import resolution
//
// This is a fixed-point algorithm. We resolve imports until our efforts
// are stymied by an unresolved import; then we bail out of the current
// module and continue. We terminate successfully once no more imports
// remain or unsuccessfully when no forward progress in resolving imports
// is made.
/// Resolves all imports for the crate. This method performs the fixed-
/// point iteration.
pub fn resolve_imports(&mut self) {
let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
while self.indeterminate_imports.len() < prev_num_indeterminates {
prev_num_indeterminates = self.indeterminate_imports.len();
for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
match self.resolve_import(&import) {
true => self.determined_imports.push(import),
false => self.indeterminate_imports.push(import),
}
}
}
}
pub fn finalize_imports(&mut self) {
for module in self.arenas.local_modules().iter() {
self.finalize_resolutions_in(module);
}
let mut errors = false;
let mut seen_spans = FxHashSet();
for i in 0 .. self.determined_imports.len() {
let import = self.determined_imports[i];
let error = self.finalize_import(import);
// For a `#![feature(uniform_paths)]` `use self::x as _` canary,
// failure is ignored, while success may cause an ambiguity error.
if import.is_uniform_paths_canary {
let (name, result) = match import.subclass {
SingleImport { source, ref result, .. } => {
let type_ns = result[TypeNS].get().ok();
let value_ns = result[ValueNS].get().ok();
(source.name, type_ns.or(value_ns))
}
_ => bug!(),
};
if error.is_some() {
continue;
}
let is_explicit_self =
import.module_path.len() > 0 &&
import.module_path[0].name == keywords::SelfValue.name();
let extern_crate_exists = self.extern_prelude.contains(&name);
// A successful `self::x` is ambiguous with an `x` external crate.
if is_explicit_self && !extern_crate_exists {
continue;
}
errors = true;
let msg = format!("import from `{}` is ambiguous", name);
let mut err = self.session.struct_span_err(import.span, &msg);
if extern_crate_exists {
err.span_label(import.span,
format!("could refer to external crate `::{}`", name));
}
if let Some(result) = result {
if is_explicit_self {
err.span_label(result.span,
format!("could also refer to `self::{}`", name));
} else {
err.span_label(result.span,
format!("shadowed by block-scoped `{}`", name));
}
}
err.help(&format!("write `::{0}` or `self::{0}` explicitly instead", name));
err.note("relative `use` paths enabled by `#![feature(uniform_paths)]`");
err.emit();
} else if let Some((span, err)) = error {
errors = true;
if let SingleImport { source, ref result, .. } = import.subclass {
if source.name == "self" {
// Silence `unresolved import` error if E0429 is already emitted
match result.value_ns.get() {
Err(Determined) => continue,
_ => {},
}
}
}
// If the error is a single failed import then create a "fake" import
// resolution for it so that later resolve stages won't complain.
self.import_dummy_binding(import);
if !seen_spans.contains(&span) {
let path = import_path_to_string(&import.module_path[..],
&import.subclass,
span);
let error = ResolutionError::UnresolvedImport(Some((span, &path, &err)));
resolve_error(self.resolver, span, error);
seen_spans.insert(span);
}
}
}
// Report unresolved imports only if no hard error was already reported
// to avoid generating multiple errors on the same import.
if !errors {
for import in &self.indeterminate_imports {
if import.is_uniform_paths_canary {
continue;
}
let error = ResolutionError::UnresolvedImport(None);
resolve_error(self.resolver, import.span, error);
break;
}
}
}
/// Attempts to resolve the given import, returning true if its resolution is determined.
/// If successful, the resolved bindings are written into the module.
fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
debug!("(resolving import for module) resolving import `{}::...` in `{}`",
names_to_string(&directive.module_path[..]),
module_to_string(self.current_module).unwrap_or("???".to_string()));
self.current_module = directive.parent;
let module = if let Some(module) = directive.imported_module.get() {
module
} else {
let vis = directive.vis.get();
// For better failure detection, pretend that the import will not define any names
// while resolving its module path.
directive.vis.set(ty::Visibility::Invisible);
let result = self.resolve_path(
Some(if directive.is_uniform_paths_canary {
ModuleOrUniformRoot::Module(directive.parent)
} else {
ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
}),
&directive.module_path[..],
None,
false,
directive.span,
directive.crate_lint(),
);
directive.vis.set(vis);
match result {
PathResult::Module(module) => module,
PathResult::Indeterminate => return false,
_ => return true,
}
};
directive.imported_module.set(Some(module));
let (source, target, result, type_ns_only) = match directive.subclass {
SingleImport { source, target, ref result, type_ns_only } =>
(source, target, result, type_ns_only),
GlobImport { .. } => {
self.resolve_glob_import(directive);
return true;
}
_ => unreachable!(),
};
let mut indeterminate = false;
self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
if let Err(Undetermined) = result[ns].get() {
result[ns].set(this.resolve_ident_in_module(module,
source,
ns,
false,
directive.span));
} else {
return
};
let parent = directive.parent;
match result[ns].get() {
Err(Undetermined) => indeterminate = true,
Err(Determined) => {
this.update_resolution(parent, target, ns, |_, resolution| {
resolution.single_imports.remove(&PtrKey(directive));
});
}
Ok(binding) if !binding.is_importable() => {
let msg = format!("`{}` is not directly importable", target);
struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
.span_label(directive.span, "cannot be imported directly")
.emit();
// Do not import this illegal binding. Import a dummy binding and pretend
// everything is fine
this.import_dummy_binding(directive);
}
Ok(binding) => {
let imported_binding = this.import(binding, directive);
let conflict = this.try_define(parent, target, ns, imported_binding);
if let Err(old_binding) = conflict {
this.report_conflict(parent, target, ns, imported_binding, old_binding);
}
}
}
});
!indeterminate
}
// If appropriate, returns an error to report.
fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<(Span, String)> {
self.current_module = directive.parent;
let ImportDirective { ref module_path, span, .. } = *directive;
let module_result = self.resolve_path(
Some(if directive.is_uniform_paths_canary {
ModuleOrUniformRoot::Module(directive.parent)
} else {
ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
}),
&module_path,
None,
true,
span,
directive.crate_lint(),
);
let module = match module_result {
PathResult::Module(module) => module,
PathResult::Failed(span, msg, false) => {
resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
return None;
}
PathResult::Failed(span, msg, true) => {
let (mut self_path, mut self_result) = (module_path.clone(), None);
let is_special = |ident: Ident| ident.is_path_segment_keyword() &&
ident.name != keywords::CrateRoot.name();
if !self_path.is_empty() && !is_special(self_path[0]) &&
!(self_path.len() > 1 && is_special(self_path[1])) {
self_path[0].name = keywords::SelfValue.name();
self_result = Some(self.resolve_path(None, &self_path, None, false,
span, CrateLint::No));
}
return if let Some(PathResult::Module(..)) = self_result {
Some((span, format!("Did you mean `{}`?", names_to_string(&self_path[..]))))
} else {
Some((span, msg))
};
},
_ => return None,
};
let (ident, result, type_ns_only) = match directive.subclass {
SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only),
GlobImport { is_prelude, ref max_vis } => {
if module_path.len() <= 1 {
// HACK(eddyb) `lint_if_path_starts_with_module` needs at least
// 2 segments, so the `resolve_path` above won't trigger it.
let mut full_path = module_path.clone();
full_path.push(keywords::Invalid.ident());
self.lint_if_path_starts_with_module(
directive.crate_lint(),
&full_path,
directive.span,
None,
);
}
if let ModuleOrUniformRoot::Module(module) = module {
if module.def_id() == directive.parent.def_id() {
// Importing a module into itself is not allowed.
return Some((directive.span,
"Cannot glob-import a module into itself.".to_string()));
}
}
if !is_prelude &&
max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
!max_vis.get().is_at_least(directive.vis.get(), &*self) {
let msg = "A non-empty glob must import something with the glob's visibility";
self.session.span_err(directive.span, msg);
}
return None;
}
_ => unreachable!(),
};
let mut all_ns_err = true;
self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
if let Ok(binding) = result[ns].get() {
all_ns_err = false;
if this.record_use(ident, ns, binding, directive.span) {
if let ModuleOrUniformRoot::Module(module) = module {
this.resolution(module, ident, ns).borrow_mut().binding =
Some(this.dummy_binding);
}
}
}
});
if all_ns_err {
let mut all_ns_failed = true;
self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
match this.resolve_ident_in_module(module, ident, ns, true, span) {
Ok(_) => all_ns_failed = false,
_ => {}
}
});
return if all_ns_failed {
let resolutions = match module {
ModuleOrUniformRoot::Module(module) =>
Some(module.resolutions.borrow()),
ModuleOrUniformRoot::UniformRoot(_) => None,
};
let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
if *i == ident { return None; } // Never suggest the same name
match *resolution.borrow() {
NameResolution { binding: Some(name_binding), .. } => {
match name_binding.kind {
NameBindingKind::Import { binding, .. } => {
match binding.kind {
// Never suggest the name that has binding error
// i.e. the name that cannot be previously resolved
NameBindingKind::Def(Def::Err, _) => return None,
_ => Some(&i.name),
}
},
_ => Some(&i.name),
}
},
NameResolution { ref single_imports, .. }
if single_imports.is_empty() => None,
_ => Some(&i.name),
}
});
let lev_suggestion =
match find_best_match_for_name(names, &ident.as_str(), None) {
Some(name) => format!(". Did you mean to use `{}`?", name),
None => "".to_owned(),
};
let msg = match module {
ModuleOrUniformRoot::Module(module) => {
let module_str = module_to_string(module);
if let Some(module_str) = module_str {
format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
} else {
format!("no `{}` in the root{}", ident, lev_suggestion)
}
}
ModuleOrUniformRoot::UniformRoot(_) => {
if !ident.is_path_segment_keyword() {
format!("no `{}` external crate{}", ident, lev_suggestion)
} else {
// HACK(eddyb) this shows up for `self` & `super`, which
// should work instead - for now keep the same error message.
format!("no `{}` in the root{}", ident, lev_suggestion)
}
}
};
Some((span, msg))
} else {
// `resolve_ident_in_module` reported a privacy error.
self.import_dummy_binding(directive);
None
}
}
let mut reexport_error = None;
let mut any_successful_reexport = false;
self.per_ns(|this, ns| {
if let Ok(binding) = result[ns].get() {
let vis = directive.vis.get();
if !binding.pseudo_vis().is_at_least(vis, &*this) {
reexport_error = Some((ns, binding));
} else {
any_successful_reexport = true;
}
}
});
// All namespaces must be re-exported with extra visibility for an error to occur.
if !any_successful_reexport {
let (ns, binding) = reexport_error.unwrap();
if ns == TypeNS && binding.is_extern_crate() {
let msg = format!("extern crate `{}` is private, and cannot be \
re-exported (error E0365), consider declaring with \
`pub`",
ident);
self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
directive.id,
directive.span,
&msg);
} else if ns == TypeNS {
struct_span_err!(self.session, directive.span, E0365,
"`{}` is private, and cannot be re-exported", ident)
.span_label(directive.span, format!("re-export of private `{}`", ident))
.note(&format!("consider declaring type or module `{}` with `pub`", ident))
.emit();
} else {
let msg = format!("`{}` is private, and cannot be re-exported", ident);
let note_msg =
format!("consider marking `{}` as `pub` in the imported module", ident);
struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
.span_note(directive.span, ¬e_msg)
.emit();
}
}
if module_path.len() <= 1 {
// HACK(eddyb) `lint_if_path_starts_with_module` needs at least
// 2 segments, so the `resolve_path` above won't trigger it.
let mut full_path = module_path.clone();
full_path.push(ident);
self.per_ns(|this, ns| {
if let Ok(binding) = result[ns].get() {
this.lint_if_path_starts_with_module(
directive.crate_lint(),
&full_path,
directive.span,
Some(binding),
);
}
});
}
// Record what this import resolves to for later uses in documentation,
// this may resolve to either a value or a type, but for documentation
// purposes it's good enough to just favor one over the other.
self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() {
let import = this.import_map.entry(directive.id).or_default();
import[ns] = Some(PathResolution::new(binding.def()));
});
debug!("(resolving single import) successfully resolved import");
None
}
fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
let module = match directive.imported_module.get().unwrap() {
ModuleOrUniformRoot::Module(module) => module,
ModuleOrUniformRoot::UniformRoot(_) => {
self.session.span_err(directive.span,
"cannot glob-import all possible crates");
return;
}
};
self.populate_module_if_necessary(module);
if let Some(Def::Trait(_)) = module.def() {
self.session.span_err(directive.span, "items in traits are not importable.");
return;
} else if module.def_id() == directive.parent.def_id() {
return;
} else if let GlobImport { is_prelude: true, .. } = directive.subclass {
self.prelude = Some(module);
return;
}
// Add to module's glob_importers
module.glob_importers.borrow_mut().push(directive);
// Ensure that `resolutions` isn't borrowed during `try_define`,
// since it might get updated via a glob cycle.
let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
resolution.borrow().binding().map(|binding| (ident, binding))
}).collect::<Vec<_>>();
for ((mut ident, ns), binding) in bindings {
let scope = match ident.span.reverse_glob_adjust(module.expansion,
directive.span.ctxt().modern()) {
Some(Some(def)) => self.macro_def_scope(def),
Some(None) => self.current_module,
None => continue,
};
if self.is_accessible_from(binding.pseudo_vis(), scope) {
let imported_binding = self.import(binding, directive);
let _ = self.try_define(directive.parent, ident, ns, imported_binding);
}
}
// Record the destination of this import
self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
}
// Miscellaneous post-processing, including recording re-exports,
// reporting conflicts, and reporting unresolved imports.
fn finalize_resolutions_in(&mut self, module: Module<'b>) {
// Since import resolution is finished, globs will not define any more names.
*module.globs.borrow_mut() = Vec::new();
let mut reexports = Vec::new();
let mut exported_macro_names = FxHashMap();
if ptr::eq(module, self.graph_root) {
let macro_exports = mem::replace(&mut self.macro_exports, Vec::new());
for export in macro_exports.into_iter().rev() {
if let Some(later_span) = exported_macro_names.insert(export.ident.modern(),
export.span) {
self.session.buffer_lint_with_diagnostic(
DUPLICATE_MACRO_EXPORTS,
CRATE_NODE_ID,
later_span,
&format!("a macro named `{}` has already been exported", export.ident),
BuiltinLintDiagnostics::DuplicatedMacroExports(
export.ident, export.span, later_span));
} else {
reexports.push(export);
}
}
}
for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
let resolution = &mut *resolution.borrow_mut();
let binding = match resolution.binding {
Some(binding) => binding,
None => continue,
};
if binding.is_import() || binding.is_macro_def() {
let def = binding.def();
if def != Def::Err {
if !def.def_id().is_local() {
self.cstore.export_macros_untracked(def.def_id().krate);
}
if let Def::Macro(..) = def {
if let Some(&span) = exported_macro_names.get(&ident.modern()) {
let msg =
format!("a macro named `{}` has already been exported", ident);
self.session.struct_span_err(span, &msg)
.span_label(span, format!("`{}` already exported", ident))
.span_note(binding.span, "previous macro export here")
.emit();
}
}
reexports.push(Export {
ident: ident.modern(),
def: def,
span: binding.span,
vis: binding.vis,
});
}
}
match binding.kind {
NameBindingKind::Import { binding: orig_binding, directive, .. } => {
if ns == TypeNS && orig_binding.is_variant() &&
!orig_binding.vis.is_at_least(binding.vis, &*self) {
let msg = match directive.subclass {
ImportDirectiveSubclass::SingleImport { .. } => {
format!("variant `{}` is private and cannot be re-exported",
ident)
},
ImportDirectiveSubclass::GlobImport { .. } => {
let msg = "enum is private and its variants \
cannot be re-exported".to_owned();
let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
Some(binding.span),
msg.clone());
let fresh = self.session.one_time_diagnostics
.borrow_mut().insert(error_id);
if !fresh {
continue;
}
msg
},
ref s @ _ => bug!("unexpected import subclass {:?}", s)
};
let mut err = self.session.struct_span_err(binding.span, &msg);
let imported_module = match directive.imported_module.get() {
Some(ModuleOrUniformRoot::Module(module)) => module,
_ => bug!("module should exist"),
};
let resolutions = imported_module.parent.expect("parent should exist")
.resolutions.borrow();
let enum_path_segment_index = directive.module_path.len() - 1;
let enum_ident = directive.module_path[enum_path_segment_index];
let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
.expect("resolution should exist");
let enum_span = enum_resolution.borrow()
.binding.expect("binding should exist")
.span;
let enum_def_span = self.session.codemap().def_span(enum_span);
let enum_def_snippet = self.session.codemap()
.span_to_snippet(enum_def_span).expect("snippet should exist");
// potentially need to strip extant `crate`/`pub(path)` for suggestion
let after_vis_index = enum_def_snippet.find("enum")
.expect("`enum` keyword should exist in snippet");
let suggestion = format!("pub {}",
&enum_def_snippet[after_vis_index..]);
self.session
.diag_span_suggestion_once(&mut err,
DiagnosticMessageId::ErrorId(0),
enum_def_span,
"consider making the enum public",
suggestion);
err.emit();
}
}
_ => {}
}
}
if reexports.len() > 0 {
if let Some(def_id) = module.def_id() {
self.export_map.insert(def_id, reexports);
}
}
}
}
fn import_path_to_string(names: &[Ident],
subclass: &ImportDirectiveSubclass,
span: Span) -> String {
let pos = names.iter()
.position(|p| span == p.span && p.name != keywords::CrateRoot.name());
let global = !names.is_empty() && names[0].name == keywords::CrateRoot.name();
if let Some(pos) = pos {
let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
names_to_string(names)
} else {
let names = if global { &names[1..] } else { names };
if names.is_empty() {
import_directive_subclass_to_string(subclass)
} else {
format!("{}::{}",
names_to_string(names),
import_directive_subclass_to_string(subclass))
}
}
}
fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
match *subclass {
SingleImport { source, .. } => source.to_string(),
GlobImport { .. } => "*".to_string(),
ExternCrate(_) => "<extern crate>".to_string(),
MacroUse => "#[macro_use]".to_string(),
}
}
|
// 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::net::SocketAddr;
use std::path::Path;
use common_config::InnerConfig;
use common_exception::ErrorCode;
use common_http::health_handler;
use common_http::home::debug_home_handler;
#[cfg(feature = "memory-profiling")]
use common_http::jeprof::debug_jeprof_dump_handler;
use common_http::pprof::debug_pprof_handler;
use common_http::HttpError;
use common_http::HttpShutdownHandler;
use common_meta_types::anyerror::AnyError;
use poem::get;
use poem::listener::RustlsCertificate;
use poem::listener::RustlsConfig;
use poem::Endpoint;
use poem::Route;
use tracing::info;
use tracing::warn;
use crate::servers::Server;
pub struct HttpService {
config: InnerConfig,
shutdown_handler: HttpShutdownHandler,
}
impl HttpService {
pub fn create(config: &InnerConfig) -> Box<HttpService> {
Box::new(HttpService {
config: config.clone(),
shutdown_handler: HttpShutdownHandler::create("http api".to_string()),
})
}
fn build_router(&self) -> impl Endpoint {
#[cfg_attr(not(feature = "memory-profiling"), allow(unused_mut))]
let mut route = Route::new()
.at("/v1/health", get(health_handler))
.at("/v1/config", get(super::http::v1::config::config_handler))
.at("/v1/logs", get(super::http::v1::logs::logs_handler))
.at(
"/v1/status",
get(super::http::v1::instance_status::instance_status_handler),
)
.at(
"/v1/tables",
get(super::http::v1::tenant_tables::list_tables_handler),
)
.at(
"/v1/cluster/list",
get(super::http::v1::cluster::cluster_list_handler),
)
.at("/debug/home", get(debug_home_handler))
.at("/debug/pprof/profile", get(debug_pprof_handler));
if self.config.query.management_mode {
route = route.at(
"/v1/tenants/:tenant/tables",
get(super::http::v1::tenant_tables::list_tenant_tables_handler),
)
}
#[cfg(feature = "memory-profiling")]
{
route = route.at(
// to follow the conversions of jepref, we arrange the path in
// this way, so that jeprof could be invoked like:
// `jeprof ./target/debug/databend-query http://localhost:8080/debug/mem`
// and jeprof will translate the above url into sth like:
// "http://localhost:8080/debug/mem/pprof/profile?seconds=30"
"/debug/mem/pprof/profile",
get(debug_jeprof_dump_handler),
);
};
route
}
fn build_tls(config: &InnerConfig) -> Result<RustlsConfig, std::io::Error> {
let certificate = RustlsCertificate::new()
.cert(std::fs::read(config.query.api_tls_server_cert.as_str())?)
.key(std::fs::read(config.query.api_tls_server_key.as_str())?);
let mut cfg = RustlsConfig::new().fallback(certificate);
if Path::new(&config.query.api_tls_server_root_ca_cert).exists() {
cfg = cfg.client_auth_required(std::fs::read(
config.query.api_tls_server_root_ca_cert.as_str(),
)?);
}
Ok(cfg)
}
async fn start_with_tls(&mut self, listening: SocketAddr) -> Result<SocketAddr, HttpError> {
info!("Http API TLS enabled");
let tls_config = Self::build_tls(&self.config)
.map_err(|e| HttpError::TlsConfigError(AnyError::new(&e)))?;
let addr = self
.shutdown_handler
.start_service(listening, Some(tls_config), self.build_router(), None)
.await?;
Ok(addr)
}
async fn start_without_tls(&mut self, listening: SocketAddr) -> Result<SocketAddr, HttpError> {
warn!("Http API TLS not set");
let addr = self
.shutdown_handler
.start_service(listening, None, self.build_router(), None)
.await?;
Ok(addr)
}
}
#[async_trait::async_trait]
impl Server for HttpService {
async fn shutdown(&mut self, graceful: bool) {
self.shutdown_handler.shutdown(graceful).await;
}
async fn start(&mut self, listening: SocketAddr) -> Result<SocketAddr, ErrorCode> {
let config = &self.config.query;
let res =
match config.api_tls_server_key.is_empty() || config.api_tls_server_cert.is_empty() {
true => self.start_without_tls(listening).await,
false => self.start_with_tls(listening).await,
};
res.map_err(|e: HttpError| match e {
HttpError::BadAddressFormat(any_err) => {
ErrorCode::BadAddressFormat(any_err.to_string())
}
le @ HttpError::ListenError { .. } => ErrorCode::CannotListenerPort(le.to_string()),
HttpError::TlsConfigError(any_err) => {
ErrorCode::TLSConfigurationFailure(any_err.to_string())
}
})
}
}
|
// Copyright 2020 IOTA Stiftung
//
// 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.
#[macro_use]
mod test_macros;
use bee_crypto::ternary::bigint::i384::{
LE_U32_0, LE_U32_1, LE_U32_2, LE_U32_MAX, LE_U32_MIN, LE_U32_NEG_1, LE_U32_NEG_2,
};
test_binary_op!(
[min_minus_one_is_max, sub_inplace, LE_U32_MIN, LE_U32_1, LE_U32_MAX],
[
min_plus_neg_one_is_max,
add_inplace,
LE_U32_MIN,
LE_U32_NEG_1,
LE_U32_MAX
],
[min_minus_zero_is_min, sub_inplace, LE_U32_MIN, LE_U32_0, LE_U32_MIN],
[min_plus_zero_is_min, add_inplace, LE_U32_MIN, LE_U32_0, LE_U32_MIN],
[
neg_one_minus_one_is_neg_two,
sub_inplace,
LE_U32_NEG_1,
LE_U32_1,
LE_U32_NEG_2
],
[
neg_one_minus_neg_one_is_zero,
sub_inplace,
LE_U32_NEG_1,
LE_U32_NEG_1,
LE_U32_0
],
[neg_one_plus_one_is_zero, add_inplace, LE_U32_NEG_1, LE_U32_1, LE_U32_0],
[
neg_one_plus_neg_one_is_neg_two,
add_inplace,
LE_U32_NEG_1,
LE_U32_NEG_1,
LE_U32_NEG_2
],
[zero_minus_one_is_neg_one, sub_inplace, LE_U32_0, LE_U32_1, LE_U32_NEG_1],
[zero_minus_neg_one_is_one, sub_inplace, LE_U32_0, LE_U32_NEG_1, LE_U32_1],
[zero_plus_one_is_one, add_inplace, LE_U32_0, LE_U32_1, LE_U32_1],
[
zero_plus_neg_one_is_neg_one,
add_inplace,
LE_U32_0,
LE_U32_NEG_1,
LE_U32_NEG_1
],
[one_minus_neg_one_is_two, sub_inplace, LE_U32_1, LE_U32_NEG_1, LE_U32_2],
[one_minus_one_is_zero, sub_inplace, LE_U32_1, LE_U32_1, LE_U32_0],
[one_plus_one_is_two, add_inplace, LE_U32_1, LE_U32_1, LE_U32_2],
[one_plus_neg_one_is_zero, add_inplace, LE_U32_1, LE_U32_NEG_1, LE_U32_0],
[max_plus_one_is_min, add_inplace, LE_U32_MAX, LE_U32_1, LE_U32_MIN],
[
max_minus_neg_one_is_min,
sub_inplace,
LE_U32_MAX,
LE_U32_NEG_1,
LE_U32_MIN
],
);
test_binary_op_calc_result!(
[
min_minus_two_is_max_minus_one,
sub_inplace,
LE_U32_MIN,
LE_U32_2,
sub_inplace,
LE_U32_MAX,
LE_U32_1
],
[
min_plus_one_is_max_plus_two,
add_inplace,
LE_U32_MIN,
LE_U32_1,
add_inplace,
LE_U32_MAX,
LE_U32_2
],
);
test_endianness_toggle!((I384), [u8_repr, U8Repr], [u32_repr, U32Repr],);
test_endianness_roundtrip!((I384), [u8_repr, U8Repr], [u32_repr, U32Repr],);
test_repr_roundtrip!((I384), [big_endian, BigEndian], [little_endian, LittleEndian],);
|
use std::sync::Arc;
use data_types::{
Column, ColumnId, ColumnType, ColumnsByName, NamespaceId, PartitionHashId, PartitionId,
PartitionKey, Table, TableId, TableSchema,
};
use crate::PartitionInfo;
pub struct PartitionInfoBuilder {
inner: PartitionInfo,
}
impl PartitionInfoBuilder {
pub fn new() -> Self {
let partition_id = PartitionId::new(1);
let namespace_id = NamespaceId::new(2);
let table_id = TableId::new(3);
let partition_key = PartitionKey::from("key");
let partition_hash_id = Some(PartitionHashId::new(table_id, &partition_key));
let table = Arc::new(Table {
id: table_id,
namespace_id,
name: String::from("table"),
partition_template: Default::default(),
});
let table_schema = Arc::new(TableSchema::new_empty_from(&table));
Self {
inner: PartitionInfo {
partition_id,
partition_hash_id,
namespace_id,
namespace_name: String::from("ns"),
table,
table_schema,
sort_key: None,
partition_key,
},
}
}
pub fn with_partition_id(mut self, id: i64) -> Self {
self.inner.partition_id = PartitionId::new(id);
self
}
pub fn with_num_columns(mut self, num_cols: usize) -> Self {
let columns: Vec<_> = (0..num_cols)
.map(|i| Column {
id: ColumnId::new(i as i64),
name: i.to_string(),
column_type: ColumnType::I64,
table_id: self.inner.table.id,
})
.collect();
let table_schema = Arc::new(TableSchema {
id: self.inner.table.id,
partition_template: Default::default(),
columns: ColumnsByName::new(columns),
});
self.inner.table_schema = table_schema;
self
}
pub fn build(self) -> PartitionInfo {
self.inner
}
}
|
use crate::config;
use crate::source;
use crate::store;
use crate::util;
use crate::video;
use crate::youtube;
pub fn run_url(
config: &config::Config,
store: &mut store::Store,
yt: &youtube::YT,
url: &str,
) -> util::Result<()> {
let yt_sleep_duration = chrono::Duration::hours(4);
let blacklist = store.blacklist()?; // maybe don't init this every time in daemon
log::info!("Processing {}", url);
let mut album = match store.get_album(url)? {
None => source::fetch(url, &config.mp3_dir())?,
Some(album) => {
if album.has_mp3(&config.mp3_dir()) {
album
} else {
// FIXME deletes yt ids!
log::warn!("Album has missing audio files, re-fetching");
return Err(util::Error::new("Refetching overwrites YT ids, FIXME!"));
// source::fetch(url, &config.mp3_dir())?
}
}
};
store.save(&album)?;
if album.license.is_none() {
return Err(util::Error::new("No license"));
}
if blacklist.matches(&album) {
return Err(util::Error::new("Blacklisted"));
}
let album_video_dir = album.dirname(&config.video_dir());
if !album.has_video(&config.video_dir()) {
let cover_img = video::find_cover(&album.dirname(&config.mp3_dir()))?;
let album_mp3_dir = album.dirname(&config.mp3_dir());
util::mkdir_if_not_exists(&album_video_dir);
for mut tr in &mut album.tracks {
let basename = tr.mp3_file.as_ref().ok_or("MP3 file missing")?;
let mut mp3_file = album_mp3_dir.clone();
mp3_file.push(basename);
let mut video_file = album_video_dir.clone();
let basename = basename.with_extension("avi");
video_file.push(basename.clone());
video::convert_file(&mp3_file, &cover_img, &video_file)?;
tr.video_file = Some(basename);
}
store.save(&album)?;
}
//TODO: can delete mp3s here
// generate descriptions first, can't use reference to album inside the for loop
let descriptions = album
.tracks
.iter()
.map(|t| source::description(&album, t))
.collect::<Result<Vec<_>, _>>()?;
for (i, desc) in descriptions.into_iter().enumerate() {
let tr = album.tracks[i].clone();
if let Some(yt_id) = &tr.youtube_id {
log::debug!(
"Track {} already has youtube id {}",
tr.title,
yt_id.as_url()
);
continue;
}
let mut video_file = album_video_dir.clone();
video_file.push(tr.video_file.as_ref().ok_or("Video file missing")?);
let args = youtube::Video {
title: format!("{} - {}", tr.artist, tr.title),
description: desc,
tags: album.tags.clone(),
filename: video_file,
};
let yt_id = util::retry(8, yt_sleep_duration, || yt.upload_video(args.clone()))?;
album.tracks[i].youtube_id = Some(yt_id);
store.save(&album)?;
}
//TODO: can delete videos here
if album.youtube_id.is_none() && album.tracks.iter().all(|t| t.youtube_id.is_some()) {
let args = youtube::Playlist {
title: youtube::playlist_title(&album.title, &album.artist, &album.year, &album.tags),
description: String::new(), // the description is not really visible
tags: album.tags.clone(),
videos: album
.tracks
.iter()
.map(|t| t.youtube_id.clone().expect("Video ID missing"))
.collect(),
};
let yt_id = util::retry(8, yt_sleep_duration, || yt.create_playlist(args.clone()))?;
album.youtube_id = Some(yt_id);
store.save(&album)?;
}
log::info!(
"Success - {} - {}",
url,
album
.youtube_id
.map_or("(no playlist id)".to_string(), |y| y.to_string())
);
Ok(())
}
pub fn daemon(
config: &config::Config,
store: &mut store::Store,
yt: &youtube::YT,
) -> util::Result<()> {
loop {
let (act, url) = match store.queue_get()? {
None => {
log::error!("No more work!");
return Ok(());
}
Some((act, url)) if act == "url" => (act, url),
Some((act, _)) => {
return Err(util::Error::new(&format!("Unknown action {}", act)));
}
};
let res = run_url(config, store, yt, &url);
let status = match res {
Err(e) => {
log::error!("Processing {} failed: {}", url, e);
e.to_string()
}
Ok(()) => "OK".to_string(),
};
store.queue_result(act, url, status)?;
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
|
pub fn strip(chrs: &mut Vec<char>) {
loop {
match chrs.last().cloned() {
None => break,
Some(c) => {
if !c.is_whitespace() {
break;
}
chrs.pop();
}
}
}
}
pub fn char_to_u16(c: &char) -> u16 {
let c2: char = *c;
return c2 as u16;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.