text stringlengths 8 4.13M |
|---|
use anyhow::*;
use std::alloc::Layout;
pub(crate) fn bucket_allocate_cont<T>(buckets: usize) -> Result<Vec<T>> {
// debug_assert!((buckets != 0) && ((buckets & (buckets - 1)) == 0), "Capacity should be power of 2");
// Array of buckets
let data = Layout::array::<T>(buckets)?;
unsafe {
let p = std::alloc::alloc_zeroed(data);
Ok(Vec::<T>::from_raw_parts(p as *mut T, 0, buckets))
}
}
pub(crate) fn bucket_alloc<T>(init_cap: usize) -> Vec<T>
where
T: Default,
{
let data = Layout::array::<T>(init_cap).unwrap();
let p = unsafe { std::alloc::alloc_zeroed(data) as *mut T };
unsafe {
(0..init_cap).for_each(|i| {
std::ptr::write(p.offset(i as isize), T::default());
});
Vec::from_raw_parts(p, init_cap, init_cap)
}
}
|
use std::borrow::Cow;
use std::cmp;
use std::fs;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::io::{self, Error, ErrorKind, SeekFrom};
use std::marker;
use std::path::{Component, Path, PathBuf};
use filetime::{self, FileTime};
use crate::archive::ArchiveInner;
use crate::error::TarError;
use crate::header::bytes2path;
use crate::other;
use crate::{Archive, Header, PaxExtensions};
/// A read-only view into an entry of an archive.
///
/// This structure is a window into a portion of a borrowed archive which can
/// be inspected. It acts as a file handle by implementing the Reader trait. An
/// entry cannot be rewritten once inserted into an archive.
pub struct Entry<'a, R: 'a + Read> {
fields: EntryFields<'a>,
_ignored: marker::PhantomData<&'a Archive<R>>,
}
// private implementation detail of `Entry`, but concrete (no type parameters)
// and also all-public to be constructed from other modules.
pub struct EntryFields<'a> {
pub long_pathname: Option<Vec<u8>>,
pub long_linkname: Option<Vec<u8>>,
pub pax_extensions: Option<Vec<u8>>,
pub mask: u32,
pub header: Header,
pub size: u64,
pub header_pos: u64,
pub file_pos: u64,
pub data: Vec<EntryIo<'a>>,
pub unpack_xattrs: bool,
pub preserve_permissions: bool,
pub preserve_ownerships: bool,
pub preserve_mtime: bool,
pub overwrite: bool,
}
pub enum EntryIo<'a> {
Pad(io::Take<io::Repeat>),
Data(io::Take<&'a ArchiveInner<dyn Read + 'a>>),
}
/// When unpacking items the unpacked thing is returned to allow custom
/// additional handling by users. Today the File is returned, in future
/// the enum may be extended with kinds for links, directories etc.
#[derive(Debug)]
pub enum Unpacked {
/// A file was unpacked.
File(std::fs::File),
/// A directory, hardlink, symlink, or other node was unpacked.
#[doc(hidden)]
__Nonexhaustive,
}
impl<'a, R: Read> Entry<'a, R> {
/// Returns the path name for this entry.
///
/// This method may fail if the pathname is not valid Unicode and this is
/// called on a Windows platform.
///
/// Note that this function will convert any `\` characters to directory
/// separators, and it will not always return the same value as
/// `self.header().path()` as some archive formats have support for longer
/// path names described in separate entries.
///
/// It is recommended to use this method instead of inspecting the `header`
/// directly to ensure that various archive formats are handled correctly.
pub fn path(&self) -> io::Result<Cow<Path>> {
self.fields.path()
}
/// Returns the raw bytes listed for this entry.
///
/// Note that this function will convert any `\` characters to directory
/// separators, and it will not always return the same value as
/// `self.header().path_bytes()` as some archive formats have support for
/// longer path names described in separate entries.
pub fn path_bytes(&self) -> Cow<[u8]> {
self.fields.path_bytes()
}
/// Returns the link name for this entry, if any is found.
///
/// This method may fail if the pathname is not valid Unicode and this is
/// called on a Windows platform. `Ok(None)` being returned, however,
/// indicates that the link name was not present.
///
/// Note that this function will convert any `\` characters to directory
/// separators, and it will not always return the same value as
/// `self.header().link_name()` as some archive formats have support for
/// longer path names described in separate entries.
///
/// It is recommended to use this method instead of inspecting the `header`
/// directly to ensure that various archive formats are handled correctly.
pub fn link_name(&self) -> io::Result<Option<Cow<Path>>> {
self.fields.link_name()
}
/// Returns the link name for this entry, in bytes, if listed.
///
/// Note that this will not always return the same value as
/// `self.header().link_name_bytes()` as some archive formats have support for
/// longer path names described in separate entries.
pub fn link_name_bytes(&self) -> Option<Cow<[u8]>> {
self.fields.link_name_bytes()
}
/// Returns an iterator over the pax extensions contained in this entry.
///
/// Pax extensions are a form of archive where extra metadata is stored in
/// key/value pairs in entries before the entry they're intended to
/// describe. For example this can be used to describe long file name or
/// other metadata like atime/ctime/mtime in more precision.
///
/// The returned iterator will yield key/value pairs for each extension.
///
/// `None` will be returned if this entry does not indicate that it itself
/// contains extensions, or if there were no previous extensions describing
/// it.
///
/// Note that global pax extensions are intended to be applied to all
/// archive entries.
///
/// Also note that this function will read the entire entry if the entry
/// itself is a list of extensions.
pub fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions>> {
self.fields.pax_extensions()
}
/// Returns access to the header of this entry in the archive.
///
/// This provides access to the metadata for this entry in the archive.
pub fn header(&self) -> &Header {
&self.fields.header
}
/// Returns access to the size of this entry in the archive.
///
/// In the event the size is stored in a pax extension, that size value
/// will be referenced. Otherwise, the entry size will be stored in the header.
pub fn size(&self) -> u64 {
self.fields.size
}
/// Returns the starting position, in bytes, of the header of this entry in
/// the archive.
///
/// The header is always a contiguous section of 512 bytes, so if the
/// underlying reader implements `Seek`, then the slice from `header_pos` to
/// `header_pos + 512` contains the raw header bytes.
pub fn raw_header_position(&self) -> u64 {
self.fields.header_pos
}
/// Returns the starting position, in bytes, of the file of this entry in
/// the archive.
///
/// If the file of this entry is continuous (e.g. not a sparse file), and
/// if the underlying reader implements `Seek`, then the slice from
/// `file_pos` to `file_pos + entry_size` contains the raw file bytes.
pub fn raw_file_position(&self) -> u64 {
self.fields.file_pos
}
/// Writes this file to the specified location.
///
/// This function will write the entire contents of this file into the
/// location specified by `dst`. Metadata will also be propagated to the
/// path `dst`.
///
/// This function will create a file at the path `dst`, and it is required
/// that the intermediate directories are created. Any existing file at the
/// location `dst` will be overwritten.
///
/// > **Note**: This function does not have as many sanity checks as
/// > `Archive::unpack` or `Entry::unpack_in`. As a result if you're
/// > thinking of unpacking untrusted tarballs you may want to review the
/// > implementations of the previous two functions and perhaps implement
/// > similar logic yourself.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use tar::Archive;
///
/// let mut ar = Archive::new(File::open("foo.tar").unwrap());
///
/// for (i, file) in ar.entries().unwrap().enumerate() {
/// let mut file = file.unwrap();
/// file.unpack(format!("file-{}", i)).unwrap();
/// }
/// ```
pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<Unpacked> {
self.fields.unpack(None, dst.as_ref())
}
/// Extracts this file under the specified path, avoiding security issues.
///
/// This function will write the entire contents of this file into the
/// location obtained by appending the path of this file in the archive to
/// `dst`, creating any intermediate directories if needed. Metadata will
/// also be propagated to the path `dst`. Any existing file at the location
/// `dst` will be overwritten.
///
/// This function carefully avoids writing outside of `dst`. If the file has
/// a '..' in its path, this function will skip it and return false.
///
/// # Examples
///
/// ```no_run
/// use std::fs::File;
/// use tar::Archive;
///
/// let mut ar = Archive::new(File::open("foo.tar").unwrap());
///
/// for (i, file) in ar.entries().unwrap().enumerate() {
/// let mut file = file.unwrap();
/// file.unpack_in("target").unwrap();
/// }
/// ```
pub fn unpack_in<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<bool> {
self.fields.unpack_in(dst.as_ref())
}
/// Set the mask of the permission bits when unpacking this entry.
///
/// The mask will be inverted when applying against a mode, similar to how
/// `umask` works on Unix. In logical notation it looks like:
///
/// ```text
/// new_mode = old_mode & (~mask)
/// ```
///
/// The mask is 0 by default and is currently only implemented on Unix.
pub fn set_mask(&mut self, mask: u32) {
self.fields.mask = mask;
}
/// Indicate whether extended file attributes (xattrs on Unix) are preserved
/// when unpacking this entry.
///
/// This flag is disabled by default and is currently only implemented on
/// Unix using xattr support. This may eventually be implemented for
/// Windows, however, if other archive implementations are found which do
/// this as well.
pub fn set_unpack_xattrs(&mut self, unpack_xattrs: bool) {
self.fields.unpack_xattrs = unpack_xattrs;
}
/// Indicate whether extended permissions (like suid on Unix) are preserved
/// when unpacking this entry.
///
/// This flag is disabled by default and is currently only implemented on
/// Unix.
pub fn set_preserve_permissions(&mut self, preserve: bool) {
self.fields.preserve_permissions = preserve;
}
/// Indicate whether access time information is preserved when unpacking
/// this entry.
///
/// This flag is enabled by default.
pub fn set_preserve_mtime(&mut self, preserve: bool) {
self.fields.preserve_mtime = preserve;
}
}
impl<'a, R: Read> Read for Entry<'a, R> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
self.fields.read(into)
}
}
impl<'a> EntryFields<'a> {
pub fn from<R: Read>(entry: Entry<R>) -> EntryFields {
entry.fields
}
pub fn into_entry<R: Read>(self) -> Entry<'a, R> {
Entry {
fields: self,
_ignored: marker::PhantomData,
}
}
pub fn read_all(&mut self) -> io::Result<Vec<u8>> {
// Preallocate some data but don't let ourselves get too crazy now.
let cap = cmp::min(self.size, 128 * 1024);
let mut v = Vec::with_capacity(cap as usize);
self.read_to_end(&mut v).map(|_| v)
}
fn path(&self) -> io::Result<Cow<Path>> {
bytes2path(self.path_bytes())
}
fn path_bytes(&self) -> Cow<[u8]> {
match self.long_pathname {
Some(ref bytes) => {
if let Some(&0) = bytes.last() {
Cow::Borrowed(&bytes[..bytes.len() - 1])
} else {
Cow::Borrowed(bytes)
}
}
None => {
if let Some(ref pax) = self.pax_extensions {
let pax = PaxExtensions::new(pax)
.filter_map(|f| f.ok())
.find(|f| f.key_bytes() == b"path")
.map(|f| f.value_bytes());
if let Some(field) = pax {
return Cow::Borrowed(field);
}
}
self.header.path_bytes()
}
}
}
/// Gets the path in a "lossy" way, used for error reporting ONLY.
fn path_lossy(&self) -> String {
String::from_utf8_lossy(&self.path_bytes()).to_string()
}
fn link_name(&self) -> io::Result<Option<Cow<Path>>> {
match self.link_name_bytes() {
Some(bytes) => bytes2path(bytes).map(Some),
None => Ok(None),
}
}
fn link_name_bytes(&self) -> Option<Cow<[u8]>> {
match self.long_linkname {
Some(ref bytes) => {
if let Some(&0) = bytes.last() {
Some(Cow::Borrowed(&bytes[..bytes.len() - 1]))
} else {
Some(Cow::Borrowed(bytes))
}
}
None => {
if let Some(ref pax) = self.pax_extensions {
let pax = PaxExtensions::new(pax)
.filter_map(|f| f.ok())
.find(|f| f.key_bytes() == b"linkpath")
.map(|f| f.value_bytes());
if let Some(field) = pax {
return Some(Cow::Borrowed(field));
}
}
self.header.link_name_bytes()
}
}
}
fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions>> {
if self.pax_extensions.is_none() {
if !self.header.entry_type().is_pax_global_extensions()
&& !self.header.entry_type().is_pax_local_extensions()
{
return Ok(None);
}
self.pax_extensions = Some(self.read_all()?);
}
Ok(Some(PaxExtensions::new(
self.pax_extensions.as_ref().unwrap(),
)))
}
fn unpack_in(&mut self, dst: &Path) -> io::Result<bool> {
// Notes regarding bsdtar 2.8.3 / libarchive 2.8.3:
// * Leading '/'s are trimmed. For example, `///test` is treated as
// `test`.
// * If the filename contains '..', then the file is skipped when
// extracting the tarball.
// * '//' within a filename is effectively skipped. An error is
// logged, but otherwise the effect is as if any two or more
// adjacent '/'s within the filename were consolidated into one
// '/'.
//
// Most of this is handled by the `path` module of the standard
// library, but we specially handle a few cases here as well.
let mut file_dst = dst.to_path_buf();
{
let path = self.path().map_err(|e| {
TarError::new(
format!("invalid path in entry header: {}", self.path_lossy()),
e,
)
})?;
for part in path.components() {
match part {
// Leading '/' characters, root paths, and '.'
// components are just ignored and treated as "empty
// components"
Component::Prefix(..) | Component::RootDir | Component::CurDir => continue,
// If any part of the filename is '..', then skip over
// unpacking the file to prevent directory traversal
// security issues. See, e.g.: CVE-2001-1267,
// CVE-2002-0399, CVE-2005-1918, CVE-2007-4131
Component::ParentDir => return Ok(false),
Component::Normal(part) => file_dst.push(part),
}
}
}
// Skip cases where only slashes or '.' parts were seen, because
// this is effectively an empty filename.
if *dst == *file_dst {
return Ok(true);
}
// Skip entries without a parent (i.e. outside of FS root)
let parent = match file_dst.parent() {
Some(p) => p,
None => return Ok(false),
};
self.ensure_dir_created(&dst, parent)
.map_err(|e| TarError::new(format!("failed to create `{}`", parent.display()), e))?;
let canon_target = self.validate_inside_dst(&dst, parent)?;
self.unpack(Some(&canon_target), &file_dst)
.map_err(|e| TarError::new(format!("failed to unpack `{}`", file_dst.display()), e))?;
Ok(true)
}
/// Unpack as destination directory `dst`.
fn unpack_dir(&mut self, dst: &Path) -> io::Result<()> {
// If the directory already exists just let it slide
fs::create_dir(dst).or_else(|err| {
if err.kind() == ErrorKind::AlreadyExists {
let prev = fs::metadata(dst);
if prev.map(|m| m.is_dir()).unwrap_or(false) {
return Ok(());
}
}
Err(Error::new(
err.kind(),
format!("{} when creating dir {}", err, dst.display()),
))
})
}
/// Returns access to the header of this entry in the archive.
fn unpack(&mut self, target_base: Option<&Path>, dst: &Path) -> io::Result<Unpacked> {
fn set_perms_ownerships(
dst: &Path,
f: Option<&mut std::fs::File>,
header: &Header,
mask: u32,
perms: bool,
ownerships: bool,
) -> io::Result<()> {
// ownerships need to be set first to avoid stripping SUID bits in the permissions ...
if ownerships {
set_ownerships(dst, &f, header.uid()?, header.gid()?)?;
}
// ... then set permissions, SUID bits set here is kept
if let Ok(mode) = header.mode() {
set_perms(dst, f, mode, mask, perms)?;
}
Ok(())
}
fn get_mtime(header: &Header) -> Option<FileTime> {
header.mtime().ok().map(|mtime| {
// For some more information on this see the comments in
// `Header::fill_platform_from`, but the general idea is that
// we're trying to avoid 0-mtime files coming out of archives
// since some tools don't ingest them well. Perhaps one day
// when Cargo stops working with 0-mtime archives we can remove
// this.
let mtime = if mtime == 0 { 1 } else { mtime };
FileTime::from_unix_time(mtime as i64, 0)
})
}
let kind = self.header.entry_type();
if kind.is_dir() {
self.unpack_dir(dst)?;
set_perms_ownerships(
dst,
None,
&self.header,
self.mask,
self.preserve_permissions,
self.preserve_ownerships,
)?;
return Ok(Unpacked::__Nonexhaustive);
} else if kind.is_hard_link() || kind.is_symlink() {
let src = match self.link_name()? {
Some(name) => name,
None => {
return Err(other(&format!(
"hard link listed for {} but no link name found",
String::from_utf8_lossy(self.header.as_bytes())
)));
}
};
if src.iter().count() == 0 {
return Err(other(&format!(
"symlink destination for {} is empty",
String::from_utf8_lossy(self.header.as_bytes())
)));
}
if kind.is_hard_link() {
let link_src = match target_base {
// If we're unpacking within a directory then ensure that
// the destination of this hard link is both present and
// inside our own directory. This is needed because we want
// to make sure to not overwrite anything outside the root.
//
// Note that this logic is only needed for hard links
// currently. With symlinks the `validate_inside_dst` which
// happens before this method as part of `unpack_in` will
// use canonicalization to ensure this guarantee. For hard
// links though they're canonicalized to their existing path
// so we need to validate at this time.
Some(ref p) => {
let link_src = p.join(src);
self.validate_inside_dst(p, &link_src)?;
link_src
}
None => src.into_owned(),
};
fs::hard_link(&link_src, dst).map_err(|err| {
Error::new(
err.kind(),
format!(
"{} when hard linking {} to {}",
err,
link_src.display(),
dst.display()
),
)
})?;
} else {
symlink(&src, dst)
.or_else(|err_io| {
if err_io.kind() == io::ErrorKind::AlreadyExists && self.overwrite {
// remove dest and try once more
std::fs::remove_file(dst).and_then(|()| symlink(&src, dst))
} else {
Err(err_io)
}
})
.map_err(|err| {
Error::new(
err.kind(),
format!(
"{} when symlinking {} to {}",
err,
src.display(),
dst.display()
),
)
})?;
if self.preserve_mtime {
if let Some(mtime) = get_mtime(&self.header) {
filetime::set_symlink_file_times(dst, mtime, mtime).map_err(|e| {
TarError::new(format!("failed to set mtime for `{}`", dst.display()), e)
})?;
}
}
}
return Ok(Unpacked::__Nonexhaustive);
#[cfg(target_arch = "wasm32")]
#[allow(unused_variables)]
fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Other, "Not implemented"))
}
#[cfg(windows)]
fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
::std::os::windows::fs::symlink_file(src, dst)
}
#[cfg(unix)]
fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
::std::os::unix::fs::symlink(src, dst)
}
} else if kind.is_pax_global_extensions()
|| kind.is_pax_local_extensions()
|| kind.is_gnu_longname()
|| kind.is_gnu_longlink()
{
return Ok(Unpacked::__Nonexhaustive);
};
// Old BSD-tar compatibility.
// Names that have a trailing slash should be treated as a directory.
// Only applies to old headers.
if self.header.as_ustar().is_none() && self.path_bytes().ends_with(b"/") {
self.unpack_dir(dst)?;
set_perms_ownerships(
dst,
None,
&self.header,
self.mask,
self.preserve_permissions,
self.preserve_ownerships,
)?;
return Ok(Unpacked::__Nonexhaustive);
}
// Note the lack of `else` clause above. According to the FreeBSD
// documentation:
//
// > A POSIX-compliant implementation must treat any unrecognized
// > typeflag value as a regular file.
//
// As a result if we don't recognize the kind we just write out the file
// as we would normally.
// Ensure we write a new file rather than overwriting in-place which
// is attackable; if an existing file is found unlink it.
fn open(dst: &Path) -> io::Result<std::fs::File> {
OpenOptions::new().write(true).create_new(true).open(dst)
}
let mut f = (|| -> io::Result<std::fs::File> {
let mut f = open(dst).or_else(|err| {
if err.kind() != ErrorKind::AlreadyExists {
Err(err)
} else if self.overwrite {
match fs::remove_file(dst) {
Ok(()) => open(dst),
Err(ref e) if e.kind() == io::ErrorKind::NotFound => open(dst),
Err(e) => Err(e),
}
} else {
Err(err)
}
})?;
for io in self.data.drain(..) {
match io {
EntryIo::Data(mut d) => {
let expected = d.limit();
if io::copy(&mut d, &mut f)? != expected {
return Err(other("failed to write entire file"));
}
}
EntryIo::Pad(d) => {
// TODO: checked cast to i64
let to = SeekFrom::Current(d.limit() as i64);
let size = f.seek(to)?;
f.set_len(size)?;
}
}
}
Ok(f)
})()
.map_err(|e| {
let header = self.header.path_bytes();
TarError::new(
format!(
"failed to unpack `{}` into `{}`",
String::from_utf8_lossy(&header),
dst.display()
),
e,
)
})?;
if self.preserve_mtime {
if let Some(mtime) = get_mtime(&self.header) {
filetime::set_file_handle_times(&f, Some(mtime), Some(mtime)).map_err(|e| {
TarError::new(format!("failed to set mtime for `{}`", dst.display()), e)
})?;
}
}
set_perms_ownerships(
dst,
Some(&mut f),
&self.header,
self.mask,
self.preserve_permissions,
self.preserve_ownerships,
)?;
if self.unpack_xattrs {
set_xattrs(self, dst)?;
}
return Ok(Unpacked::File(f));
fn set_ownerships(
dst: &Path,
f: &Option<&mut std::fs::File>,
uid: u64,
gid: u64,
) -> Result<(), TarError> {
_set_ownerships(dst, f, uid, gid).map_err(|e| {
TarError::new(
format!(
"failed to set ownerships to uid={:?}, gid={:?} \
for `{}`",
uid,
gid,
dst.display()
),
e,
)
})
}
#[cfg(unix)]
fn _set_ownerships(
dst: &Path,
f: &Option<&mut std::fs::File>,
uid: u64,
gid: u64,
) -> io::Result<()> {
use std::convert::TryInto;
use std::os::unix::prelude::*;
let uid: libc::uid_t = uid.try_into().map_err(|_| {
io::Error::new(io::ErrorKind::Other, format!("UID {} is too large!", uid))
})?;
let gid: libc::gid_t = gid.try_into().map_err(|_| {
io::Error::new(io::ErrorKind::Other, format!("GID {} is too large!", gid))
})?;
match f {
Some(f) => unsafe {
let fd = f.as_raw_fd();
if libc::fchown(fd, uid, gid) != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
},
None => unsafe {
let path = std::ffi::CString::new(dst.as_os_str().as_bytes()).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("path contains null character: {:?}", e),
)
})?;
if libc::lchown(path.as_ptr(), uid, gid) != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
},
}
}
// Windows does not support posix numeric ownership IDs
#[cfg(any(windows, target_arch = "wasm32"))]
fn _set_ownerships(
_: &Path,
_: &Option<&mut std::fs::File>,
_: u64,
_: u64,
) -> io::Result<()> {
Ok(())
}
fn set_perms(
dst: &Path,
f: Option<&mut std::fs::File>,
mode: u32,
mask: u32,
preserve: bool,
) -> Result<(), TarError> {
_set_perms(dst, f, mode, mask, preserve).map_err(|e| {
TarError::new(
format!(
"failed to set permissions to {:o} \
for `{}`",
mode,
dst.display()
),
e,
)
})
}
#[cfg(unix)]
fn _set_perms(
dst: &Path,
f: Option<&mut std::fs::File>,
mode: u32,
mask: u32,
preserve: bool,
) -> io::Result<()> {
use std::os::unix::prelude::*;
let mode = if preserve { mode } else { mode & 0o777 };
let mode = mode & !mask;
let perm = fs::Permissions::from_mode(mode as _);
match f {
Some(f) => f.set_permissions(perm),
None => fs::set_permissions(dst, perm),
}
}
#[cfg(windows)]
fn _set_perms(
dst: &Path,
f: Option<&mut std::fs::File>,
mode: u32,
_mask: u32,
_preserve: bool,
) -> io::Result<()> {
if mode & 0o200 == 0o200 {
return Ok(());
}
match f {
Some(f) => {
let mut perm = f.metadata()?.permissions();
perm.set_readonly(true);
f.set_permissions(perm)
}
None => {
let mut perm = fs::metadata(dst)?.permissions();
perm.set_readonly(true);
fs::set_permissions(dst, perm)
}
}
}
#[cfg(target_arch = "wasm32")]
#[allow(unused_variables)]
fn _set_perms(
dst: &Path,
f: Option<&mut std::fs::File>,
mode: u32,
mask: u32,
_preserve: bool,
) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Other, "Not implemented"))
}
#[cfg(all(unix, feature = "xattr"))]
fn set_xattrs(me: &mut EntryFields, dst: &Path) -> io::Result<()> {
use std::ffi::OsStr;
use std::os::unix::prelude::*;
let exts = match me.pax_extensions() {
Ok(Some(e)) => e,
_ => return Ok(()),
};
let exts = exts
.filter_map(|e| e.ok())
.filter_map(|e| {
let key = e.key_bytes();
let prefix = b"SCHILY.xattr.";
if key.starts_with(prefix) {
Some((&key[prefix.len()..], e))
} else {
None
}
})
.map(|(key, e)| (OsStr::from_bytes(key), e.value_bytes()));
for (key, value) in exts {
xattr::set(dst, key, value).map_err(|e| {
TarError::new(
format!(
"failed to set extended \
attributes to {}. \
Xattrs: key={:?}, value={:?}.",
dst.display(),
key,
String::from_utf8_lossy(value)
),
e,
)
})?;
}
Ok(())
}
// Windows does not completely support posix xattrs
// https://en.wikipedia.org/wiki/Extended_file_attributes#Windows_NT
#[cfg(any(windows, not(feature = "xattr"), target_arch = "wasm32"))]
fn set_xattrs(_: &mut EntryFields, _: &Path) -> io::Result<()> {
Ok(())
}
}
fn ensure_dir_created(&self, dst: &Path, dir: &Path) -> io::Result<()> {
let mut ancestor = dir;
let mut dirs_to_create = Vec::new();
while ancestor.symlink_metadata().is_err() {
dirs_to_create.push(ancestor);
if let Some(parent) = ancestor.parent() {
ancestor = parent;
} else {
break;
}
}
for ancestor in dirs_to_create.into_iter().rev() {
if let Some(parent) = ancestor.parent() {
self.validate_inside_dst(dst, parent)?;
}
fs::create_dir_all(ancestor)?;
}
Ok(())
}
fn validate_inside_dst(&self, dst: &Path, file_dst: &Path) -> io::Result<PathBuf> {
// Abort if target (canonical) parent is outside of `dst`
let canon_parent = file_dst.canonicalize().map_err(|err| {
Error::new(
err.kind(),
format!("{} while canonicalizing {}", err, file_dst.display()),
)
})?;
let canon_target = dst.canonicalize().map_err(|err| {
Error::new(
err.kind(),
format!("{} while canonicalizing {}", err, dst.display()),
)
})?;
if !canon_parent.starts_with(&canon_target) {
let err = TarError::new(
format!(
"trying to unpack outside of destination path: {}",
canon_target.display()
),
// TODO: use ErrorKind::InvalidInput here? (minor breaking change)
Error::new(ErrorKind::Other, "Invalid argument"),
);
return Err(err.into());
}
Ok(canon_target)
}
}
impl<'a> Read for EntryFields<'a> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
loop {
match self.data.get_mut(0).map(|io| io.read(into)) {
Some(Ok(0)) => {
self.data.remove(0);
}
Some(r) => return r,
None => return Ok(0),
}
}
}
}
impl<'a> Read for EntryIo<'a> {
fn read(&mut self, into: &mut [u8]) -> io::Result<usize> {
match *self {
EntryIo::Pad(ref mut io) => io.read(into),
EntryIo::Data(ref mut io) => io.read(into),
}
}
}
|
// Authors: Matthew Bartlett & Arron Harman
// Major: (Software Development & Math) & (Software Development)
// Creation Date: October 27, 2020
// Due Date: November 24, 2020
// Course: CSC328
// Professor Name: Dr. Frye
// Assignment: Chat Server
// Filename: main.rs
// Purpose: Create and document functions to be used to create a chat server
use std::str::from_utf8;
use std::string::ToString;
use std::net::*;
use std::sync::*;
use std::io::Write;
use std::time::Duration;
use chrono::Utc;
use std::path::Path;
extern crate libc;
use libc::*;
use std::os::unix::io::AsRawFd;
/// The Max size of message
const MESSAGE_MAX_SIZE : usize = 1024;
/// The Max size of a name
const NAME_MAX_SIZE : usize = 32;
/// The structure to describe Messages passed from client to server
#[derive(Clone,PartialEq,Eq)]
pub enum Message {
HELLO,
NICK(String),
BYE,
READY,
RETRY,
CHAT(String),
}
/// Implements the to_string method for Message, ONLY TO BE USED FOR LOGGING.
impl ToString for Message {
fn to_string(&self) -> String {
match self {
Message::HELLO => "HELLO".to_string(),
Message::NICK(n) => format!("NICK{}",n),
Message::BYE => "BYE".to_string(),
Message::READY => "READY".to_string(),
Message::RETRY => "RETRY".to_string(),
Message::CHAT(m) => format!("CHAT{}",m),
}
}
}
// Library Bindings
/// This is a reproduction of the C-struct messageInfo in the C library
#[derive(Clone)]
#[repr(C)]
struct messageInfo {
protocol : c_int,
name : [c_uchar; NAME_MAX_SIZE],
msg : [c_uchar; MESSAGE_MAX_SIZE],
msg_size : c_int,
name_size : c_int,
}
/// This is initial state for messageInfo types because we have to initialize them before we pass them
const MESSAGEINFOINIT : messageInfo =
messageInfo{
protocol : 0,
name : [0;NAME_MAX_SIZE],
msg : [0;MESSAGE_MAX_SIZE],
msg_size : 0,
name_size : 0,
};
// here's the actual bindings to library functions
#[link(name = "cs", kind = "static")]
extern "C" {
/// Send a correctly formated message.
/// socfd: The file descriptor for the socket.
/// proto: The number of the protocol
/// 0 -> HELLO
/// 1 -> BYE
/// 2 -> NICK
/// 3 -> READY
/// 4 -> RETRY
/// 5 -> CHAT
/// name: C-string that is the name of the person sending a CHAT or the Name portion of a
/// NICK message otherwise 0.
/// message: C-string that is the message of a CHAT otherwise 0.
/// nameSizeL: NAME_MAX_SIZE for CHAT messages otherwise 0.
/// messageSize: MESSAGE_MAX_SIZE for CHAT messages NAME_MAX_SIZE for NICK messages otherwise
/// 0.
/// returns -1 if there was an error, otherwise the number of bytes sent.
fn sendMessage(
sockfd : c_int,
proto : c_int,
name : *mut c_char,
message : *mut c_char,
nameSize : c_int,
messageSize : c_int) -> c_int;
/// Receives a correctly formated message.
/// socfd: The file descriptor for the socket.
/// buf: The buffer for the message.
/// size: The max size of the buffer.
/// returns -1 if there was an error, otherwise the number of bytes read.
fn receiveMessage(
sockfd : c_int,
buf : *mut c_void,
size: c_int) -> c_int;
/// Parses a received message.
/// msgStruct: The message struct to be filled with info from the buffer.
/// buffer: The received message buffer.
/// returns -1 if there was an error, otherwise 0
fn getInfo(
msgStruct : *mut messageInfo,
buffer : *mut c_char) -> c_int;
}
// and now functions to make them easier to use
/// Sends a message to a client
/// stream: The stream to send a message to
/// msg: The message to send
/// returns () on success and None on failure
pub fn send_message(stream : &mut TcpStream, msg : Message, nickname : Option<String>) -> Option<()> {
let proto : c_int;
let mut string : Option<String> = None;
let mut name = false;
match msg {
Message::HELLO => proto = 0,
Message::BYE => proto = 1,
Message::NICK(s) => {proto = 2;
string = Some(s);
name = true;}
Message::READY => proto = 3,
Message::RETRY => proto = 4,
Message::CHAT(s) => {proto = 5;
string = Some(s);}
}
let mut message = ['\0' as i8; MESSAGE_MAX_SIZE];
fn min(a : usize, b : usize) -> usize {
if a < b
{a}
else
{b}
};
match string.clone() {
Some(s) => {for i in 0..min(MESSAGE_MAX_SIZE,s.as_bytes().len()) {
message[i] = s.as_bytes()[i] as i8;
};}
None => (),
}
// fn sendMessage(sockfd : c_int,proto : c_int,name : *mut c_char,message : *mut c_char,nameSize : c_int,messageSize : c_int) -> c_int;
unsafe {
if name {// Sending a nickname
if sendMessage(stream.as_raw_fd(), proto, &mut message[0], 0 as *mut i8, NAME_MAX_SIZE as i32, 0) == -1 {
None
} else {
Some(())
}
} else {// Sending anything other than a nickname
match nickname {
Some(s) => {let ref mut nick_ar : [i8; NAME_MAX_SIZE] = ['\0' as i8; NAME_MAX_SIZE];
for x in 0..s.len() {
nick_ar[x] = s.as_bytes()[x] as i8;
}
if sendMessage(stream.as_raw_fd(), proto,
&mut nick_ar[0], &mut message[0],
NAME_MAX_SIZE as i32, MESSAGE_MAX_SIZE as i32) == -1 {
None
} else {
Some(())
}}
None => {if sendMessage(stream.as_raw_fd(), proto,
0 as *mut i8, &mut message[0],
0, MESSAGE_MAX_SIZE as i32) == -1 {
None
} else {
Some(())
}}
}
}
}
}
/// receves a message
/// stream: the stream to receve from
/// returns the message reveved
pub fn rcv_message(stream : &mut TcpStream) -> Option<Message> {
unsafe {
// BUFF_SIZE store the max size of the buffer 3 32 bit integers and arrays of NAME_MAX_SIZE
// and MESSAGE_MAX_SIZE
const BUFF_SIZE : usize = 3*4+NAME_MAX_SIZE+MESSAGE_MAX_SIZE;
let buf = &mut ['\0' as u8;BUFF_SIZE] as *mut _ as *mut c_void;
let ref mut msg_info : messageInfo = MESSAGEINFOINIT.clone();
let bytes_read = receiveMessage(stream.as_raw_fd(), buf , BUFF_SIZE as c_int);
if bytes_read == -1 {
None
} else {
if getInfo(msg_info, buf.cast::<c_char>()) == -1 {return None}
match msg_info.protocol {
0 => Some(Message::HELLO),
1 => Some(Message::BYE),
2 => Some(Message::NICK(from_utf8(&msg_info.name).ok()?.trim_end().to_string())),
3 => Some(Message::READY),
4 => Some(Message::RETRY),
5 => Some(Message::CHAT(from_utf8(&msg_info.msg).ok()?.trim_end().to_string())),
_ => None,
}
}
}
}
/// Removes all dead connections from a vector
/// conns : The list of active connections
/// Returns a vector of all active connections
pub fn remove_dead_connections(conns : &Vec<(TcpStream,String)>) -> Vec<TcpStream> {
conns.into_iter().filter_map( |(x,_)| {
match x.take_error() {
Err(_) => None,
Ok(Some(_)) => None,
Ok(None) => Some(x.try_clone().ok()?),
}
}).collect()
}
/// Dissconnects from all active connections, waits 5 seconds and then ends
/// conns : The active connections
pub fn disconnect_all_connections(conns : &Vec<(TcpStream,String)>) {
const TIMEOUT_TIMER : Duration = Duration::from_secs(5);
let conns : Vec<(TcpStream,String)> = conns.iter().filter_map( |(x,y)| {
match x.try_clone().ok() {
Some(x) => Some((x,y.clone())),
None => None,
}
}).collect();
println!("\nDisconnecting from all connections and closeing");
for (conn, name) in conns {
let mut conn = Box::new(conn);
std::thread::spawn( move || {
log(&format!("disconnecting from {}@{:?}",name,conn.peer_addr()));
send_message(&mut conn,Message::BYE,None);
conn.shutdown(Shutdown::Both).unwrap_or(());
});
};
std::thread::sleep(TIMEOUT_TIMER);
}
/// Removes a connection from a list of connections
/// conns : The active connections
/// to_remove : The connection to remove
pub fn remove_connection(conns : &mut Vec<(TcpStream,String)>, to_remove : &TcpStream) {
let peer = to_remove.peer_addr().unwrap();
remove_dead_connections(conns);
*conns = conns
.into_iter()
.filter(|(x,_)| {
match x.peer_addr().ok() {
Some(x) => x != peer,
None => false,
}})
.map(|(x,y)| (x.try_clone().unwrap(),y.clone())).collect::<Vec<_>>();
}
/// Sends a message from one user to all other users
/// conns : The current open connections.
/// me : The address of the user sending the message.
/// nick : The nickname of the user sending the message.
/// message : The message being sent.
pub fn blast_out(conns : &Vec<(TcpStream,String)>, me : &SocketAddr, nick : &String, message : &String) -> () {
for (connection,name) in conns {
let addr = connection.peer_addr().unwrap_or(*me);
if addr != *me && *name != "".to_string() {
log(&format!("{}@{}:`{}` -> {}@{}",nick,me,message,name,addr));
let message = Message::CHAT(message.clone());
send_message(&mut connection.try_clone().unwrap(), message, Some(nick.clone()));
}
};
}
/// Logs the input to a file and the screen, adds a time stamp
/// log_message : the string to log
pub fn log(log_message : &String) {
let log_message = format!("{}\t{}\n",Utc::now(),log_message);
let log_file_name : &Path = Path::new("logfile.log");
print!("{}",log_message);
match std::fs::OpenOptions::new()
.append(true)
.open(log_file_name) {
Ok(mut x) => {
match x.write(log_message.as_bytes()) {
Ok(_) => (),
Err(x) => println!("Could not write to log file because: {:?}",x),
}
}
Err(x) => println!("Could not open log file because: {:?}",x),
}
}
/// Gets a valid nickname from the user
/// and adds the nickname to the list of nicknames in use
/// stream : the tcpstream connected to the user
/// nicknames : the global list of all nicknames
/// returns : a valid nickname or None if the user wants to end the connection or an error occurred
pub fn get_nickname(stream : &mut TcpStream, conns : &Arc<Mutex<Vec<(TcpStream,String)>>>) -> Option<String> {
fn nicknames(conns : &Arc<Mutex<Vec<(TcpStream,String)>>>) -> Option<Vec<String>> {
Some((*conns.lock().ok()?).iter().map( |(_,y)| y.clone()).collect())
};
while match rcv_message(stream) {
Some(Message::NICK(n)) => {
let n = n.trim().to_string().replace('\r',"");
// if the nickname is not taken set add it to the list of nicknames in
// use and then return the nick
if !nicknames(conns)?.contains(&n.clone()) {
conns.lock().unwrap().push((stream.try_clone().unwrap(),n.clone()));
send_message(stream, Message::READY, None);
return Some(n);
} else {
// else ask the client to retry
send_message(stream, Message::RETRY, None);
true
}
}
Some(Message::BYE) => return None,
None => return None,
_ => true,
} {
};
None
}
|
use crate::error::{GameError, GameResult};
use crate::math::Delta;
use crate::event::{Event, KeyAction};
use crate::filesystem::{Filesystem, FilesystemConfig};
use crate::window::{Window, WindowConfig, LogicalPosition, LogicalSize};
use crate::graphics::{Graphics, GraphicsConfig};
use crate::timer::{Timer, TimerConfig};
use crate::keyboard::{Keyboard, KeyboardConfig};
use crate::mouse::{Mouse, MouseConfig};
use crate::touch::{Touch, TouchConfig};
use crate::touchpad::{Touchpad, TouchpadConfig};
use crate::gamepad::{Gamepad, GamepadConfig};
use crate::audio::{Audio, AudioConfig};
use crate::game::Game;
use winit::event_loop::{EventLoop, ControlFlow};
use winit::event::{StartCause, WindowEvent, MouseScrollDelta};
use winit::platform::desktop::EventLoopExtDesktop;
#[derive(Debug)]
enum State {
Ready,
Running,
Finished,
Broken(Option<GameError>),
}
pub struct Engine {
event_loop: Option<EventLoop<()>>,
filesystem: Filesystem,
window: Window,
graphics: Graphics,
timer: Timer,
keyboard: Keyboard,
mouse: Mouse,
touch: Touch,
touchpad: Touchpad,
gamepad: Gamepad,
audio: Audio,
state: State,
}
impl Engine {
pub fn filesystem(&mut self) -> &mut Filesystem {
&mut self.filesystem
}
pub fn window(&mut self) -> &mut Window {
&mut self.window
}
pub fn graphics(&mut self) -> &mut Graphics {
&mut self.graphics
}
pub fn timer(&mut self) -> &mut Timer {
&mut self.timer
}
pub fn keyboard(&mut self) -> &mut Keyboard {
&mut self.keyboard
}
pub fn mouse(&mut self) -> &mut Mouse {
&mut self.mouse
}
pub fn touch(&mut self) -> &mut Touch {
&mut self.touch
}
pub fn touchpad(&mut self) -> &mut Touchpad {
&mut self.touchpad
}
pub fn gamepad(&mut self) -> &mut Gamepad {
&mut self.gamepad
}
pub fn audio(&mut self) -> &mut Audio {
&mut self.audio
}
pub fn quit(&mut self) {
match &self.state {
State::Finished | State::Broken(_) => (),
_ => self.state = State::Finished,
}
}
pub fn exit(&mut self, error: GameError) {
match &self.state {
State::Finished | State::Broken(_) => (),
_ => self.state = State::Broken(Some(error)),
}
}
fn handle_event(&mut self, event: winit::event::Event<()>, control_flow: &mut ControlFlow, game: &mut impl Game) -> GameResult {
match event {
winit::event::Event::NewEvents(start_cause) => {
match start_cause {
StartCause::Init => self.timer.reset_tick(),
_ => (),
}
}
winit::event::Event::WindowEvent { window_id, event } => {
if window_id == self.window.window().id() {
match event {
WindowEvent::CloseRequested => {
if !game.event(self, Event::WindowClose)? {
*control_flow = ControlFlow::Exit;
self.quit();
}
}
WindowEvent::Resized(physical_size) => {
let scale_factor = self.window.window().scale_factor();
let logical_size = physical_size.to_logical(scale_factor);
self.graphics.resize(physical_size, scale_factor);
game.event(self, Event::WindowResize(LogicalSize::new(logical_size.width, logical_size.height)))?;
}
WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size } => {
let logical_size = new_inner_size.to_logical(scale_factor);
self.graphics.resize(*new_inner_size, scale_factor);
game.event(self, Event::WindowResize(LogicalSize::new(logical_size.width, logical_size.height)))?;
}
WindowEvent::Moved(physical_position) => {
let scale_factor = self.window.window().scale_factor();
let logical_position = physical_position.to_logical(scale_factor);
game.event(self, Event::WindowMove(LogicalPosition::new(logical_position.x, logical_position.y)))?;
}
WindowEvent::Focused(focused) => {
self.window.handle_focus_change_event(focused);
game.event(self, Event::WindowFocusChange(focused))?;
}
WindowEvent::ReceivedCharacter(char) => {
game.event(self, Event::ReceiveChar(char))?;
}
WindowEvent::KeyboardInput { input, .. } => {
let key = (input.virtual_keycode, input.scancode).into();
let action = input.state.into();
let repeated = self.keyboard.handle_input_event(key, action);
game.event(self, Event::KeyboardInput { key, action, repeated })?;
}
WindowEvent::ModifiersChanged(state) => {
let state = state.into();
self.keyboard.handle_modifiers_state_change(state);
game.event(self, Event::ModifiersChange(state))?;
}
WindowEvent::CursorMoved { position, .. } => {
let scale_factor = self.window.window().scale_factor();
let logical_position = position.to_logical(scale_factor);
let position = LogicalPosition::new(logical_position.x, logical_position.y);
self.mouse.handle_move_event(position);
game.event(self, Event::MouseMove(position))?;
}
WindowEvent::CursorEntered { .. } => {
self.mouse.handle_enter_window_event();
game.event(self, Event::MouseEnterWindow)?;
}
WindowEvent::CursorLeft { .. } => {
self.mouse.handle_leave_window_event();
game.event(self, Event::MouseLeaveWindow)?;
}
WindowEvent::MouseWheel { delta, phase, .. } => {
match delta {
MouseScrollDelta::LineDelta(delta_x, delta_y) => {
let delta = Delta::new(delta_x, delta_y);
self.mouse.handle_wheel_scroll_event(delta);
game.event(self, Event::MouseWheelScroll(delta))?;
}
MouseScrollDelta::PixelDelta(logical_position) => {
let delta = Delta::new(logical_position.x as f32, logical_position.y as f32);
self.touchpad.handle_scroll_event(delta);
game.event(self, Event::TouchpadScroll { delta, phase: phase.into() })?;
}
}
}
WindowEvent::MouseInput { state, button, .. } => {
let button = button.into();
let action = state.into();
self.mouse.handle_input_event(button, action);
game.event(self, Event::MouseInput { button, action })?;
}
WindowEvent::Touch(touch) => {
let id = touch.id;
let phase = touch.phase.into();
let position = {
let scale_factor = self.window.window().scale_factor();
let logical_position = touch.location.to_logical(scale_factor);
LogicalPosition::new(logical_position.x, logical_position.y)
};
self.touch.handle_event(id, phase, position);
game.event(self, Event::Touch { id, phase, position })?;
}
WindowEvent::TouchpadPressure { pressure, stage, .. } => {
self.touchpad.handle_press_event(pressure, stage);
game.event(self, Event::TouchpadPress { pressure, click_stage: stage })?;
}
WindowEvent::Destroyed => self.quit(),
_ => (),
}
}
}
winit::event::Event::Suspended => {
game.event(self, Event::AppSuspend)?;
self.audio.suspend();
}
winit::event::Event::Resumed => {
self.audio.resume();
game.event(self, Event::AppResume)?;
}
winit::event::Event::MainEventsCleared => {
let events = self.gamepad.pump_events();
for event in events {
let id = event.id;
let event = event.event;
match event {
gilrs::EventType::Connected => {
self.gamepad.handle_connect_event(id);
game.event(self, Event::GamepadConnect(id))?;
}
gilrs::EventType::Disconnected => {
self.gamepad.handle_disconnect_event(id);
game.event(self, Event::GamepadDisconnect(id))?;
}
gilrs::EventType::ButtonPressed(button, _) => {
let button = button.into();
let action = KeyAction::Down;
self.gamepad.handle_button_input_event(id, button, action);
game.event(self, Event::GamepadButtonInput { id, button, action })?;
}
gilrs::EventType::ButtonReleased(button, _) => {
let button = button.into();
let action = KeyAction::Up;
self.gamepad.handle_button_input_event(id, button, action);
game.event(self, Event::GamepadButtonInput { id, button, action })?;
}
gilrs::EventType::ButtonChanged(button, value, _) => {
let button = button.into();
self.gamepad.handle_button_change_event(id, button, value);
game.event(self, Event::GamepadButtonChange { id, button, value })?;
}
gilrs::EventType::AxisChanged(axis, value, _) => {
let axis = axis.into();
self.gamepad.handle_axis_change_event(id, axis, value);
game.event(self, Event::GamepadAxisChange { id, axis, value })?;
}
_ => (),
}
}
self.window.window().request_redraw();
}
winit::event::Event::RedrawRequested(window_id) => {
if window_id == self.window.window().id() {
if self.timer.tick_and_check() {
game.update(self)?;
game.render(self)?;
self.graphics.present()?;
self.keyboard.clear_states();
self.mouse.clear_states();
self.touch.clear_states();
self.touchpad.clear_states();
self.gamepad.clear_states();
}
}
}
winit::event::Event::LoopDestroyed => {
self.quit();
self.graphics.clean();
}
_ => (),
}
Ok(())
}
pub fn run(&mut self, game: &mut impl Game) -> GameResult {
match &self.state {
State::Ready => self.state = State::Running,
_ => return Err(GameError::StateError(format!("engine can not be run on state `{:?}`", self.state).into())),
}
let mut event_loop = self.event_loop.take()
.ok_or_else(|| GameError::RuntimeError("no event_loop instance".into()))?;
event_loop.run_return(|event, _, control_flow| {
match &self.state {
State::Finished | State::Broken(_) => *control_flow = ControlFlow::Exit,
State::Running => {
if let Err(error) = self.handle_event(event, control_flow, game) {
self.exit(error);
}
}
_ => self.exit(GameError::StateError(format!("engine state `{:?}` incorrect on handle event", self.state).into())),
}
});
self.event_loop = Some(event_loop);
match &mut self.state {
State::Finished => Ok(()),
State::Broken(error) => {
let error = error.take()
.unwrap_or_else(|| GameError::RuntimeError("no engine broken error instance".into()));
Err(error)
}
_ => Err(GameError::StateError(format!("engine state `{:?}` incorrect on event loop returned", self.state).into())),
}
}
pub fn run_with<G, F>(&mut self, init: F) -> GameResult
where
G: Game,
F: FnOnce(&mut Self) -> GameResult<G>,
{
let mut game = init(self)?;
self.run(&mut game)
}
}
#[derive(Debug, Clone)]
pub struct EngineBuilder {
filesystem_config: Option<FilesystemConfig>,
window_config: Option<WindowConfig>,
graphics_config: Option<GraphicsConfig>,
timer_config: Option<TimerConfig>,
keyboard_config: Option<KeyboardConfig>,
mouse_config: Option<MouseConfig>,
touch_config: Option<TouchConfig>,
touchpad_config: Option<TouchpadConfig>,
gamepad_config: Option<GamepadConfig>,
audio_config: Option<AudioConfig>,
}
impl EngineBuilder {
pub fn new() -> Self {
Self {
filesystem_config: None,
window_config: None,
graphics_config: None,
timer_config: None,
keyboard_config: None,
mouse_config: None,
touch_config: None,
touchpad_config: None,
gamepad_config: None,
audio_config: None,
}
}
pub fn filesystem_config(mut self, filesystem_config: FilesystemConfig) -> Self {
self.filesystem_config = Some(filesystem_config);
self
}
pub fn window_config(mut self, window_config: WindowConfig) -> Self {
self.window_config = Some(window_config);
self
}
pub fn graphics_config(mut self, graphics_config: GraphicsConfig) -> Self {
self.graphics_config = Some(graphics_config);
self
}
pub fn timer_config(mut self, timer_config: TimerConfig) -> Self {
self.timer_config = Some(timer_config);
self
}
pub fn keyboard_config(mut self, keyboard_config: KeyboardConfig) -> Self {
self.keyboard_config = Some(keyboard_config);
self
}
pub fn mouse_config(mut self, mouse_config: MouseConfig) -> Self {
self.mouse_config = Some(mouse_config);
self
}
pub fn touch_config(mut self, touch_config: TouchConfig) -> Self {
self.touch_config = Some(touch_config);
self
}
pub fn touchpad_config(mut self, touchpad_config: TouchpadConfig) -> Self {
self.touchpad_config = Some(touchpad_config);
self
}
pub fn gamepad_config(mut self, gamepad_config: GamepadConfig) -> Self {
self.gamepad_config = Some(gamepad_config);
self
}
pub fn audio_config(mut self, audio_config: AudioConfig) -> Self {
self.audio_config = Some(audio_config);
self
}
pub fn build(self) -> GameResult<Engine> {
let filesystem_config = self.filesystem_config.unwrap_or_else(|| FilesystemConfig::new());
let window_config = self.window_config.unwrap_or_else(|| WindowConfig::new());
let graphics_config = self.graphics_config.unwrap_or_else(|| GraphicsConfig::new());
let timer_config = self.timer_config.unwrap_or_else(|| TimerConfig::new());
let keyboard_config = self.keyboard_config.unwrap_or_else(|| KeyboardConfig::new());
let mouse_config = self.mouse_config.unwrap_or_else(|| MouseConfig::new());
let touch_config = self.touch_config.unwrap_or_else(|| TouchConfig::new());
let touchpad_config = self.touchpad_config.unwrap_or_else(|| TouchpadConfig::new());
let gamepad_config = self.gamepad_config.unwrap_or_else(|| GamepadConfig::new());
let audio_config = self.audio_config.unwrap_or_else(|| AudioConfig::new());
let event_loop = EventLoop::new();
let filesystem = Filesystem::new(filesystem_config)?;
let window = Window::new(window_config, &event_loop, &filesystem)?;
let graphics = Graphics::new(graphics_config, window.context_wrapper().clone())?;
let timer = Timer::new(timer_config)?;
let keyboard = Keyboard::new(keyboard_config)?;
let mouse = Mouse::new(mouse_config, window.context_wrapper().clone())?;
let touch = Touch::new(touch_config)?;
let touchpad = Touchpad::new(touchpad_config)?;
let gamepad = Gamepad::new(gamepad_config)?;
let audio = Audio::new(audio_config)?;
Ok(Engine {
event_loop: Some(event_loop),
filesystem,
window,
graphics,
timer,
keyboard,
mouse,
touch,
touchpad,
gamepad,
audio,
state: State::Ready,
})
}
}
|
use add_one;
use rand;
fn main() {
let num = 10;
println!("Hello, world! {} plus one is {}", num, add_one::add_one(num));
let thre = rand::thread_rng();
println!("Next random : {}", add_one::ret_rand(thre));
}
|
use serde::Serializer;
use serde::ser::Serialize;
/// тестовая форма
#[derive(FromForm)]
pub struct MyForm {
pub field: String,
}
impl MyForm {
pub fn new() -> MyForm {
MyForm { field: String::new() }
}
}
impl Serialize for MyForm {
/// хитрим и рендерим форму для шаблона
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
serializer.serialize_str(self.field.as_str()) //todo + raw_template
//https://tera.netlify.app/docs/#loading-templates-from-strings
}
}
|
use std::collections::HashMap;
use std::fs;
use std::time::Instant;
use pcre2::bytes::Regex;
fn process_input(puzzle: Vec<&str>) -> (HashMap<&str, Vec<Vec<&str>>>, Vec<&str>) {
let mut rules_map: HashMap<&str, Vec<Vec<&str>>> = HashMap::new();
assert!(!puzzle.is_empty());
let mut it = puzzle.iter();
loop {
let cur = it.next().unwrap();
if cur.is_empty() {
break;
}
let mut it2 = cur.split(": ");
let index = it2.next().to_owned().unwrap();
let rule = it2.next().to_owned().unwrap();
assert!(it2.next().is_none());
let mut v: Vec<Vec<&str>> = vec![];
let mut it3 = rule.split(" | ");
while let Some(cur) = it3.next().to_owned() {
v.push(cur.split(" ").collect());
}
rules_map.insert(index, v);
}
let mut texts = vec![];
while let Some(cur) = it.next() {
texts.push(cur.clone());
}
(rules_map, texts)
}
fn make_regex(rule: &str, rules_map: &HashMap<&str, Vec<Vec<&str>>>, part2: bool) -> String {
if part2 {
if rule == "8" {
return "(".to_owned() + &make_regex("42", rules_map, part2) + "+" + ")";
}
if rule == "11" {
return "(?P<token>".to_owned() + &make_regex("42", rules_map, part2) + "(?&token)*" + &make_regex("31", rules_map, part2) + ")";
}
}
if !rules_map.contains_key(rule) {
return rule.trim_matches('"').parse().unwrap();
}
let mut acc = vec![];
for rules in rules_map.get(rule).unwrap() {
let mut x = String::from("(");
for rule in rules {
x += &*make_regex(rule, rules_map, part2);
}
x += ")";
acc.push(x)
}
return "(".to_owned() + &acc.join("|") + ")";
}
fn part1(puzzle: Vec<String>) -> usize {
let (seq, texts) = process_input(puzzle.iter().map(|x| &**x).collect::<Vec<&str>>());
let r = Regex::new(&*("^".to_owned() + &make_regex("0", &seq, false) + "$")).unwrap();
let mut s = 0;
for text in texts {
s += if r.is_match(text.as_ref()).unwrap() { 1 } else { 0 }
}
s
}
fn part2(puzzle: Vec<String>) -> usize {
let (seq, texts) = process_input(puzzle.iter().map(|x| &**x).collect::<Vec<&str>>());
let r = Regex::new(&*("^".to_owned() + &make_regex("0", &seq, true) + "$")).unwrap();
let mut s = 0;
for text in texts {
s += if r.is_match(text.as_ref()).unwrap() { 1 } else { 0 }
}
s
}
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 {}ms", now.elapsed().as_millis());
println!("Running part2");
let now = Instant::now();
println!("Found {}", part2(puzzle.clone()));
println!("Took {}ms", now.elapsed().as_millis());
} |
#[derive(Debug)]
pub struct User{
pub name: String,
pub email: String,
pub age: u16,
pub user_type: UserType
}
impl User{
pub fn print_user(self){
println!("The name of the user is {}.\nHis email is: {}.\nHe is {} old.\nType of user: {:?}", self.name, self.email, self.age, self.user_type);
}
}
#[derive(Debug)]
pub enum UserType{
Guest,
Regular,
Admin
}
|
//! A slab-like, pre-allocated storage where the slab is divided into immovable
//! slots. Each allocated slot doubles the capacity of the slab.
//!
//! Converted from <https://github.com/carllerche/slab>, this slab however
//! contains a growable collection of fixed-size regions called slots.
//! This allows is to store immovable objects inside the slab, since growing the
//! collection doesn't require the existing slots to move.
//!
//! # Examples
//!
//! ```rust
//! use unicycle::pin_slab::PinSlab;
//!
//! let mut slab = PinSlab::new();
//!
//! assert!(!slab.remove(0));
//! let index = slab.insert(42);
//! assert!(slab.remove(index));
//! assert!(!slab.remove(index));
//! ```
use std::pin::Pin;
use pin_project::pin_project;
use crate::pin_vec::PinVec;
/// Pre-allocated storage for a uniform data type, with slots of immovable
/// memory regions.
///
/// ## `Sync` and `Send` Auto Traits
///
/// `PinSlab<T>` is `Sync` or `Send` if `T` is. Examples:
///
/// `Send` and `Sync`:
/// ```
/// # use unicycle::pin_slab::PinSlab;
/// fn assert_send<T: Send>(_: &T) {}
/// fn assert_sync<T: Sync>(_: &T) {}
///
/// let slab = PinSlab::<i32>::new();
/// assert_send(&slab);
/// assert_sync(&slab);
/// ```
///
/// `!Sync`:
/// ```compile_fail
/// # use unicycle::pin_slab::PinSlab;
/// # fn assert_sync<T: Sync>(_: &T) {}
///
/// let slab = PinSlab::<std::cell::Cell<i32>>::new();
/// assert_sync(&slab);
/// ```
///
/// `!Send`:
/// ```compile_fail
/// # use unicycle::pin_slab::PinSlab;
/// # fn assert_send<T: Send>(_: &T) {}
///
/// let slab = PinSlab::<std::rc::Rc<i32>>::new();
/// assert_send(&slab);
/// ```
pub struct PinSlab<T> {
entries: PinVec<Entry<T>>,
len: usize,
// Offset of the next available slot in the slab.
next: usize,
}
#[pin_project(project = EntryProject)]
enum Entry<T> {
// Each slot is pre-allocated with entries of `None`.
None,
// Removed entries are replaced with the vacant tomb stone, pointing to the
// next vacant entry.
Vacant(usize),
// An entry that is occupied with a value.
Occupied(#[pin] T),
}
impl<T> PinSlab<T> {
/// Construct a new, empty [PinSlab] with the default slot size.
///
/// # Examples
///
/// ```rust
/// use unicycle::pin_slab::PinSlab;
///
/// let mut slab = PinSlab::new();
///
/// assert!(!slab.remove(0));
/// let index = slab.insert(42);
/// assert!(slab.remove(index));
/// assert!(!slab.remove(index));
/// ```
pub fn new() -> Self {
Self {
entries: PinVec::new(),
len: 0,
next: 0,
}
}
/// Get the length of the slab.
///
/// # Examples
///
/// ```rust
/// use unicycle::pin_slab::PinSlab;
///
/// let mut slab = PinSlab::new();
/// assert_eq!(0, slab.len());
/// assert_eq!(0, slab.insert(42));
/// assert_eq!(1, slab.len());
/// ```
pub fn len(&self) -> usize {
self.len
}
/// Test if the pin slab is empty.
///
/// # Examples
///
/// ```rust
/// use unicycle::pin_slab::PinSlab;
///
/// let mut slab = PinSlab::new();
/// assert!(slab.is_empty());
/// assert_eq!(0, slab.insert(42));
/// assert!(!slab.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Insert a value into the pin slab.
pub fn insert(&mut self, val: T) -> usize {
let key = self.next;
self.insert_at(key, val);
key
}
/// Access the given key as a pinned mutable value.
pub fn get_pin_mut(&mut self, key: usize) -> Option<Pin<&mut T>> {
self.entries
.get_pin_mut(key)
.and_then(|entry| match entry.project() {
EntryProject::Occupied(entry) => Some(entry),
_ => None,
})
}
/// Get a reference to the value at the given slot.
///
/// # Examples
///
/// ```rust
/// use unicycle::pin_slab::PinSlab;
///
/// let mut slab = PinSlab::new();
/// let key = slab.insert(42);
/// assert_eq!(Some(&42), slab.get(key));
/// ```
pub fn get(&mut self, key: usize) -> Option<&T> {
self.entries.get(key).and_then(|entry| match entry {
Entry::Occupied(entry) => Some(entry),
_ => None,
})
}
/// Get a mutable reference to the value at the given slot.
///
/// # Examples
///
/// ```rust
/// use unicycle::pin_slab::PinSlab;
///
/// let mut slab = PinSlab::new();
/// let key = slab.insert(42);
/// *slab.get_mut(key).unwrap() = 43;
/// assert_eq!(Some(&43), slab.get(key));
/// ```
pub fn get_mut(&mut self, key: usize) -> Option<&mut T>
where
T: Unpin,
{
self.entries.get_mut(key).and_then(|entry| match entry {
Entry::Occupied(entry) => Some(entry),
_ => None,
})
}
/// Remove the key from the slab.
///
/// Returns `true` if the entry was removed, `false` otherwise.
/// Removing a key which does not exist has no effect, and `false` will be
/// returned.
///
/// We need to take care that we don't move it, hence we only perform
/// operations over pointers below.
///
/// # Examples
///
/// ```rust
/// use unicycle::pin_slab::PinSlab;
///
/// let mut slab = PinSlab::new();
///
/// assert!(!slab.remove(0));
/// let index = slab.insert(42);
/// assert!(slab.remove(index));
/// assert!(!slab.remove(index));
/// ```
pub fn remove(&mut self, key: usize) -> bool {
let mut entry = match self.entries.get_pin_mut(key) {
Some(entry) => entry,
None => return false,
};
match entry.as_mut().project() {
EntryProject::Occupied(..) => (),
_ => return false,
}
entry.set(Entry::Vacant(self.next));
self.len -= 1;
self.next = key;
true
}
/// Clear all available data in the PinSlot.
///
/// # Examples
///
/// ```rust
/// use unicycle::pin_slab::PinSlab;
///
/// let mut slab = PinSlab::new();
/// assert_eq!(0, slab.insert(42));
/// slab.clear();
/// assert!(slab.get(0).is_none());
/// ```
pub fn clear(&mut self) {
self.entries.clear()
}
/// Insert a value at the given slot.
fn insert_at(&mut self, key: usize, val: T) {
if key >= self.entries.len() {
self.entries
.extend((self.entries.len()..=key).map(|_| Entry::None));
}
let mut entry = self.entries.get_pin_mut(key).unwrap();
self.next = match entry.as_mut().project() {
EntryProject::None => key + 1,
EntryProject::Vacant(next) => *next,
// NB: unreachable because insert_at is an internal function,
// which can only be appropriately called on non-occupied
// entries. This is however, not a safety concern.
_ => unreachable!(),
};
entry.set(Entry::Occupied(val));
self.len += 1;
}
}
impl<T> Default for PinSlab<T> {
fn default() -> Self {
Self::new()
}
}
|
// 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::time::Duration;
use common_base::base::tokio;
use common_exception::ErrorCode;
use common_grpc::ConnectionFactory;
use common_meta_api::SchemaApi;
use common_meta_app::schema::GetDatabaseReq;
use common_meta_client::MetaGrpcClient;
use common_meta_client::MIN_METASRV_SEMVER;
use common_meta_types::protobuf::meta_service_client::MetaServiceClient;
use common_meta_types::MetaClientError;
use common_meta_types::MetaError;
use crate::grpc_server::start_grpc_server;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_grpc_client_action_timeout() {
// start_grpc_server will sleep 1 second.
let srv_addr = start_grpc_server();
// use `timeout=3secs` here cause our mock grpc
// server's handshake impl will sleep 2secs.
let timeout = Duration::from_secs(3);
let client =
MetaGrpcClient::try_create(vec![srv_addr], "", "", Some(timeout), None, None).unwrap();
let res = client
.get_database(GetDatabaseReq::new("tenant1", "xx"))
.await;
let got = res.unwrap_err();
let got = ErrorCode::from(got).message();
let expect = "ConnectionError: source: tonic::status::Status: status: Cancelled, message: \"Timeout expired\", details: [], metadata: MetadataMap { headers: {} } source: transport error source: Timeout expired";
assert_eq!(got, expect);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_grpc_client_handshake_timeout() {
let srv_addr = start_grpc_server();
// timeout will happen
{
// our mock grpc server's handshake impl will sleep 2secs.
// see: GrpcServiceForTestImp.handshake
let timeout = Duration::from_secs(2);
let c = ConnectionFactory::create_rpc_channel(srv_addr.clone(), Some(timeout), None)
.await
.unwrap();
let mut client = MetaServiceClient::new(c);
let res = MetaGrpcClient::handshake(
&mut client,
&MIN_METASRV_SEMVER,
&MIN_METASRV_SEMVER,
"root",
"xxx",
)
.await;
let got = res.unwrap_err();
let got =
ErrorCode::from(MetaError::ClientError(MetaClientError::HandshakeError(got))).message();
let expect = "failed to handshake with meta-service: when sending handshake rpc, cause: tonic::status::Status: status: Cancelled, message: \"Timeout expired\", details: [], metadata: MetadataMap { headers: {} } source: transport error source: Timeout expired";
assert_eq!(got, expect);
}
// handshake success
{
let timeout = Duration::from_secs(3);
let c = ConnectionFactory::create_rpc_channel(srv_addr, Some(timeout), None)
.await
.unwrap();
let mut client = MetaServiceClient::new(c);
let res = MetaGrpcClient::handshake(
&mut client,
&MIN_METASRV_SEMVER,
&MIN_METASRV_SEMVER,
"root",
"xxx",
)
.await;
assert!(res.is_ok());
}
}
|
/// ```rust,ignore
/// 89. 格雷编码
/// 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
///
/// 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。
///
/// 示例 1:
///
/// 输入: 2
/// 输出: [0,1,3,2]
/// 解释:
/// 00 - 0
/// 01 - 1
/// 11 - 3
/// 10 - 2
///
/// 对于给定的 n,其格雷编码序列并不唯一。
/// 例如,[0,2,3,1] 也是一个有效的格雷编码序列。
///
/// 00 - 0
/// 10 - 2
/// 11 - 3
/// 01 - 1
///
/// 示例 2:
///
/// 输入: 0
/// 输出: [0]
/// 解释: 我们定义格雷编码序列必须以 0 开头。
/// 给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。
/// 因此,当 n = 0 时,其格雷编码序列为 [0]。
///
/// 来源:力扣(LeetCode)
/// 链接:https://leetcode-cn.com/problems/gray-code
/// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/// ```
pub fn gray_code(n: i32) -> Vec<i32> {
let mut vec: Vec<i32> = Vec::new();
for i in 0..2_i32.pow(n as u32) {
vec.push(i ^ i>>1)
}
vec
}
#[cfg(test)]
mod test
{
use super::*;
#[test]
fn test_gray_code()
{
assert_eq!(gray_code(2), vec![0,1,3,2]);
}
}
|
use input_i_scanner::InputIScanner;
use std::collections::HashSet;
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 = scan!(usize);
let mut set = HashSet::new();
for _ in 0..n {
let l = scan!(usize);
let a = scan!(u32; l);
set.insert(a);
}
println!("{}", set.len());
}
|
use super::{LayerVariablesBuilder};
use super::super::{algebra, Layer, LayerInstance};
use ndarray::Dimension;
// Performs batch normalization during inference. This layer only supports inference and does NOT
// implement proper batch normalization during training since this library has no concept of
// batches right now.
pub struct BatchNormalization<BetaInitializer, GammaInitializer, MovingMeanInitializer, MovingVarianceInitializer>
where BetaInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
GammaInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
MovingMeanInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
MovingVarianceInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
{
pub epsilon: f32,
pub beta_initializer: BetaInitializer,
pub gamma_initializer: GammaInitializer,
pub moving_mean_initializer: MovingMeanInitializer,
pub moving_variance_initializer: MovingVarianceInitializer,
}
impl<BetaInitializer, GammaInitializer, MovingMeanInitializer, MovingVarianceInitializer> Layer for BatchNormalization<BetaInitializer, GammaInitializer, MovingMeanInitializer, MovingVarianceInitializer>
where BetaInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
GammaInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
MovingMeanInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
MovingVarianceInitializer: Fn(&ndarray::IxDyn) -> ndarray::ArrayD<f32>,
{
fn init(self: Box<Self>, namespace: &str, input_shape: &ndarray::IxDyn) -> Box<dyn LayerInstance> {
let mut lv_builder = LayerVariablesBuilder::new(namespace);
let epsilon = self.epsilon;
let depth = input_shape.as_array_view()[input_shape.ndim() - 1];
let beta = lv_builder.append("beta", (self.beta_initializer)(&ndarray::IxDyn(&[depth])));
let gamma = lv_builder.append("gamma", (self.gamma_initializer)(&ndarray::IxDyn(&[depth])));
let moving_mean = lv_builder.append("moving_mean", (self.moving_mean_initializer)(&ndarray::IxDyn(&[depth])));
let moving_variance = lv_builder.append("moving_variance", (self.moving_variance_initializer)(&ndarray::IxDyn(&[depth])));
let input_shape = input_shape.clone();
Box::new(super::Instance{
expression: move |input| {
let inv = gamma.clone() / (moving_variance.clone() + epsilon).sqrt();
input * algebra::broadcast_to(inv.clone(), input_shape.clone()) + algebra::broadcast_to(beta.clone() - moving_mean.clone() * inv, input_shape.clone())
},
variables: lv_builder.variables,
})
}
}
|
use super::*;
mod with_small_integer_time;
// BigInt is not tested because it would take too long and would always count as `long_term` for the
// super shot soon and later wheel sizes used for `cfg(test)`
#[test]
fn without_non_negative_integer_time_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_not_non_negative_integer(arc_process.clone()),
strategy::term(arc_process.clone()),
)
},
|(arc_process, time, message)| {
let destination = arc_process.pid_term();
let options = options(&arc_process);
prop_assert_badarg!(
result(arc_process.clone(), time, destination, message, options),
format!("time ({}) is not a non-negative integer", time)
);
Ok(())
},
);
}
fn options(process: &Process) -> Term {
super::options(true.into(), process)
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {
pub fn CloseIMsgSession(lpmsgsess: *mut _MSGSESS);
#[cfg(feature = "Win32_System_AddressBook")]
pub fn GetAttribIMsgOnIStg(lpobject: *mut ::core::ffi::c_void, lpproptagarray: *mut super::super::System::AddressBook::SPropTagArray, lpppropattrarray: *mut *mut SPropAttrArray) -> ::windows_sys::core::HRESULT;
pub fn MapStorageSCode(stgscode: i32) -> i32;
#[cfg(all(feature = "Win32_System_AddressBook", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))]
pub fn OpenIMsgOnIStg(
lpmsgsess: *mut _MSGSESS,
lpallocatebuffer: super::super::System::AddressBook::LPALLOCATEBUFFER,
lpallocatemore: super::super::System::AddressBook::LPALLOCATEMORE,
lpfreebuffer: super::super::System::AddressBook::LPFREEBUFFER,
lpmalloc: super::super::System::Com::IMalloc,
lpmapisup: *mut ::core::ffi::c_void,
lpstg: super::super::System::Com::StructuredStorage::IStorage,
lpfmsgcallrelease: *mut MSGCALLRELEASE,
ulcallerdata: u32,
ulflags: u32,
lppmsg: *mut super::super::System::AddressBook::IMessage,
) -> i32;
#[cfg(feature = "Win32_System_Com")]
pub fn OpenIMsgSession(lpmalloc: super::super::System::Com::IMalloc, ulflags: u32, lppmsgsess: *mut *mut _MSGSESS) -> i32;
#[cfg(feature = "Win32_System_AddressBook")]
pub fn SetAttribIMsgOnIStg(lpobject: *mut ::core::ffi::c_void, lpproptags: *mut super::super::System::AddressBook::SPropTagArray, lppropattrs: *mut SPropAttrArray, lpppropproblems: *mut *mut super::super::System::AddressBook::SPropProblemArray) -> ::windows_sys::core::HRESULT;
}
pub const BlockRange: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3037186599, data2: 8708, data3: 4573, data4: [150, 106, 0, 26, 160, 27, 188, 88] };
pub const BlockRangeList: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3037186600, data2: 8708, data3: 4573, data4: [150, 106, 0, 26, 160, 27, 188, 88] };
pub const BootOptions: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904974, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const CATID_SMTP_DNSRESOLVERRECORDSINK: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3171631974, data2: 36355, data3: 4562, data4: [148, 246, 0, 192, 79, 121, 241, 214] };
pub const CATID_SMTP_DSN: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 582309681,
data2: 62968,
data3: 19747,
data4: [189, 143, 135, 181, 35, 113, 167, 58],
};
pub const CATID_SMTP_GET_AUX_DOMAIN_INFO_FLAGS: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2231318154,
data2: 64179,
data3: 17367,
data4: [188, 223, 105, 44, 91, 70, 230, 177],
};
pub const CATID_SMTP_LOG: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2479924536,
data2: 11294,
data3: 19304,
data4: [167, 201, 215, 58, 138, 166, 238, 151],
};
pub const CATID_SMTP_MAXMSGSIZE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3958462942, data2: 42622, data3: 4562, data4: [148, 247, 0, 192, 79, 121, 241, 214] };
pub const CATID_SMTP_MSGTRACKLOG: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3336524458, data2: 32176, data3: 4562, data4: [148, 244, 0, 192, 79, 121, 241, 214] };
pub const CATID_SMTP_ON_BEFORE_DATA: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4133653650, data2: 3422, data3: 4562, data4: [170, 104, 0, 192, 79, 163, 91, 130] };
pub const CATID_SMTP_ON_INBOUND_COMMAND: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4133653645, data2: 3422, data3: 4562, data4: [170, 104, 0, 192, 79, 163, 91, 130] };
pub const CATID_SMTP_ON_MESSAGE_START: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4133653648, data2: 3422, data3: 4562, data4: [170, 104, 0, 192, 79, 163, 91, 130] };
pub const CATID_SMTP_ON_PER_RECIPIENT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4133653649, data2: 3422, data3: 4562, data4: [170, 104, 0, 192, 79, 163, 91, 130] };
pub const CATID_SMTP_ON_SERVER_RESPONSE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4133653646, data2: 3422, data3: 4562, data4: [170, 104, 0, 192, 79, 163, 91, 130] };
pub const CATID_SMTP_ON_SESSION_END: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4133653651, data2: 3422, data3: 4562, data4: [170, 104, 0, 192, 79, 163, 91, 130] };
pub const CATID_SMTP_ON_SESSION_START: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4133653647, data2: 3422, data3: 4562, data4: [170, 104, 0, 192, 79, 163, 91, 130] };
pub const CATID_SMTP_STORE_DRIVER: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1494702160, data2: 58675, data3: 4561, data4: [170, 103, 0, 192, 79, 163, 69, 246] };
pub const CATID_SMTP_TRANSPORT_CATEGORIZE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2516734627, data2: 2618, data3: 4562, data4: [158, 0, 0, 192, 79, 163, 34, 186] };
pub const CATID_SMTP_TRANSPORT_POSTCATEGORIZE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1987155540, data2: 1446, data3: 4562, data4: [157, 253, 0, 192, 79, 163, 34, 186] };
pub const CATID_SMTP_TRANSPORT_PRECATEGORIZE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2746022669, data2: 33791, data3: 4562, data4: [158, 20, 0, 192, 79, 163, 34, 186] };
pub const CATID_SMTP_TRANSPORT_ROUTER: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 674509001, data2: 6224, data3: 4562, data4: [158, 3, 0, 192, 79, 163, 34, 186] };
pub const CATID_SMTP_TRANSPORT_SUBMISSION: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4282165795, data2: 185, data3: 4562, data4: [157, 251, 0, 192, 79, 163, 34, 186] };
pub const CLSID_SmtpCat: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2990290359, data2: 37401, data3: 4562, data4: [158, 23, 0, 192, 79, 163, 34, 186] };
pub type DDiscFormat2DataEvents = *mut ::core::ffi::c_void;
pub type DDiscFormat2EraseEvents = *mut ::core::ffi::c_void;
pub type DDiscFormat2RawCDEvents = *mut ::core::ffi::c_void;
pub type DDiscFormat2TrackAtOnceEvents = *mut ::core::ffi::c_void;
pub type DDiscMaster2Events = *mut ::core::ffi::c_void;
pub type DFileSystemImageEvents = *mut ::core::ffi::c_void;
pub type DFileSystemImageImportEvents = *mut ::core::ffi::c_void;
pub type DISC_RECORDER_STATE_FLAGS = u32;
pub const RECORDER_BURNING: DISC_RECORDER_STATE_FLAGS = 2u32;
pub const RECORDER_DOING_NOTHING: DISC_RECORDER_STATE_FLAGS = 0u32;
pub const RECORDER_OPENED: DISC_RECORDER_STATE_FLAGS = 1u32;
pub const DISPID_DDISCFORMAT2DATAEVENTS_UPDATE: u32 = 512u32;
pub const DISPID_DDISCFORMAT2RAWCDEVENTS_UPDATE: u32 = 512u32;
pub const DISPID_DDISCFORMAT2TAOEVENTS_UPDATE: u32 = 512u32;
pub const DISPID_DDISCMASTER2EVENTS_DEVICEADDED: u32 = 256u32;
pub const DISPID_DDISCMASTER2EVENTS_DEVICEREMOVED: u32 = 257u32;
pub const DISPID_DFILESYSTEMIMAGEEVENTS_UPDATE: u32 = 256u32;
pub const DISPID_DFILESYSTEMIMAGEIMPORTEVENTS_UPDATEIMPORT: u32 = 257u32;
pub const DISPID_DWRITEENGINE2EVENTS_UPDATE: u32 = 256u32;
pub const DISPID_IBLOCKRANGELIST_BLOCKRANGES: u32 = 256u32;
pub const DISPID_IBLOCKRANGE_ENDLBA: u32 = 257u32;
pub const DISPID_IBLOCKRANGE_STARTLBA: u32 = 256u32;
pub const DISPID_IDISCFORMAT2DATAEVENTARGS_CURRENTACTION: u32 = 771u32;
pub const DISPID_IDISCFORMAT2DATAEVENTARGS_ELAPSEDTIME: u32 = 768u32;
pub const DISPID_IDISCFORMAT2DATAEVENTARGS_ESTIMATEDREMAININGTIME: u32 = 769u32;
pub const DISPID_IDISCFORMAT2DATAEVENTARGS_ESTIMATEDTOTALTIME: u32 = 770u32;
pub const DISPID_IDISCFORMAT2DATA_BUFFERUNDERRUNFREEDISABLED: u32 = 257u32;
pub const DISPID_IDISCFORMAT2DATA_CANCELWRITE: u32 = 513u32;
pub const DISPID_IDISCFORMAT2DATA_CLIENTNAME: u32 = 272u32;
pub const DISPID_IDISCFORMAT2DATA_CURRENTMEDIASTATUS: u32 = 262u32;
pub const DISPID_IDISCFORMAT2DATA_CURRENTMEDIATYPE: u32 = 271u32;
pub const DISPID_IDISCFORMAT2DATA_CURRENTROTATIONTYPEISPURECAV: u32 = 276u32;
pub const DISPID_IDISCFORMAT2DATA_CURRENTWRITESPEED: u32 = 275u32;
pub const DISPID_IDISCFORMAT2DATA_DISABLEDVDCOMPATIBILITYMODE: u32 = 270u32;
pub const DISPID_IDISCFORMAT2DATA_FORCEMEDIATOBECLOSED: u32 = 269u32;
pub const DISPID_IDISCFORMAT2DATA_FORCEOVERWRITE: u32 = 279u32;
pub const DISPID_IDISCFORMAT2DATA_FREESECTORS: u32 = 265u32;
pub const DISPID_IDISCFORMAT2DATA_LASTSECTOROFPREVIOUSSESSION: u32 = 268u32;
pub const DISPID_IDISCFORMAT2DATA_MUTLISESSIONINTERFACES: u32 = 280u32;
pub const DISPID_IDISCFORMAT2DATA_NEXTWRITABLEADDRESS: u32 = 266u32;
pub const DISPID_IDISCFORMAT2DATA_POSTGAPALREADYINIMAGE: u32 = 260u32;
pub const DISPID_IDISCFORMAT2DATA_RECORDER: u32 = 256u32;
pub const DISPID_IDISCFORMAT2DATA_REQUESTEDROTATIONTYPEISPURECAV: u32 = 274u32;
pub const DISPID_IDISCFORMAT2DATA_REQUESTEDWRITESPEED: u32 = 273u32;
pub const DISPID_IDISCFORMAT2DATA_SETWRITESPEED: u32 = 514u32;
pub const DISPID_IDISCFORMAT2DATA_STARTSECTOROFPREVIOUSSESSION: u32 = 267u32;
pub const DISPID_IDISCFORMAT2DATA_SUPPORTEDWRITESPEEDDESCRIPTORS: u32 = 278u32;
pub const DISPID_IDISCFORMAT2DATA_SUPPORTEDWRITESPEEDS: u32 = 277u32;
pub const DISPID_IDISCFORMAT2DATA_TOTALSECTORS: u32 = 264u32;
pub const DISPID_IDISCFORMAT2DATA_WRITE: u32 = 512u32;
pub const DISPID_IDISCFORMAT2DATA_WRITEPROTECTSTATUS: u32 = 263u32;
pub const DISPID_IDISCFORMAT2ERASEEVENTS_UPDATE: u32 = 512u32;
pub const DISPID_IDISCFORMAT2ERASE_CLIENTNAME: u32 = 259u32;
pub const DISPID_IDISCFORMAT2ERASE_ERASEMEDIA: u32 = 513u32;
pub const DISPID_IDISCFORMAT2ERASE_FULLERASE: u32 = 257u32;
pub const DISPID_IDISCFORMAT2ERASE_MEDIATYPE: u32 = 258u32;
pub const DISPID_IDISCFORMAT2ERASE_RECORDER: u32 = 256u32;
pub const DISPID_IDISCFORMAT2RAWCDEVENTARGS_CURRENTACTION: u32 = 769u32;
pub const DISPID_IDISCFORMAT2RAWCDEVENTARGS_CURRENTTRACKNUMBER: u32 = 768u32;
pub const DISPID_IDISCFORMAT2RAWCDEVENTARGS_ELAPSEDTIME: u32 = 768u32;
pub const DISPID_IDISCFORMAT2RAWCDEVENTARGS_ESTIMATEDREMAININGTIME: u32 = 769u32;
pub const DISPID_IDISCFORMAT2RAWCDEVENTARGS_ESTIMATEDTOTALTIME: u32 = 770u32;
pub const DISPID_IDISCFORMAT2RAWCD_BUFFERUNDERRUNFREEDISABLED: u32 = 258u32;
pub const DISPID_IDISCFORMAT2RAWCD_CANCELWRITE: u32 = 515u32;
pub const DISPID_IDISCFORMAT2RAWCD_CLIENTNAME: u32 = 266u32;
pub const DISPID_IDISCFORMAT2RAWCD_CURRENTMEDIATYPE: u32 = 261u32;
pub const DISPID_IDISCFORMAT2RAWCD_CURRENTROTATIONTYPEISPURECAV: u32 = 270u32;
pub const DISPID_IDISCFORMAT2RAWCD_CURRENTWRITESPEED: u32 = 269u32;
pub const DISPID_IDISCFORMAT2RAWCD_LASTPOSSIBLESTARTOFLEADOUT: u32 = 260u32;
pub const DISPID_IDISCFORMAT2RAWCD_PREPAREMEDIA: u32 = 512u32;
pub const DISPID_IDISCFORMAT2RAWCD_RECORDER: u32 = 256u32;
pub const DISPID_IDISCFORMAT2RAWCD_RELEASEMEDIA: u32 = 516u32;
pub const DISPID_IDISCFORMAT2RAWCD_REQUESTEDDATASECTORTYPE: u32 = 265u32;
pub const DISPID_IDISCFORMAT2RAWCD_REQUESTEDROTATIONTYPEISPURECAV: u32 = 268u32;
pub const DISPID_IDISCFORMAT2RAWCD_REQUESTEDWRITESPEED: u32 = 267u32;
pub const DISPID_IDISCFORMAT2RAWCD_SETWRITESPEED: u32 = 517u32;
pub const DISPID_IDISCFORMAT2RAWCD_STARTOFNEXTSESSION: u32 = 259u32;
pub const DISPID_IDISCFORMAT2RAWCD_SUPPORTEDDATASECTORTYPES: u32 = 264u32;
pub const DISPID_IDISCFORMAT2RAWCD_SUPPORTEDWRITESPEEDDESCRIPTORS: u32 = 272u32;
pub const DISPID_IDISCFORMAT2RAWCD_SUPPORTEDWRITESPEEDS: u32 = 271u32;
pub const DISPID_IDISCFORMAT2RAWCD_WRITEMEDIA: u32 = 513u32;
pub const DISPID_IDISCFORMAT2RAWCD_WRITEMEDIAWITHVALIDATION: u32 = 514u32;
pub const DISPID_IDISCFORMAT2TAOEVENTARGS_CURRENTACTION: u32 = 769u32;
pub const DISPID_IDISCFORMAT2TAOEVENTARGS_CURRENTTRACKNUMBER: u32 = 768u32;
pub const DISPID_IDISCFORMAT2TAOEVENTARGS_ELAPSEDTIME: u32 = 770u32;
pub const DISPID_IDISCFORMAT2TAOEVENTARGS_ESTIMATEDREMAININGTIME: u32 = 771u32;
pub const DISPID_IDISCFORMAT2TAOEVENTARGS_ESTIMATEDTOTALTIME: u32 = 772u32;
pub const DISPID_IDISCFORMAT2TAO_ADDAUDIOTRACK: u32 = 513u32;
pub const DISPID_IDISCFORMAT2TAO_BUFFERUNDERRUNFREEDISABLED: u32 = 258u32;
pub const DISPID_IDISCFORMAT2TAO_CANCELADDTRACK: u32 = 514u32;
pub const DISPID_IDISCFORMAT2TAO_CLIENTNAME: u32 = 270u32;
pub const DISPID_IDISCFORMAT2TAO_CURRENTMEDIATYPE: u32 = 267u32;
pub const DISPID_IDISCFORMAT2TAO_CURRENTROTATIONTYPEISPURECAV: u32 = 274u32;
pub const DISPID_IDISCFORMAT2TAO_CURRENTWRITESPEED: u32 = 273u32;
pub const DISPID_IDISCFORMAT2TAO_DONOTFINALIZEMEDIA: u32 = 263u32;
pub const DISPID_IDISCFORMAT2TAO_EXPECTEDTABLEOFCONTENTS: u32 = 266u32;
pub const DISPID_IDISCFORMAT2TAO_FINISHMEDIA: u32 = 515u32;
pub const DISPID_IDISCFORMAT2TAO_FREESECTORSONMEDIA: u32 = 261u32;
pub const DISPID_IDISCFORMAT2TAO_NUMBEROFEXISTINGTRACKS: u32 = 259u32;
pub const DISPID_IDISCFORMAT2TAO_PREPAREMEDIA: u32 = 512u32;
pub const DISPID_IDISCFORMAT2TAO_RECORDER: u32 = 256u32;
pub const DISPID_IDISCFORMAT2TAO_REQUESTEDROTATIONTYPEISPURECAV: u32 = 272u32;
pub const DISPID_IDISCFORMAT2TAO_REQUESTEDWRITESPEED: u32 = 271u32;
pub const DISPID_IDISCFORMAT2TAO_SETWRITESPEED: u32 = 516u32;
pub const DISPID_IDISCFORMAT2TAO_SUPPORTEDWRITESPEEDDESCRIPTORS: u32 = 276u32;
pub const DISPID_IDISCFORMAT2TAO_SUPPORTEDWRITESPEEDS: u32 = 275u32;
pub const DISPID_IDISCFORMAT2TAO_TOTALSECTORSONMEDIA: u32 = 260u32;
pub const DISPID_IDISCFORMAT2TAO_USEDSECTORSONMEDIA: u32 = 262u32;
pub const DISPID_IDISCFORMAT2_MEDIAHEURISTICALLYBLANK: u32 = 1793u32;
pub const DISPID_IDISCFORMAT2_MEDIAPHYSICALLYBLANK: u32 = 1792u32;
pub const DISPID_IDISCFORMAT2_MEDIASUPPORTED: u32 = 2049u32;
pub const DISPID_IDISCFORMAT2_RECORDERSUPPORTED: u32 = 2048u32;
pub const DISPID_IDISCFORMAT2_SUPPORTEDMEDIATYPES: u32 = 1794u32;
pub const DISPID_IDISCRECORDER2_ACQUIREEXCLUSIVEACCESS: u32 = 258u32;
pub const DISPID_IDISCRECORDER2_ACTIVEDISCRECORDER: u32 = 0u32;
pub const DISPID_IDISCRECORDER2_CLOSETRAY: u32 = 257u32;
pub const DISPID_IDISCRECORDER2_CURRENTFEATUREPAGES: u32 = 521u32;
pub const DISPID_IDISCRECORDER2_CURRENTPROFILES: u32 = 523u32;
pub const DISPID_IDISCRECORDER2_DEVICECANLOADMEDIA: u32 = 518u32;
pub const DISPID_IDISCRECORDER2_DISABLEMCN: u32 = 260u32;
pub const DISPID_IDISCRECORDER2_EJECTMEDIA: u32 = 256u32;
pub const DISPID_IDISCRECORDER2_ENABLEMCN: u32 = 261u32;
pub const DISPID_IDISCRECORDER2_EXCLUSIVEACCESSOWNER: u32 = 525u32;
pub const DISPID_IDISCRECORDER2_INITIALIZEDISCRECORDER: u32 = 262u32;
pub const DISPID_IDISCRECORDER2_LEGACYDEVICENUMBER: u32 = 519u32;
pub const DISPID_IDISCRECORDER2_PRODUCTID: u32 = 514u32;
pub const DISPID_IDISCRECORDER2_PRODUCTREVISION: u32 = 515u32;
pub const DISPID_IDISCRECORDER2_RELEASEEXCLUSIVEACCESS: u32 = 259u32;
pub const DISPID_IDISCRECORDER2_SUPPORTEDFEATUREPAGES: u32 = 520u32;
pub const DISPID_IDISCRECORDER2_SUPPORTEDMODEPAGES: u32 = 524u32;
pub const DISPID_IDISCRECORDER2_SUPPORTEDPROFILES: u32 = 522u32;
pub const DISPID_IDISCRECORDER2_VENDORID: u32 = 513u32;
pub const DISPID_IDISCRECORDER2_VOLUMENAME: u32 = 516u32;
pub const DISPID_IDISCRECORDER2_VOLUMEPATHNAMES: u32 = 517u32;
pub const DISPID_IMULTISESSION_FIRSTDATASESSION: u32 = 512u32;
pub const DISPID_IMULTISESSION_FREESECTORS: u32 = 516u32;
pub const DISPID_IMULTISESSION_IMPORTRECORDER: u32 = 258u32;
pub const DISPID_IMULTISESSION_INUSE: u32 = 257u32;
pub const DISPID_IMULTISESSION_LASTSECTOROFPREVIOUSSESSION: u32 = 514u32;
pub const DISPID_IMULTISESSION_LASTWRITTENADDRESS: u32 = 518u32;
pub const DISPID_IMULTISESSION_NEXTWRITABLEADDRESS: u32 = 515u32;
pub const DISPID_IMULTISESSION_SECTORSONMEDIA: u32 = 519u32;
pub const DISPID_IMULTISESSION_STARTSECTOROFPREVIOUSSESSION: u32 = 513u32;
pub const DISPID_IMULTISESSION_SUPPORTEDONCURRENTMEDIA: u32 = 256u32;
pub const DISPID_IMULTISESSION_WRITEUNITSIZE: u32 = 517u32;
pub const DISPID_IRAWCDIMAGECREATOR_ADDSPECIALPREGAP: u32 = 514u32;
pub const DISPID_IRAWCDIMAGECREATOR_ADDSUBCODERWGENERATOR: u32 = 515u32;
pub const DISPID_IRAWCDIMAGECREATOR_ADDTRACK: u32 = 513u32;
pub const DISPID_IRAWCDIMAGECREATOR_CREATERESULTIMAGE: u32 = 512u32;
pub const DISPID_IRAWCDIMAGECREATOR_DISABLEGAPLESSAUDIO: u32 = 259u32;
pub const DISPID_IRAWCDIMAGECREATOR_EXPECTEDTABLEOFCONTENTS: u32 = 265u32;
pub const DISPID_IRAWCDIMAGECREATOR_MEDIACATALOGNUMBER: u32 = 260u32;
pub const DISPID_IRAWCDIMAGECREATOR_NUMBEROFEXISTINGTRACKS: u32 = 263u32;
pub const DISPID_IRAWCDIMAGECREATOR_RESULTINGIMAGETYPE: u32 = 256u32;
pub const DISPID_IRAWCDIMAGECREATOR_STARTINGTRACKNUMBER: u32 = 261u32;
pub const DISPID_IRAWCDIMAGECREATOR_STARTOFLEADOUT: u32 = 257u32;
pub const DISPID_IRAWCDIMAGECREATOR_STARTOFLEADOUTLIMIT: u32 = 258u32;
pub const DISPID_IRAWCDIMAGECREATOR_TRACKINFO: u32 = 262u32;
pub const DISPID_IRAWCDIMAGECREATOR_USEDSECTORSONDISC: u32 = 264u32;
pub const DISPID_IRAWCDTRACKINFO_AUDIOHASPREEMPHASIS: u32 = 262u32;
pub const DISPID_IRAWCDTRACKINFO_DIGITALAUDIOCOPYSETTING: u32 = 261u32;
pub const DISPID_IRAWCDTRACKINFO_ISRC: u32 = 260u32;
pub const DISPID_IRAWCDTRACKINFO_SECTORCOUNT: u32 = 257u32;
pub const DISPID_IRAWCDTRACKINFO_SECTORTYPE: u32 = 259u32;
pub const DISPID_IRAWCDTRACKINFO_STARTINGLBA: u32 = 256u32;
pub const DISPID_IRAWCDTRACKINFO_TRACKNUMBER: u32 = 258u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_FREESYSTEMBUFFER: u32 = 264u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_LASTREADLBA: u32 = 258u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_LASTWRITTENLBA: u32 = 259u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_SECTORCOUNT: u32 = 257u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_STARTLBA: u32 = 256u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_TOTALDEVICEBUFFER: u32 = 260u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_TOTALSYSTEMBUFFER: u32 = 262u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_USEDDEVICEBUFFER: u32 = 261u32;
pub const DISPID_IWRITEENGINE2EVENTARGS_USEDSYSTEMBUFFER: u32 = 263u32;
pub const DISPID_IWRITEENGINE2_BYTESPERSECTOR: u32 = 260u32;
pub const DISPID_IWRITEENGINE2_CANCELWRITE: u32 = 513u32;
pub const DISPID_IWRITEENGINE2_DISCRECORDER: u32 = 256u32;
pub const DISPID_IWRITEENGINE2_ENDINGSECTORSPERSECOND: u32 = 259u32;
pub const DISPID_IWRITEENGINE2_STARTINGSECTORSPERSECOND: u32 = 258u32;
pub const DISPID_IWRITEENGINE2_USESTREAMINGWRITE12: u32 = 257u32;
pub const DISPID_IWRITEENGINE2_WRITEINPROGRESS: u32 = 261u32;
pub const DISPID_IWRITEENGINE2_WRITESECTION: u32 = 512u32;
pub type DWriteEngine2Events = *mut ::core::ffi::c_void;
pub type EmulationType = i32;
pub const EmulationNone: EmulationType = 0i32;
pub const Emulation12MFloppy: EmulationType = 1i32;
pub const Emulation144MFloppy: EmulationType = 2i32;
pub const Emulation288MFloppy: EmulationType = 3i32;
pub const EmulationHardDisk: EmulationType = 4i32;
pub const EnumFsiItems: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904966, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const EnumProgressItems: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904970, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const FileSystemImageResult: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904972, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const FsiDirectoryItem: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904968, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const FsiFileItem: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904967, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub type FsiFileSystems = i32;
pub const FsiFileSystemNone: FsiFileSystems = 0i32;
pub const FsiFileSystemISO9660: FsiFileSystems = 1i32;
pub const FsiFileSystemJoliet: FsiFileSystems = 2i32;
pub const FsiFileSystemUDF: FsiFileSystems = 4i32;
pub const FsiFileSystemUnknown: FsiFileSystems = 1073741824i32;
pub type FsiItemType = i32;
pub const FsiItemNotFound: FsiItemType = 0i32;
pub const FsiItemDirectory: FsiItemType = 1i32;
pub const FsiItemFile: FsiItemType = 2i32;
pub const FsiNamedStreams: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3333880045,
data2: 27929,
data3: 17588,
data4: [181, 57, 177, 89, 183, 147, 163, 45],
};
pub const FsiStream: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904973, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const GUID_SMTPSVC_SOURCE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 456918630, data2: 58480, data3: 4561, data4: [170, 103, 0, 192, 79, 163, 69, 246] };
pub const GUID_SMTP_SOURCE_TYPE: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4217750748, data2: 58472, data3: 4561, data4: [170, 103, 0, 192, 79, 163, 69, 246] };
pub type IBlockRange = *mut ::core::ffi::c_void;
pub type IBlockRangeList = *mut ::core::ffi::c_void;
pub type IBootOptions = *mut ::core::ffi::c_void;
pub type IBurnVerification = *mut ::core::ffi::c_void;
pub type IDiscFormat2 = *mut ::core::ffi::c_void;
pub type IDiscFormat2Data = *mut ::core::ffi::c_void;
pub type IDiscFormat2DataEventArgs = *mut ::core::ffi::c_void;
pub type IDiscFormat2Erase = *mut ::core::ffi::c_void;
pub type IDiscFormat2RawCD = *mut ::core::ffi::c_void;
pub type IDiscFormat2RawCDEventArgs = *mut ::core::ffi::c_void;
pub type IDiscFormat2TrackAtOnce = *mut ::core::ffi::c_void;
pub type IDiscFormat2TrackAtOnceEventArgs = *mut ::core::ffi::c_void;
pub type IDiscMaster = *mut ::core::ffi::c_void;
pub type IDiscMaster2 = *mut ::core::ffi::c_void;
pub type IDiscMasterProgressEvents = *mut ::core::ffi::c_void;
pub type IDiscRecorder = *mut ::core::ffi::c_void;
pub type IDiscRecorder2 = *mut ::core::ffi::c_void;
pub type IDiscRecorder2Ex = *mut ::core::ffi::c_void;
pub type IEnumDiscMasterFormats = *mut ::core::ffi::c_void;
pub type IEnumDiscRecorders = *mut ::core::ffi::c_void;
pub type IEnumFsiItems = *mut ::core::ffi::c_void;
pub type IEnumProgressItems = *mut ::core::ffi::c_void;
pub type IFileSystemImage = *mut ::core::ffi::c_void;
pub type IFileSystemImage2 = *mut ::core::ffi::c_void;
pub type IFileSystemImage3 = *mut ::core::ffi::c_void;
pub type IFileSystemImageResult = *mut ::core::ffi::c_void;
pub type IFileSystemImageResult2 = *mut ::core::ffi::c_void;
pub type IFsiDirectoryItem = *mut ::core::ffi::c_void;
pub type IFsiDirectoryItem2 = *mut ::core::ffi::c_void;
pub type IFsiFileItem = *mut ::core::ffi::c_void;
pub type IFsiFileItem2 = *mut ::core::ffi::c_void;
pub type IFsiItem = *mut ::core::ffi::c_void;
pub type IFsiNamedStreams = *mut ::core::ffi::c_void;
pub type IIsoImageManager = *mut ::core::ffi::c_void;
pub type IJolietDiscMaster = *mut ::core::ffi::c_void;
pub const IMAPI2FS_BOOT_ENTRY_COUNT_MAX: u32 = 32u32;
pub const IMAPI2FS_MajorVersion: u32 = 1u32;
pub const IMAPI2FS_MinorVersion: u32 = 0u32;
pub const IMAPI2_DEFAULT_COMMAND_TIMEOUT: u32 = 10u32;
pub const IMAPILib2_MajorVersion: u32 = 1u32;
pub const IMAPILib2_MinorVersion: u32 = 0u32;
pub type IMAPI_BURN_VERIFICATION_LEVEL = i32;
pub const IMAPI_BURN_VERIFICATION_NONE: IMAPI_BURN_VERIFICATION_LEVEL = 0i32;
pub const IMAPI_BURN_VERIFICATION_QUICK: IMAPI_BURN_VERIFICATION_LEVEL = 1i32;
pub const IMAPI_BURN_VERIFICATION_FULL: IMAPI_BURN_VERIFICATION_LEVEL = 2i32;
pub type IMAPI_CD_SECTOR_TYPE = i32;
pub const IMAPI_CD_SECTOR_AUDIO: IMAPI_CD_SECTOR_TYPE = 0i32;
pub const IMAPI_CD_SECTOR_MODE_ZERO: IMAPI_CD_SECTOR_TYPE = 1i32;
pub const IMAPI_CD_SECTOR_MODE1: IMAPI_CD_SECTOR_TYPE = 2i32;
pub const IMAPI_CD_SECTOR_MODE2FORM0: IMAPI_CD_SECTOR_TYPE = 3i32;
pub const IMAPI_CD_SECTOR_MODE2FORM1: IMAPI_CD_SECTOR_TYPE = 4i32;
pub const IMAPI_CD_SECTOR_MODE2FORM2: IMAPI_CD_SECTOR_TYPE = 5i32;
pub const IMAPI_CD_SECTOR_MODE1RAW: IMAPI_CD_SECTOR_TYPE = 6i32;
pub const IMAPI_CD_SECTOR_MODE2FORM0RAW: IMAPI_CD_SECTOR_TYPE = 7i32;
pub const IMAPI_CD_SECTOR_MODE2FORM1RAW: IMAPI_CD_SECTOR_TYPE = 8i32;
pub const IMAPI_CD_SECTOR_MODE2FORM2RAW: IMAPI_CD_SECTOR_TYPE = 9i32;
pub type IMAPI_CD_TRACK_DIGITAL_COPY_SETTING = i32;
pub const IMAPI_CD_TRACK_DIGITAL_COPY_PERMITTED: IMAPI_CD_TRACK_DIGITAL_COPY_SETTING = 0i32;
pub const IMAPI_CD_TRACK_DIGITAL_COPY_PROHIBITED: IMAPI_CD_TRACK_DIGITAL_COPY_SETTING = 1i32;
pub const IMAPI_CD_TRACK_DIGITAL_COPY_SCMS: IMAPI_CD_TRACK_DIGITAL_COPY_SETTING = 2i32;
pub const IMAPI_E_ALREADYOPEN: ::windows_sys::core::HRESULT = -2147220958i32;
pub const IMAPI_E_BADJOLIETNAME: ::windows_sys::core::HRESULT = -2147220963i32;
pub const IMAPI_E_BOOTIMAGE_AND_NONBLANK_DISC: ::windows_sys::core::HRESULT = -2147220946i32;
pub const IMAPI_E_CANNOT_WRITE_TO_MEDIA: ::windows_sys::core::HRESULT = -2147220948i32;
pub const IMAPI_E_COMPRESSEDSTASH: ::windows_sys::core::HRESULT = -2147220952i32;
pub const IMAPI_E_DEVICE_INVALIDTYPE: ::windows_sys::core::HRESULT = -2147220972i32;
pub const IMAPI_E_DEVICE_NOPROPERTIES: ::windows_sys::core::HRESULT = -2147220975i32;
pub const IMAPI_E_DEVICE_NOTACCESSIBLE: ::windows_sys::core::HRESULT = -2147220974i32;
pub const IMAPI_E_DEVICE_NOTPRESENT: ::windows_sys::core::HRESULT = -2147220973i32;
pub const IMAPI_E_DEVICE_STILL_IN_USE: ::windows_sys::core::HRESULT = -2147220954i32;
pub const IMAPI_E_DISCFULL: ::windows_sys::core::HRESULT = -2147220964i32;
pub const IMAPI_E_DISCINFO: ::windows_sys::core::HRESULT = -2147220967i32;
pub const IMAPI_E_ENCRYPTEDSTASH: ::windows_sys::core::HRESULT = -2147220951i32;
pub const IMAPI_E_FILEACCESS: ::windows_sys::core::HRESULT = -2147220968i32;
pub const IMAPI_E_FILEEXISTS: ::windows_sys::core::HRESULT = -2147220956i32;
pub const IMAPI_E_FILESYSTEM: ::windows_sys::core::HRESULT = -2147220969i32;
pub const IMAPI_E_GENERIC: ::windows_sys::core::HRESULT = -2147220978i32;
pub const IMAPI_E_INITIALIZE_ENDWRITE: ::windows_sys::core::HRESULT = -2147220970i32;
pub const IMAPI_E_INITIALIZE_WRITE: ::windows_sys::core::HRESULT = -2147220971i32;
pub const IMAPI_E_INVALIDIMAGE: ::windows_sys::core::HRESULT = -2147220962i32;
pub const IMAPI_E_LOSS_OF_STREAMING: ::windows_sys::core::HRESULT = -2147220953i32;
pub const IMAPI_E_MEDIUM_INVALIDTYPE: ::windows_sys::core::HRESULT = -2147220976i32;
pub const IMAPI_E_MEDIUM_NOTPRESENT: ::windows_sys::core::HRESULT = -2147220977i32;
pub const IMAPI_E_NOACTIVEFORMAT: ::windows_sys::core::HRESULT = -2147220961i32;
pub const IMAPI_E_NOACTIVERECORDER: ::windows_sys::core::HRESULT = -2147220960i32;
pub const IMAPI_E_NOTENOUGHDISKFORSTASH: ::windows_sys::core::HRESULT = -2147220950i32;
pub const IMAPI_E_NOTINITIALIZED: ::windows_sys::core::HRESULT = -2147220980i32;
pub const IMAPI_E_NOTOPENED: ::windows_sys::core::HRESULT = -2147220981i32;
pub const IMAPI_E_REMOVABLESTASH: ::windows_sys::core::HRESULT = -2147220949i32;
pub const IMAPI_E_STASHINUSE: ::windows_sys::core::HRESULT = -2147220955i32;
pub const IMAPI_E_TRACKNOTOPEN: ::windows_sys::core::HRESULT = -2147220966i32;
pub const IMAPI_E_TRACKOPEN: ::windows_sys::core::HRESULT = -2147220965i32;
pub const IMAPI_E_TRACK_NOT_BIG_ENOUGH: ::windows_sys::core::HRESULT = -2147220947i32;
pub const IMAPI_E_USERABORT: ::windows_sys::core::HRESULT = -2147220979i32;
pub const IMAPI_E_WRONGDISC: ::windows_sys::core::HRESULT = -2147220957i32;
pub const IMAPI_E_WRONGFORMAT: ::windows_sys::core::HRESULT = -2147220959i32;
pub type IMAPI_FEATURE_PAGE_TYPE = i32;
pub const IMAPI_FEATURE_PAGE_TYPE_PROFILE_LIST: IMAPI_FEATURE_PAGE_TYPE = 0i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CORE: IMAPI_FEATURE_PAGE_TYPE = 1i32;
pub const IMAPI_FEATURE_PAGE_TYPE_MORPHING: IMAPI_FEATURE_PAGE_TYPE = 2i32;
pub const IMAPI_FEATURE_PAGE_TYPE_REMOVABLE_MEDIUM: IMAPI_FEATURE_PAGE_TYPE = 3i32;
pub const IMAPI_FEATURE_PAGE_TYPE_WRITE_PROTECT: IMAPI_FEATURE_PAGE_TYPE = 4i32;
pub const IMAPI_FEATURE_PAGE_TYPE_RANDOMLY_READABLE: IMAPI_FEATURE_PAGE_TYPE = 16i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CD_MULTIREAD: IMAPI_FEATURE_PAGE_TYPE = 29i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CD_READ: IMAPI_FEATURE_PAGE_TYPE = 30i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DVD_READ: IMAPI_FEATURE_PAGE_TYPE = 31i32;
pub const IMAPI_FEATURE_PAGE_TYPE_RANDOMLY_WRITABLE: IMAPI_FEATURE_PAGE_TYPE = 32i32;
pub const IMAPI_FEATURE_PAGE_TYPE_INCREMENTAL_STREAMING_WRITABLE: IMAPI_FEATURE_PAGE_TYPE = 33i32;
pub const IMAPI_FEATURE_PAGE_TYPE_SECTOR_ERASABLE: IMAPI_FEATURE_PAGE_TYPE = 34i32;
pub const IMAPI_FEATURE_PAGE_TYPE_FORMATTABLE: IMAPI_FEATURE_PAGE_TYPE = 35i32;
pub const IMAPI_FEATURE_PAGE_TYPE_HARDWARE_DEFECT_MANAGEMENT: IMAPI_FEATURE_PAGE_TYPE = 36i32;
pub const IMAPI_FEATURE_PAGE_TYPE_WRITE_ONCE: IMAPI_FEATURE_PAGE_TYPE = 37i32;
pub const IMAPI_FEATURE_PAGE_TYPE_RESTRICTED_OVERWRITE: IMAPI_FEATURE_PAGE_TYPE = 38i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CDRW_CAV_WRITE: IMAPI_FEATURE_PAGE_TYPE = 39i32;
pub const IMAPI_FEATURE_PAGE_TYPE_MRW: IMAPI_FEATURE_PAGE_TYPE = 40i32;
pub const IMAPI_FEATURE_PAGE_TYPE_ENHANCED_DEFECT_REPORTING: IMAPI_FEATURE_PAGE_TYPE = 41i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DVD_PLUS_RW: IMAPI_FEATURE_PAGE_TYPE = 42i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DVD_PLUS_R: IMAPI_FEATURE_PAGE_TYPE = 43i32;
pub const IMAPI_FEATURE_PAGE_TYPE_RIGID_RESTRICTED_OVERWRITE: IMAPI_FEATURE_PAGE_TYPE = 44i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CD_TRACK_AT_ONCE: IMAPI_FEATURE_PAGE_TYPE = 45i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CD_MASTERING: IMAPI_FEATURE_PAGE_TYPE = 46i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DVD_DASH_WRITE: IMAPI_FEATURE_PAGE_TYPE = 47i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DOUBLE_DENSITY_CD_READ: IMAPI_FEATURE_PAGE_TYPE = 48i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DOUBLE_DENSITY_CD_R_WRITE: IMAPI_FEATURE_PAGE_TYPE = 49i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DOUBLE_DENSITY_CD_RW_WRITE: IMAPI_FEATURE_PAGE_TYPE = 50i32;
pub const IMAPI_FEATURE_PAGE_TYPE_LAYER_JUMP_RECORDING: IMAPI_FEATURE_PAGE_TYPE = 51i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CD_RW_MEDIA_WRITE_SUPPORT: IMAPI_FEATURE_PAGE_TYPE = 55i32;
pub const IMAPI_FEATURE_PAGE_TYPE_BD_PSEUDO_OVERWRITE: IMAPI_FEATURE_PAGE_TYPE = 56i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DVD_PLUS_R_DUAL_LAYER: IMAPI_FEATURE_PAGE_TYPE = 59i32;
pub const IMAPI_FEATURE_PAGE_TYPE_BD_READ: IMAPI_FEATURE_PAGE_TYPE = 64i32;
pub const IMAPI_FEATURE_PAGE_TYPE_BD_WRITE: IMAPI_FEATURE_PAGE_TYPE = 65i32;
pub const IMAPI_FEATURE_PAGE_TYPE_HD_DVD_READ: IMAPI_FEATURE_PAGE_TYPE = 80i32;
pub const IMAPI_FEATURE_PAGE_TYPE_HD_DVD_WRITE: IMAPI_FEATURE_PAGE_TYPE = 81i32;
pub const IMAPI_FEATURE_PAGE_TYPE_POWER_MANAGEMENT: IMAPI_FEATURE_PAGE_TYPE = 256i32;
pub const IMAPI_FEATURE_PAGE_TYPE_SMART: IMAPI_FEATURE_PAGE_TYPE = 257i32;
pub const IMAPI_FEATURE_PAGE_TYPE_EMBEDDED_CHANGER: IMAPI_FEATURE_PAGE_TYPE = 258i32;
pub const IMAPI_FEATURE_PAGE_TYPE_CD_ANALOG_PLAY: IMAPI_FEATURE_PAGE_TYPE = 259i32;
pub const IMAPI_FEATURE_PAGE_TYPE_MICROCODE_UPDATE: IMAPI_FEATURE_PAGE_TYPE = 260i32;
pub const IMAPI_FEATURE_PAGE_TYPE_TIMEOUT: IMAPI_FEATURE_PAGE_TYPE = 261i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DVD_CSS: IMAPI_FEATURE_PAGE_TYPE = 262i32;
pub const IMAPI_FEATURE_PAGE_TYPE_REAL_TIME_STREAMING: IMAPI_FEATURE_PAGE_TYPE = 263i32;
pub const IMAPI_FEATURE_PAGE_TYPE_LOGICAL_UNIT_SERIAL_NUMBER: IMAPI_FEATURE_PAGE_TYPE = 264i32;
pub const IMAPI_FEATURE_PAGE_TYPE_MEDIA_SERIAL_NUMBER: IMAPI_FEATURE_PAGE_TYPE = 265i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DISC_CONTROL_BLOCKS: IMAPI_FEATURE_PAGE_TYPE = 266i32;
pub const IMAPI_FEATURE_PAGE_TYPE_DVD_CPRM: IMAPI_FEATURE_PAGE_TYPE = 267i32;
pub const IMAPI_FEATURE_PAGE_TYPE_FIRMWARE_INFORMATION: IMAPI_FEATURE_PAGE_TYPE = 268i32;
pub const IMAPI_FEATURE_PAGE_TYPE_AACS: IMAPI_FEATURE_PAGE_TYPE = 269i32;
pub const IMAPI_FEATURE_PAGE_TYPE_VCPS: IMAPI_FEATURE_PAGE_TYPE = 272i32;
pub type IMAPI_FORMAT2_DATA_MEDIA_STATE = i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_UNKNOWN: IMAPI_FORMAT2_DATA_MEDIA_STATE = 0i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_INFORMATIONAL_MASK: IMAPI_FORMAT2_DATA_MEDIA_STATE = 15i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_UNSUPPORTED_MASK: IMAPI_FORMAT2_DATA_MEDIA_STATE = 64512i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_OVERWRITE_ONLY: IMAPI_FORMAT2_DATA_MEDIA_STATE = 1i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_RANDOMLY_WRITABLE: IMAPI_FORMAT2_DATA_MEDIA_STATE = 1i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_BLANK: IMAPI_FORMAT2_DATA_MEDIA_STATE = 2i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_APPENDABLE: IMAPI_FORMAT2_DATA_MEDIA_STATE = 4i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_FINAL_SESSION: IMAPI_FORMAT2_DATA_MEDIA_STATE = 8i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_DAMAGED: IMAPI_FORMAT2_DATA_MEDIA_STATE = 1024i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_ERASE_REQUIRED: IMAPI_FORMAT2_DATA_MEDIA_STATE = 2048i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_NON_EMPTY_SESSION: IMAPI_FORMAT2_DATA_MEDIA_STATE = 4096i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_WRITE_PROTECTED: IMAPI_FORMAT2_DATA_MEDIA_STATE = 8192i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_FINALIZED: IMAPI_FORMAT2_DATA_MEDIA_STATE = 16384i32;
pub const IMAPI_FORMAT2_DATA_MEDIA_STATE_UNSUPPORTED_MEDIA: IMAPI_FORMAT2_DATA_MEDIA_STATE = 32768i32;
pub type IMAPI_FORMAT2_DATA_WRITE_ACTION = i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_VALIDATING_MEDIA: IMAPI_FORMAT2_DATA_WRITE_ACTION = 0i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_FORMATTING_MEDIA: IMAPI_FORMAT2_DATA_WRITE_ACTION = 1i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_INITIALIZING_HARDWARE: IMAPI_FORMAT2_DATA_WRITE_ACTION = 2i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_CALIBRATING_POWER: IMAPI_FORMAT2_DATA_WRITE_ACTION = 3i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_WRITING_DATA: IMAPI_FORMAT2_DATA_WRITE_ACTION = 4i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_FINALIZATION: IMAPI_FORMAT2_DATA_WRITE_ACTION = 5i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_COMPLETED: IMAPI_FORMAT2_DATA_WRITE_ACTION = 6i32;
pub const IMAPI_FORMAT2_DATA_WRITE_ACTION_VERIFYING: IMAPI_FORMAT2_DATA_WRITE_ACTION = 7i32;
pub type IMAPI_FORMAT2_RAW_CD_DATA_SECTOR_TYPE = i32;
pub const IMAPI_FORMAT2_RAW_CD_SUBCODE_PQ_ONLY: IMAPI_FORMAT2_RAW_CD_DATA_SECTOR_TYPE = 1i32;
pub const IMAPI_FORMAT2_RAW_CD_SUBCODE_IS_COOKED: IMAPI_FORMAT2_RAW_CD_DATA_SECTOR_TYPE = 2i32;
pub const IMAPI_FORMAT2_RAW_CD_SUBCODE_IS_RAW: IMAPI_FORMAT2_RAW_CD_DATA_SECTOR_TYPE = 3i32;
pub type IMAPI_FORMAT2_RAW_CD_WRITE_ACTION = i32;
pub const IMAPI_FORMAT2_RAW_CD_WRITE_ACTION_UNKNOWN: IMAPI_FORMAT2_RAW_CD_WRITE_ACTION = 0i32;
pub const IMAPI_FORMAT2_RAW_CD_WRITE_ACTION_PREPARING: IMAPI_FORMAT2_RAW_CD_WRITE_ACTION = 1i32;
pub const IMAPI_FORMAT2_RAW_CD_WRITE_ACTION_WRITING: IMAPI_FORMAT2_RAW_CD_WRITE_ACTION = 2i32;
pub const IMAPI_FORMAT2_RAW_CD_WRITE_ACTION_FINISHING: IMAPI_FORMAT2_RAW_CD_WRITE_ACTION = 3i32;
pub type IMAPI_FORMAT2_TAO_WRITE_ACTION = i32;
pub const IMAPI_FORMAT2_TAO_WRITE_ACTION_UNKNOWN: IMAPI_FORMAT2_TAO_WRITE_ACTION = 0i32;
pub const IMAPI_FORMAT2_TAO_WRITE_ACTION_PREPARING: IMAPI_FORMAT2_TAO_WRITE_ACTION = 1i32;
pub const IMAPI_FORMAT2_TAO_WRITE_ACTION_WRITING: IMAPI_FORMAT2_TAO_WRITE_ACTION = 2i32;
pub const IMAPI_FORMAT2_TAO_WRITE_ACTION_FINISHING: IMAPI_FORMAT2_TAO_WRITE_ACTION = 3i32;
pub const IMAPI_FORMAT2_TAO_WRITE_ACTION_VERIFYING: IMAPI_FORMAT2_TAO_WRITE_ACTION = 4i32;
pub type IMAPI_MEDIA_PHYSICAL_TYPE = i32;
pub const IMAPI_MEDIA_TYPE_UNKNOWN: IMAPI_MEDIA_PHYSICAL_TYPE = 0i32;
pub const IMAPI_MEDIA_TYPE_CDROM: IMAPI_MEDIA_PHYSICAL_TYPE = 1i32;
pub const IMAPI_MEDIA_TYPE_CDR: IMAPI_MEDIA_PHYSICAL_TYPE = 2i32;
pub const IMAPI_MEDIA_TYPE_CDRW: IMAPI_MEDIA_PHYSICAL_TYPE = 3i32;
pub const IMAPI_MEDIA_TYPE_DVDROM: IMAPI_MEDIA_PHYSICAL_TYPE = 4i32;
pub const IMAPI_MEDIA_TYPE_DVDRAM: IMAPI_MEDIA_PHYSICAL_TYPE = 5i32;
pub const IMAPI_MEDIA_TYPE_DVDPLUSR: IMAPI_MEDIA_PHYSICAL_TYPE = 6i32;
pub const IMAPI_MEDIA_TYPE_DVDPLUSRW: IMAPI_MEDIA_PHYSICAL_TYPE = 7i32;
pub const IMAPI_MEDIA_TYPE_DVDPLUSR_DUALLAYER: IMAPI_MEDIA_PHYSICAL_TYPE = 8i32;
pub const IMAPI_MEDIA_TYPE_DVDDASHR: IMAPI_MEDIA_PHYSICAL_TYPE = 9i32;
pub const IMAPI_MEDIA_TYPE_DVDDASHRW: IMAPI_MEDIA_PHYSICAL_TYPE = 10i32;
pub const IMAPI_MEDIA_TYPE_DVDDASHR_DUALLAYER: IMAPI_MEDIA_PHYSICAL_TYPE = 11i32;
pub const IMAPI_MEDIA_TYPE_DISK: IMAPI_MEDIA_PHYSICAL_TYPE = 12i32;
pub const IMAPI_MEDIA_TYPE_DVDPLUSRW_DUALLAYER: IMAPI_MEDIA_PHYSICAL_TYPE = 13i32;
pub const IMAPI_MEDIA_TYPE_HDDVDROM: IMAPI_MEDIA_PHYSICAL_TYPE = 14i32;
pub const IMAPI_MEDIA_TYPE_HDDVDR: IMAPI_MEDIA_PHYSICAL_TYPE = 15i32;
pub const IMAPI_MEDIA_TYPE_HDDVDRAM: IMAPI_MEDIA_PHYSICAL_TYPE = 16i32;
pub const IMAPI_MEDIA_TYPE_BDROM: IMAPI_MEDIA_PHYSICAL_TYPE = 17i32;
pub const IMAPI_MEDIA_TYPE_BDR: IMAPI_MEDIA_PHYSICAL_TYPE = 18i32;
pub const IMAPI_MEDIA_TYPE_BDRE: IMAPI_MEDIA_PHYSICAL_TYPE = 19i32;
pub const IMAPI_MEDIA_TYPE_MAX: IMAPI_MEDIA_PHYSICAL_TYPE = 19i32;
pub type IMAPI_MEDIA_WRITE_PROTECT_STATE = i32;
pub const IMAPI_WRITEPROTECTED_UNTIL_POWERDOWN: IMAPI_MEDIA_WRITE_PROTECT_STATE = 1i32;
pub const IMAPI_WRITEPROTECTED_BY_CARTRIDGE: IMAPI_MEDIA_WRITE_PROTECT_STATE = 2i32;
pub const IMAPI_WRITEPROTECTED_BY_MEDIA_SPECIFIC_REASON: IMAPI_MEDIA_WRITE_PROTECT_STATE = 4i32;
pub const IMAPI_WRITEPROTECTED_BY_SOFTWARE_WRITE_PROTECT: IMAPI_MEDIA_WRITE_PROTECT_STATE = 8i32;
pub const IMAPI_WRITEPROTECTED_BY_DISC_CONTROL_BLOCK: IMAPI_MEDIA_WRITE_PROTECT_STATE = 16i32;
pub const IMAPI_WRITEPROTECTED_READ_ONLY_MEDIA: IMAPI_MEDIA_WRITE_PROTECT_STATE = 16384i32;
pub type IMAPI_MODE_PAGE_REQUEST_TYPE = i32;
pub const IMAPI_MODE_PAGE_REQUEST_TYPE_CURRENT_VALUES: IMAPI_MODE_PAGE_REQUEST_TYPE = 0i32;
pub const IMAPI_MODE_PAGE_REQUEST_TYPE_CHANGEABLE_VALUES: IMAPI_MODE_PAGE_REQUEST_TYPE = 1i32;
pub const IMAPI_MODE_PAGE_REQUEST_TYPE_DEFAULT_VALUES: IMAPI_MODE_PAGE_REQUEST_TYPE = 2i32;
pub const IMAPI_MODE_PAGE_REQUEST_TYPE_SAVED_VALUES: IMAPI_MODE_PAGE_REQUEST_TYPE = 3i32;
pub type IMAPI_MODE_PAGE_TYPE = i32;
pub const IMAPI_MODE_PAGE_TYPE_READ_WRITE_ERROR_RECOVERY: IMAPI_MODE_PAGE_TYPE = 1i32;
pub const IMAPI_MODE_PAGE_TYPE_MRW: IMAPI_MODE_PAGE_TYPE = 3i32;
pub const IMAPI_MODE_PAGE_TYPE_WRITE_PARAMETERS: IMAPI_MODE_PAGE_TYPE = 5i32;
pub const IMAPI_MODE_PAGE_TYPE_CACHING: IMAPI_MODE_PAGE_TYPE = 8i32;
pub const IMAPI_MODE_PAGE_TYPE_INFORMATIONAL_EXCEPTIONS: IMAPI_MODE_PAGE_TYPE = 28i32;
pub const IMAPI_MODE_PAGE_TYPE_TIMEOUT_AND_PROTECT: IMAPI_MODE_PAGE_TYPE = 29i32;
pub const IMAPI_MODE_PAGE_TYPE_POWER_CONDITION: IMAPI_MODE_PAGE_TYPE = 26i32;
pub const IMAPI_MODE_PAGE_TYPE_LEGACY_CAPABILITIES: IMAPI_MODE_PAGE_TYPE = 42i32;
pub type IMAPI_PROFILE_TYPE = i32;
pub const IMAPI_PROFILE_TYPE_INVALID: IMAPI_PROFILE_TYPE = 0i32;
pub const IMAPI_PROFILE_TYPE_NON_REMOVABLE_DISK: IMAPI_PROFILE_TYPE = 1i32;
pub const IMAPI_PROFILE_TYPE_REMOVABLE_DISK: IMAPI_PROFILE_TYPE = 2i32;
pub const IMAPI_PROFILE_TYPE_MO_ERASABLE: IMAPI_PROFILE_TYPE = 3i32;
pub const IMAPI_PROFILE_TYPE_MO_WRITE_ONCE: IMAPI_PROFILE_TYPE = 4i32;
pub const IMAPI_PROFILE_TYPE_AS_MO: IMAPI_PROFILE_TYPE = 5i32;
pub const IMAPI_PROFILE_TYPE_CDROM: IMAPI_PROFILE_TYPE = 8i32;
pub const IMAPI_PROFILE_TYPE_CD_RECORDABLE: IMAPI_PROFILE_TYPE = 9i32;
pub const IMAPI_PROFILE_TYPE_CD_REWRITABLE: IMAPI_PROFILE_TYPE = 10i32;
pub const IMAPI_PROFILE_TYPE_DVDROM: IMAPI_PROFILE_TYPE = 16i32;
pub const IMAPI_PROFILE_TYPE_DVD_DASH_RECORDABLE: IMAPI_PROFILE_TYPE = 17i32;
pub const IMAPI_PROFILE_TYPE_DVD_RAM: IMAPI_PROFILE_TYPE = 18i32;
pub const IMAPI_PROFILE_TYPE_DVD_DASH_REWRITABLE: IMAPI_PROFILE_TYPE = 19i32;
pub const IMAPI_PROFILE_TYPE_DVD_DASH_RW_SEQUENTIAL: IMAPI_PROFILE_TYPE = 20i32;
pub const IMAPI_PROFILE_TYPE_DVD_DASH_R_DUAL_SEQUENTIAL: IMAPI_PROFILE_TYPE = 21i32;
pub const IMAPI_PROFILE_TYPE_DVD_DASH_R_DUAL_LAYER_JUMP: IMAPI_PROFILE_TYPE = 22i32;
pub const IMAPI_PROFILE_TYPE_DVD_PLUS_RW: IMAPI_PROFILE_TYPE = 26i32;
pub const IMAPI_PROFILE_TYPE_DVD_PLUS_R: IMAPI_PROFILE_TYPE = 27i32;
pub const IMAPI_PROFILE_TYPE_DDCDROM: IMAPI_PROFILE_TYPE = 32i32;
pub const IMAPI_PROFILE_TYPE_DDCD_RECORDABLE: IMAPI_PROFILE_TYPE = 33i32;
pub const IMAPI_PROFILE_TYPE_DDCD_REWRITABLE: IMAPI_PROFILE_TYPE = 34i32;
pub const IMAPI_PROFILE_TYPE_DVD_PLUS_RW_DUAL: IMAPI_PROFILE_TYPE = 42i32;
pub const IMAPI_PROFILE_TYPE_DVD_PLUS_R_DUAL: IMAPI_PROFILE_TYPE = 43i32;
pub const IMAPI_PROFILE_TYPE_BD_ROM: IMAPI_PROFILE_TYPE = 64i32;
pub const IMAPI_PROFILE_TYPE_BD_R_SEQUENTIAL: IMAPI_PROFILE_TYPE = 65i32;
pub const IMAPI_PROFILE_TYPE_BD_R_RANDOM_RECORDING: IMAPI_PROFILE_TYPE = 66i32;
pub const IMAPI_PROFILE_TYPE_BD_REWRITABLE: IMAPI_PROFILE_TYPE = 67i32;
pub const IMAPI_PROFILE_TYPE_HD_DVD_ROM: IMAPI_PROFILE_TYPE = 80i32;
pub const IMAPI_PROFILE_TYPE_HD_DVD_RECORDABLE: IMAPI_PROFILE_TYPE = 81i32;
pub const IMAPI_PROFILE_TYPE_HD_DVD_RAM: IMAPI_PROFILE_TYPE = 82i32;
pub const IMAPI_PROFILE_TYPE_NON_STANDARD: IMAPI_PROFILE_TYPE = 65535i32;
pub type IMAPI_READ_TRACK_ADDRESS_TYPE = i32;
pub const IMAPI_READ_TRACK_ADDRESS_TYPE_LBA: IMAPI_READ_TRACK_ADDRESS_TYPE = 0i32;
pub const IMAPI_READ_TRACK_ADDRESS_TYPE_TRACK: IMAPI_READ_TRACK_ADDRESS_TYPE = 1i32;
pub const IMAPI_READ_TRACK_ADDRESS_TYPE_SESSION: IMAPI_READ_TRACK_ADDRESS_TYPE = 2i32;
pub const IMAPI_SECTORS_PER_SECOND_AT_1X_BD: u32 = 2195u32;
pub const IMAPI_SECTORS_PER_SECOND_AT_1X_CD: u32 = 75u32;
pub const IMAPI_SECTORS_PER_SECOND_AT_1X_DVD: u32 = 680u32;
pub const IMAPI_SECTORS_PER_SECOND_AT_1X_HD_DVD: u32 = 4568u32;
pub const IMAPI_SECTOR_SIZE: u32 = 2048u32;
pub const IMAPI_S_BUFFER_TO_SMALL: ::windows_sys::core::HRESULT = 262657i32;
pub const IMAPI_S_PROPERTIESIGNORED: ::windows_sys::core::HRESULT = 262656i32;
pub type IMMPID_CPV_ENUM = i32;
pub const IMMPID_CPV_BEFORE__: IMMPID_CPV_ENUM = 32767i32;
pub const IMMPID_CP_START: IMMPID_CPV_ENUM = 32768i32;
pub const IMMPID_CPV_AFTER__: IMMPID_CPV_ENUM = 32769i32;
pub type IMMPID_MPV_ENUM = i32;
pub const IMMPID_MPV_BEFORE__: IMMPID_MPV_ENUM = 12287i32;
pub const IMMPID_MPV_STORE_DRIVER_HANDLE: IMMPID_MPV_ENUM = 12288i32;
pub const IMMPID_MPV_MESSAGE_CREATION_FLAGS: IMMPID_MPV_ENUM = 12289i32;
pub const IMMPID_MPV_MESSAGE_OPEN_HANDLES: IMMPID_MPV_ENUM = 12290i32;
pub const IMMPID_MPV_TOTAL_OPEN_HANDLES: IMMPID_MPV_ENUM = 12291i32;
pub const IMMPID_MPV_TOTAL_OPEN_PROPERTY_STREAM_HANDLES: IMMPID_MPV_ENUM = 12292i32;
pub const IMMPID_MPV_TOTAL_OPEN_CONTENT_HANDLES: IMMPID_MPV_ENUM = 12293i32;
pub const IMMPID_MPV_AFTER__: IMMPID_MPV_ENUM = 12294i32;
pub type IMMPID_MP_ENUM = i32;
pub const IMMPID_MP_BEFORE__: IMMPID_MP_ENUM = 4095i32;
pub const IMMPID_MP_RECIPIENT_LIST: IMMPID_MP_ENUM = 4096i32;
pub const IMMPID_MP_CONTENT_FILE_NAME: IMMPID_MP_ENUM = 4097i32;
pub const IMMPID_MP_SENDER_ADDRESS_SMTP: IMMPID_MP_ENUM = 4098i32;
pub const IMMPID_MP_SENDER_ADDRESS_X500: IMMPID_MP_ENUM = 4099i32;
pub const IMMPID_MP_SENDER_ADDRESS_X400: IMMPID_MP_ENUM = 4100i32;
pub const IMMPID_MP_SENDER_ADDRESS_LEGACY_EX_DN: IMMPID_MP_ENUM = 4101i32;
pub const IMMPID_MP_DOMAIN_LIST: IMMPID_MP_ENUM = 4102i32;
pub const IMMPID_MP_PICKUP_FILE_NAME: IMMPID_MP_ENUM = 4103i32;
pub const IMMPID_MP_AUTHENTICATED_USER_NAME: IMMPID_MP_ENUM = 4104i32;
pub const IMMPID_MP_CONNECTION_IP_ADDRESS: IMMPID_MP_ENUM = 4105i32;
pub const IMMPID_MP_HELO_DOMAIN: IMMPID_MP_ENUM = 4106i32;
pub const IMMPID_MP_EIGHTBIT_MIME_OPTION: IMMPID_MP_ENUM = 4107i32;
pub const IMMPID_MP_CHUNKING_OPTION: IMMPID_MP_ENUM = 4108i32;
pub const IMMPID_MP_BINARYMIME_OPTION: IMMPID_MP_ENUM = 4109i32;
pub const IMMPID_MP_REMOTE_AUTHENTICATION_TYPE: IMMPID_MP_ENUM = 4110i32;
pub const IMMPID_MP_ERROR_CODE: IMMPID_MP_ENUM = 4111i32;
pub const IMMPID_MP_DSN_ENVID_VALUE: IMMPID_MP_ENUM = 4112i32;
pub const IMMPID_MP_DSN_RET_VALUE: IMMPID_MP_ENUM = 4113i32;
pub const IMMPID_MP_REMOTE_SERVER_DSN_CAPABLE: IMMPID_MP_ENUM = 4114i32;
pub const IMMPID_MP_ARRIVAL_TIME: IMMPID_MP_ENUM = 4115i32;
pub const IMMPID_MP_MESSAGE_STATUS: IMMPID_MP_ENUM = 4116i32;
pub const IMMPID_MP_EXPIRE_DELAY: IMMPID_MP_ENUM = 4117i32;
pub const IMMPID_MP_EXPIRE_NDR: IMMPID_MP_ENUM = 4118i32;
pub const IMMPID_MP_LOCAL_EXPIRE_DELAY: IMMPID_MP_ENUM = 4119i32;
pub const IMMPID_MP_LOCAL_EXPIRE_NDR: IMMPID_MP_ENUM = 4120i32;
pub const IMMPID_MP_ARRIVAL_FILETIME: IMMPID_MP_ENUM = 4121i32;
pub const IMMPID_MP_HR_CAT_STATUS: IMMPID_MP_ENUM = 4122i32;
pub const IMMPID_MP_MSG_GUID: IMMPID_MP_ENUM = 4123i32;
pub const IMMPID_MP_SUPERSEDES_MSG_GUID: IMMPID_MP_ENUM = 4124i32;
pub const IMMPID_MP_SCANNED_FOR_CRLF_DOT_CRLF: IMMPID_MP_ENUM = 4125i32;
pub const IMMPID_MP_FOUND_EMBEDDED_CRLF_DOT_CRLF: IMMPID_MP_ENUM = 4126i32;
pub const IMMPID_MP_MSG_SIZE_HINT: IMMPID_MP_ENUM = 4127i32;
pub const IMMPID_MP_RFC822_MSG_ID: IMMPID_MP_ENUM = 4128i32;
pub const IMMPID_MP_RFC822_MSG_SUBJECT: IMMPID_MP_ENUM = 4129i32;
pub const IMMPID_MP_RFC822_FROM_ADDRESS: IMMPID_MP_ENUM = 4130i32;
pub const IMMPID_MP_RFC822_TO_ADDRESS: IMMPID_MP_ENUM = 4131i32;
pub const IMMPID_MP_RFC822_CC_ADDRESS: IMMPID_MP_ENUM = 4132i32;
pub const IMMPID_MP_RFC822_BCC_ADDRESS: IMMPID_MP_ENUM = 4133i32;
pub const IMMPID_MP_CONNECTION_SERVER_IP_ADDRESS: IMMPID_MP_ENUM = 4134i32;
pub const IMMPID_MP_SERVER_NAME: IMMPID_MP_ENUM = 4135i32;
pub const IMMPID_MP_SERVER_VERSION: IMMPID_MP_ENUM = 4136i32;
pub const IMMPID_MP_NUM_RECIPIENTS: IMMPID_MP_ENUM = 4137i32;
pub const IMMPID_MP_X_PRIORITY: IMMPID_MP_ENUM = 4138i32;
pub const IMMPID_MP_FROM_ADDRESS: IMMPID_MP_ENUM = 4139i32;
pub const IMMPID_MP_SENDER_ADDRESS: IMMPID_MP_ENUM = 4140i32;
pub const IMMPID_MP_DEFERRED_DELIVERY_FILETIME: IMMPID_MP_ENUM = 4141i32;
pub const IMMPID_MP_SENDER_ADDRESS_OTHER: IMMPID_MP_ENUM = 4142i32;
pub const IMMPID_MP_ORIGINAL_ARRIVAL_TIME: IMMPID_MP_ENUM = 4143i32;
pub const IMMPID_MP_MSGCLASS: IMMPID_MP_ENUM = 4144i32;
pub const IMMPID_MP_CONTENT_TYPE: IMMPID_MP_ENUM = 4145i32;
pub const IMMPID_MP_ENCRYPTION_TYPE: IMMPID_MP_ENUM = 4146i32;
pub const IMMPID_MP_CONNECTION_SERVER_PORT: IMMPID_MP_ENUM = 4147i32;
pub const IMMPID_MP_CLIENT_AUTH_USER: IMMPID_MP_ENUM = 4148i32;
pub const IMMPID_MP_CLIENT_AUTH_TYPE: IMMPID_MP_ENUM = 4149i32;
pub const IMMPID_MP_CRC_GLOBAL: IMMPID_MP_ENUM = 4150i32;
pub const IMMPID_MP_CRC_RECIPS: IMMPID_MP_ENUM = 4151i32;
pub const IMMPID_MP_INBOUND_MAIL_FROM_AUTH: IMMPID_MP_ENUM = 4152i32;
pub const IMMPID_MP_AFTER__: IMMPID_MP_ENUM = 4153i32;
pub type IMMPID_NMP_ENUM = i32;
pub const IMMPID_NMP_BEFORE__: IMMPID_NMP_ENUM = 24575i32;
pub const IMMPID_NMP_SECONDARY_GROUPS: IMMPID_NMP_ENUM = 24576i32;
pub const IMMPID_NMP_SECONDARY_ARTNUM: IMMPID_NMP_ENUM = 24577i32;
pub const IMMPID_NMP_PRIMARY_GROUP: IMMPID_NMP_ENUM = 24578i32;
pub const IMMPID_NMP_PRIMARY_ARTID: IMMPID_NMP_ENUM = 24579i32;
pub const IMMPID_NMP_POST_TOKEN: IMMPID_NMP_ENUM = 24580i32;
pub const IMMPID_NMP_NEWSGROUP_LIST: IMMPID_NMP_ENUM = 24581i32;
pub const IMMPID_NMP_HEADERS: IMMPID_NMP_ENUM = 24582i32;
pub const IMMPID_NMP_NNTP_PROCESSING: IMMPID_NMP_ENUM = 24583i32;
pub const IMMPID_NMP_NNTP_APPROVED_HEADER: IMMPID_NMP_ENUM = 24584i32;
pub const IMMPID_NMP_AFTER__: IMMPID_NMP_ENUM = 24585i32;
pub type IMMPID_RPV_ENUM = i32;
pub const IMMPID_RPV_BEFORE__: IMMPID_RPV_ENUM = 16383i32;
pub const IMMPID_RPV_DONT_DELIVER: IMMPID_RPV_ENUM = 16384i32;
pub const IMMPID_RPV_NO_NAME_COLLISIONS: IMMPID_RPV_ENUM = 16385i32;
pub const IMMPID_RPV_AFTER__: IMMPID_RPV_ENUM = 16386i32;
pub type IMMPID_RP_ENUM = i32;
pub const IMMPID_RP_BEFORE__: IMMPID_RP_ENUM = 8191i32;
pub const IMMPID_RP_DSN_NOTIFY_SUCCESS: IMMPID_RP_ENUM = 8192i32;
pub const IMMPID_RP_DSN_NOTIFY_INVALID: IMMPID_RP_ENUM = 8193i32;
pub const IMMPID_RP_ADDRESS_TYPE: IMMPID_RP_ENUM = 8194i32;
pub const IMMPID_RP_ADDRESS: IMMPID_RP_ENUM = 8195i32;
pub const IMMPID_RP_ADDRESS_TYPE_SMTP: IMMPID_RP_ENUM = 8196i32;
pub const IMMPID_RP_ERROR_CODE: IMMPID_RP_ENUM = 8197i32;
pub const IMMPID_RP_ERROR_STRING: IMMPID_RP_ENUM = 8198i32;
pub const IMMPID_RP_DSN_NOTIFY_VALUE: IMMPID_RP_ENUM = 8199i32;
pub const IMMPID_RP_DSN_ORCPT_VALUE: IMMPID_RP_ENUM = 8200i32;
pub const IMMPID_RP_ADDRESS_SMTP: IMMPID_RP_ENUM = 8201i32;
pub const IMMPID_RP_ADDRESS_X400: IMMPID_RP_ENUM = 8202i32;
pub const IMMPID_RP_ADDRESS_X500: IMMPID_RP_ENUM = 8203i32;
pub const IMMPID_RP_LEGACY_EX_DN: IMMPID_RP_ENUM = 8204i32;
pub const IMMPID_RP_RECIPIENT_FLAGS: IMMPID_RP_ENUM = 8205i32;
pub const IMMPID_RP_SMTP_STATUS_STRING: IMMPID_RP_ENUM = 8206i32;
pub const IMMPID_RP_DSN_PRE_CAT_ADDRESS: IMMPID_RP_ENUM = 8207i32;
pub const IMMPID_RP_MDB_GUID: IMMPID_RP_ENUM = 8208i32;
pub const IMMPID_RP_USER_GUID: IMMPID_RP_ENUM = 8209i32;
pub const IMMPID_RP_DOMAIN: IMMPID_RP_ENUM = 8210i32;
pub const IMMPID_RP_ADDRESS_OTHER: IMMPID_RP_ENUM = 8211i32;
pub const IMMPID_RP_DISPLAY_NAME: IMMPID_RP_ENUM = 8212i32;
pub const IMMPID_RP_AFTER__: IMMPID_RP_ENUM = 8213i32;
#[repr(C)]
pub struct IMMP_MPV_STORE_DRIVER_HANDLE {
pub guidSignature: ::windows_sys::core::GUID,
}
impl ::core::marker::Copy for IMMP_MPV_STORE_DRIVER_HANDLE {}
impl ::core::clone::Clone for IMMP_MPV_STORE_DRIVER_HANDLE {
fn clone(&self) -> Self {
*self
}
}
pub type IMultisession = *mut ::core::ffi::c_void;
pub type IMultisessionRandomWrite = *mut ::core::ffi::c_void;
pub type IMultisessionSequential = *mut ::core::ffi::c_void;
pub type IMultisessionSequential2 = *mut ::core::ffi::c_void;
pub type IProgressItem = *mut ::core::ffi::c_void;
pub type IProgressItems = *mut ::core::ffi::c_void;
pub type IRawCDImageCreator = *mut ::core::ffi::c_void;
pub type IRawCDImageTrackInfo = *mut ::core::ffi::c_void;
pub type IRedbookDiscMaster = *mut ::core::ffi::c_void;
pub type IStreamConcatenate = *mut ::core::ffi::c_void;
pub type IStreamInterleave = *mut ::core::ffi::c_void;
pub type IStreamPseudoRandomBased = *mut ::core::ffi::c_void;
pub type IWriteEngine2 = *mut ::core::ffi::c_void;
pub type IWriteEngine2EventArgs = *mut ::core::ffi::c_void;
pub type IWriteSpeedDescriptor = *mut ::core::ffi::c_void;
pub type MEDIA_FLAGS = i32;
pub const MEDIA_BLANK: MEDIA_FLAGS = 1i32;
pub const MEDIA_RW: MEDIA_FLAGS = 2i32;
pub const MEDIA_WRITABLE: MEDIA_FLAGS = 4i32;
pub const MEDIA_FORMAT_UNUSABLE_BY_IMAPI: MEDIA_FLAGS = 8i32;
pub type MEDIA_TYPES = i32;
pub const MEDIA_CDDA_CDROM: MEDIA_TYPES = 1i32;
pub const MEDIA_CD_ROM_XA: MEDIA_TYPES = 2i32;
pub const MEDIA_CD_I: MEDIA_TYPES = 3i32;
pub const MEDIA_CD_EXTRA: MEDIA_TYPES = 4i32;
pub const MEDIA_CD_OTHER: MEDIA_TYPES = 5i32;
pub const MEDIA_SPECIAL: MEDIA_TYPES = 6i32;
pub const MPV_INBOUND_CUTOFF_EXCEEDED: u32 = 1u32;
pub const MPV_WRITE_CONTENT: u32 = 2u32;
pub const MP_MSGCLASS_DELIVERY_REPORT: u32 = 3u32;
pub const MP_MSGCLASS_NONDELIVERY_REPORT: u32 = 4u32;
pub const MP_MSGCLASS_REPLICATION: u32 = 2u32;
pub const MP_MSGCLASS_SYSTEM: u32 = 1u32;
pub const MP_STATUS_ABANDON_DELIVERY: u32 = 6u32;
pub const MP_STATUS_ABORT_DELIVERY: u32 = 2u32;
pub const MP_STATUS_BAD_MAIL: u32 = 3u32;
pub const MP_STATUS_CATEGORIZED: u32 = 5u32;
pub const MP_STATUS_RETRY: u32 = 1u32;
pub const MP_STATUS_SUBMITTED: u32 = 4u32;
pub const MP_STATUS_SUCCESS: u32 = 0u32;
pub const MSDiscMasterObj: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1376569955, data2: 20901, data3: 4563, data4: [145, 68, 0, 16, 75, 161, 28, 94] };
pub const MSDiscRecorderObj: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1376569953, data2: 20901, data3: 4563, data4: [145, 68, 0, 16, 75, 161, 28, 94] };
pub const MSEnumDiscRecordersObj: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2315474554,
data2: 25547,
data3: 19368,
data4: [186, 246, 82, 17, 152, 22, 209, 239],
};
#[cfg(feature = "Win32_System_AddressBook")]
pub type MSGCALLRELEASE = ::core::option::Option<unsafe extern "system" fn(ulcallerdata: u32, lpmessage: super::super::System::AddressBook::IMessage)>;
pub const MsftDiscFormat2Data: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801514, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftDiscFormat2Erase: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801515, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftDiscFormat2RawCD: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801512, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftDiscFormat2TrackAtOnce: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801513, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftDiscMaster2: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801518, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftDiscRecorder2: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801517, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftFileSystemImage: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904965, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const MsftIsoImageManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3471719266,
data2: 36694,
data3: 16470,
data4: [134, 155, 239, 22, 145, 126, 62, 252],
};
pub const MsftMultisessionRandomWrite: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3037186596, data2: 8708, data3: 4573, data4: [150, 106, 0, 26, 160, 27, 188, 88] };
pub const MsftMultisessionSequential: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801506, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftRawCDImageCreator: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 630732129, data2: 40293, data3: 18894, data4: [179, 53, 64, 99, 13, 144, 18, 39] };
pub const MsftStreamConcatenate: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801509, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftStreamInterleave: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801508, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftStreamPrng001: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801510, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftStreamZero: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801511, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftWriteEngine2: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801516, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const MsftWriteSpeedDescriptor: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 657801507, data2: 32612, data3: 23311, data4: [143, 0, 93, 119, 175, 190, 38, 30] };
pub const NMP_PROCESS_CONTROL: u32 = 2u32;
pub const NMP_PROCESS_MODERATOR: u32 = 4u32;
pub const NMP_PROCESS_POST: u32 = 1u32;
pub type PlatformId = i32;
pub const PlatformX86: PlatformId = 0i32;
pub const PlatformPowerPC: PlatformId = 1i32;
pub const PlatformMac: PlatformId = 2i32;
pub const PlatformEFI: PlatformId = 239i32;
pub const ProgressItem: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904971, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub const ProgressItems: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 747904969, data2: 38747, data3: 22974, data4: [169, 96, 154, 42, 38, 40, 83, 165] };
pub type RECORDER_TYPES = i32;
pub const RECORDER_CDR: RECORDER_TYPES = 1i32;
pub const RECORDER_CDRW: RECORDER_TYPES = 2i32;
pub const RP_DELIVERED: u32 = 272u32;
pub const RP_DSN_HANDLED: u32 = 64u32;
pub const RP_DSN_NOTIFY_DELAY: u32 = 67108864u32;
pub const RP_DSN_NOTIFY_FAILURE: u32 = 33554432u32;
pub const RP_DSN_NOTIFY_INVALID: u32 = 0u32;
pub const RP_DSN_NOTIFY_MASK: u32 = 251658240u32;
pub const RP_DSN_NOTIFY_NEVER: u32 = 134217728u32;
pub const RP_DSN_NOTIFY_SUCCESS: u32 = 16777216u32;
pub const RP_DSN_SENT_DELAYED: u32 = 16384u32;
pub const RP_DSN_SENT_DELIVERED: u32 = 131136u32;
pub const RP_DSN_SENT_EXPANDED: u32 = 32832u32;
pub const RP_DSN_SENT_NDR: u32 = 1104u32;
pub const RP_DSN_SENT_RELAYED: u32 = 65600u32;
pub const RP_ENPANDED: u32 = 8208u32;
pub const RP_ERROR_CONTEXT_CAT: u32 = 2097152u32;
pub const RP_ERROR_CONTEXT_MTA: u32 = 4194304u32;
pub const RP_ERROR_CONTEXT_STORE: u32 = 1048576u32;
pub const RP_EXPANDED: u32 = 8208u32;
pub const RP_FAILED: u32 = 2096u32;
pub const RP_GENERAL_FAILURE: u32 = 32u32;
pub const RP_HANDLED: u32 = 16u32;
pub const RP_RECIP_FLAGS_RESERVED: u32 = 15u32;
pub const RP_REMOTE_MTA_NO_DSN: u32 = 524288u32;
pub const RP_UNRESOLVED: u32 = 4144u32;
pub const RP_VOLATILE_FLAGS_MASK: u32 = 4026531840u32;
#[repr(C)]
pub struct SPropAttrArray {
pub cValues: u32,
pub aPropAttr: [u32; 1],
}
impl ::core::marker::Copy for SPropAttrArray {}
impl ::core::clone::Clone for SPropAttrArray {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
pub struct _MSGSESS(pub u8);
pub const tagIMMPID_CPV_STRUCT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2728880938, data2: 58669, data3: 4561, data4: [170, 100, 0, 192, 79, 163, 91, 130] };
#[repr(C)]
pub struct tagIMMPID_GUIDLIST_ITEM {
pub pguid: *mut ::windows_sys::core::GUID,
pub dwStart: u32,
pub dwLast: u32,
}
impl ::core::marker::Copy for tagIMMPID_GUIDLIST_ITEM {}
impl ::core::clone::Clone for tagIMMPID_GUIDLIST_ITEM {
fn clone(&self) -> Self {
*self
}
}
pub const tagIMMPID_MPV_STRUCT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3420886790, data2: 51645, data3: 4561, data4: [159, 242, 0, 192, 79, 163, 115, 72] };
pub const tagIMMPID_MP_STRUCT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 322456816, data2: 46020, data3: 4561, data4: [170, 146, 0, 170, 0, 107, 200, 11] };
pub const tagIMMPID_NMP_STRUCT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1949542826, data2: 8418, data3: 4562, data4: [148, 214, 0, 192, 79, 163, 121, 241] };
pub const tagIMMPID_RPV_STRUCT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2045255753, data2: 54048, data3: 4561, data4: [159, 244, 0, 192, 79, 163, 115, 72] };
pub const tagIMMPID_RP_STRUCT: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2045255752, data2: 54048, data3: 4561, data4: [159, 244, 0, 192, 79, 163, 115, 72] };
|
use proconio::input;
fn main() {
input! {
n: usize,
a: [usize; n],
m: usize,
b: [usize; m],
x: usize,
};
let mut ban = vec![false; x + 1];
for b in b {
ban[b] = true;
}
let mut dp = vec![false; x + 1];
dp[0] = true;
for i in 0..x {
if dp[i] == false {
continue;
}
for &a in &a {
if i + a <= x && ban[i + a] == false {
dp[i + a] = true;
}
}
}
if dp[x] {
println!("Yes");
} else {
println!("No");
}
}
|
use crate::{onTagClose, onTagOpen, ParsingError};
#[derive(Clone, Copy)]
#[repr(C)]
pub enum CustomEventType {
/// Variant that can be used to log various information on the RxPlayer's
/// logger.
///
/// Useful for debugging, for example.
#[allow(dead_code)]
Log = 0,
/// Variant used to report parsing errors to the RxPlayer.
Error = 1,
}
/// `TagName` enumerates parsed XML elements in an MPD.
///
/// Note that not all parsed elements have an entry in `TagName`, the simpler
/// ones might actually have an entry in `AttributeName` instead to simplify
/// the parser's implementation.
#[derive(PartialEq, Clone, Copy)]
#[repr(C)]
#[allow(clippy::upper_case_acronyms)]
pub enum TagName {
/// Indicate an <MPD> node
/// These nodes are usually contained at the root of an MPD.
MPD = 1,
// -- Inside an <MPD> --
/// Indicate a <Period> node
Period = 2,
/// Indicate a <UTCTiming> node
UtcTiming = 3,
// -- Inside a <Period> --
/// Indicate an <AdaptationSet> node
AdaptationSet = 4,
/// Indicate an <EventStream> node
EventStream = 5,
/// Indicate an <Event> node.
/// These nodes are usually contained in <EventStream> elements.
EventStreamElt = 6,
// -- Inside an <AdaptationSet> --
/// Indicate a <Representation> node
Representation = 7,
/// Indicate an <Accessibility> node
Accessibility = 8,
/// Indicate a <ContentComponent> node
ContentComponent = 9,
/// Indicate a <ContentProtection> node
ContentProtection = 10,
/// Indicate an <EssentialProperty> node
EssentialProperty = 11,
/// Indicate a <Role> node
Role = 12,
/// Indicate a <SupplementalProperty> node
SupplementalProperty = 13,
// -- Inside various elements --
/// Indicate a <BaseURL> node
BaseURL = 15,
/// Indicate a <SegmentTemplate> node
SegmentTemplate = 16,
/// Indicate a <SegmentBase> node
SegmentBase = 17,
/// Indicate a <SegmentList> node
SegmentList = 18,
/// Indicate an <InbandEventStream> node
InbandEventStream = 19,
// -- Inside a <SegmentList> --
/// Indicate a <SegmentURL> node
SegmentUrl = 20,
}
#[derive(PartialEq, Clone, Copy)]
#[repr(C)]
pub enum AttributeName {
/// Describes the "id" attribute that can be found in many, many elements.
///
/// It is reported as an UTF-8 sequence of bytes (through a pointer into
/// WebAssembly's memory and length).
///
/// Among the elements concerned:
/// - <MPD>
/// - <Period>
/// - <AdaptationSet>
/// - <Representation>
/// - <ContentComponent>
/// - <Event> (from <EventStream> elements)
Id = 0,
/// Describes the "duration" attribute that can be found in multiple MPD
/// elements.
///
/// It is reported as an f64, for easier JS manipulation.
///
/// The Duration attribute can be found in:
/// - <Period> elements. In that case this value will be reported as a
/// number of seconds.
/// - <SegmentTemplate> elements
/// - <SegmentBase> elements
/// - <Event> elements (from <EventStream> elements)
Duration = 1,
/// Describes the "profiles" attribute, found in `<MPD>` elements.
///
/// It is reported as an UTF-8 sequence of bytes (through a pointer and
/// length into WebAssembly's memory).
Profiles = 2,
// AdaptationSet + Representation
AudioSamplingRate = 3,
Codecs = 4, // String
CodingDependency = 5,
FrameRate = 6,
Height = 7, // f64
Width = 8, // f64
MaxPlayoutRate = 9,
MaxSAPPeriod = 10,
MimeType = 11, // f64
SegmentProfiles = 12,
// ContentProtection
ContentProtectionValue = 13, // String
ContentProtectionKeyId = 14, // ArrayBuffer
ContentProtectionCencPSSH = 15, // ArrayBuffer
// Various schemes (Accessibility) + EventStream + ContentProtection
SchemeIdUri = 16, // String
// Various schemes (Accessibility)
SchemeValue = 17, // String
// SegmentURL
MediaRange = 18, // [f64, f64]
// SegmentTimeline
SegmentTimeline = 19, // Vec<SElement>
// SegmentTemplate
StartNumber = 20, // f64
// SegmentTemplate + SegmentBase
AvailabilityTimeComplete = 22, // u8 (bool)
IndexRangeExact = 23, // u8 (bool)
PresentationTimeOffset = 24, // f64
// EventStream
EventPresentationTime = 25, // f64
// SegmentTemplate + SegmentBase + EventStream + EventStreamElt
TimeScale = 27, // f64
// SegmentURL + SegmentTemplate
Index = 28, // String
// Initialization
InitializationRange = 29, // [f64, f64]
// SegmentURL + SegmentTemplate + SegmentBase + Initialization
Media = 30, // String
IndexRange = 31, // [f64, f64]
// Period + AdaptationSet + SegmentTemplate
BitstreamSwitching = 32, // u8 (bool)
// MPD
Type = 33, // String
AvailabilityStartTime = 34, // f64
AvailabilityEndTime = 35, // f64
PublishTime = 36, // f64
MinimumUpdatePeriod = 37, // f64
MinBufferTime = 38, // f64
TimeShiftBufferDepth = 39, // f64
SuggestedPresentationDelay = 40, // f64
MaxSegmentDuration = 41, // f64
MaxSubsegmentDuration = 42, // f64
// BaseURL + SegmentTemplate
AvailabilityTimeOffset = 43, // f64
// Period
Start = 45, // f64
XLinkHref = 46, // String
XLinkActuate = 47, // String
// AdaptationSet
Group = 48,
MaxBandwidth = 49, // f64
MaxFrameRate = 50, // f64
MaxHeight = 51, // f64
MaxWidth = 52, // f64
MinBandwidth = 53, // f64
MinFrameRate = 54, // f64
MinHeight = 55, // f64
MinWidth = 56, // f64
SelectionPriority = 57,
SegmentAlignment = 58,
SubsegmentAlignment = 59,
// AdaptationSet + ContentComponent
Language = 60, // String
ContentType = 61, // String
Par = 62,
// Representation
Bitrate = 63, // f64
Text = 64,
QualityRanking = 65,
Location = 66,
InitializationMedia = 67,
/// Describes an encountered "mediaPresentationDuration" attribute, as found
/// in `<MPD>` elements.
///
/// This value has been converted into seconds, as an f64.
MediaPresentationDuration = 68,
/// Describes the byte range (end not included) of an encountered `<Event>`
/// element in the whole MPD.
///
/// This can be useful to re-construct the whole element on the JS-sid.
///
/// It is reported as an array of two f64 values.
/// The first number indicating the starting range (included).
/// The second indicating the ending range (non-included).
EventStreamEltRange = 69,
/// Describes an XML namespace coming from either a `<MPD>` element, a
/// `<Period> element or a `<EventStream>` elements, as those are the three
/// parent tags of potential `<Event>` elements.
///
/// It is reported as the concatenation of four values:
///
/// - In the four first bytes: The length of the namespace's name (the
/// part in the XML attribute just after "xmlns:"), as a big endian
/// unsigned 32 bit integer
///
/// - The namespace's name (the part coming after "xmlns:" in the
/// attribute's name), as an UTF-8 encoded string.
/// The length of this attribute is indicated by the preceding four
/// bytes.
///
/// - As the next four bytes: The length of the namespace's value (the
/// corresponding XML attribute's value), as a big endian
/// unsigned 32 bit integer
///
/// - The namespace's value (the value of the corresponding XML
/// attribute), as an UTF-8 encoded string.
/// The length of this attribute is indicated by the preceding four
/// bytes.
///
/// This special Attribute was needed because we need those namespaces to be
/// able to communicate `<Event>` property under a JavaScript's Element
/// format: the browser's `DOMParser` API needs to know all potential
/// namespaces that will appear in it.
Namespace = 70,
Label = 71, // String
ServiceLocation = 72, // String
// SegmentTemplate
EndNumber = 76, // f64
}
impl TagName {
/// Signal a new tag opening to the application
pub fn report_tag_open(self) {
debug_assert!(self as u64 <= u8::MAX as u64);
// UNSAFE: We're using FFI, but there should be no risk at all here
unsafe { onTagOpen(self) };
}
/// Signal that a previously-open tag closed to the application
pub fn report_tag_close(self) {
debug_assert!(self as u64 <= u8::MAX as u64);
// UNSAFE: We're using FFI, but there should be no risk at all here
unsafe { onTagClose(self) };
}
}
use crate::reportable::ReportableAttribute;
use crate::utils;
impl AttributeName {
#[inline(always)]
pub fn report<T: ReportableAttribute>(self, val: T) {
val.report_as_attr(self)
}
pub fn try_report_as_string(self, attr: &quick_xml::events::attributes::Attribute) {
match attr.unescape_value() {
Ok(val) => self.report(val),
Err(_) => ParsingError("Could not escape original value".to_owned()).report_err(),
}
}
pub fn try_report_as_f64(self, attr: &quick_xml::events::attributes::Attribute) {
match utils::parse_f64(&attr.value) {
Ok(val) => self.report(val),
Err(error) => error.report_err(),
}
}
pub fn try_report_as_iso_8601_duration(self, attr: &quick_xml::events::attributes::Attribute) {
match utils::parse_iso_8601_duration(&attr.value) {
Ok(val) => self.report(val),
Err(error) => error.report_err(),
}
}
pub fn try_report_as_u64(self, attr: &quick_xml::events::attributes::Attribute) {
match utils::parse_u64(&attr.value) {
Ok(val) => self.report(val as f64),
Err(error) => error.report_err(),
}
}
pub fn try_report_as_u64_or_bool(self, attr: &quick_xml::events::attributes::Attribute) {
match utils::parse_u64_or_bool(&attr.value) {
Ok(val) => self.report(val),
Err(error) => error.report_err(),
}
}
pub fn try_report_as_bool(self, attr: &quick_xml::events::attributes::Attribute) {
match utils::parse_bool(&attr.value) {
Ok(val) => self.report(val),
Err(error) => error.report_err(),
}
}
pub fn try_report_as_range(self, attr: &quick_xml::events::attributes::Attribute) {
match utils::parse_byte_range(&attr.value) {
Ok(val) => self.report(val),
Err(error) => error.report_err(),
}
}
pub fn try_report_as_key_value(
self,
key: &[u8],
value: &quick_xml::events::attributes::Attribute,
) {
match value.unescape_value() {
Ok(val) => self.report((key, val)),
Err(_) => ParsingError("Could not escape original value".to_owned()).report_err(),
}
}
}
|
use crate::datastructure::bvh::boundingbox::BoundingBox;
use crate::scene::triangle::Triangle;
use crate::util::vector::Vector;
use core::fmt;
use log::debug;
use std::fmt::{Display, Formatter};
pub enum BVHNode<'d> {
Leaf {
bounding_box: BoundingBox,
triangles: Vec<&'d Triangle<'d>>,
},
Node {
bounding_box: BoundingBox,
left: Box<BVHNode<'d>>,
right: Box<BVHNode<'d>>,
},
}
impl<'d> Display for BVHNode<'d> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.print(f, 0)
}
}
impl<'d> BVHNode<'d> {
fn print(&self, f: &mut Formatter<'_>, depth: usize) -> fmt::Result {
match self {
BVHNode::Leaf {
triangles,
..
} => {
write!(f, "{}", "\t".repeat(depth))?;
writeln!(f, "leaf node with {} triangles:", triangles.len(),)?;
}
BVHNode::Node {
left,
right,
..
} => {
write!(f, "{}", "\t".repeat(depth))?;
writeln!(f, ">>")?;
left.print(f, depth + 1)?;
right.print(f, depth + 1)?;
}
}
Ok(())
}
pub fn new(triangles: Vec<&'d Triangle<'d>>) -> Self {
debug!("Creating new KD Tree with {} triangles", triangles.len());
let bb = BoundingBox::from_triangles(triangles.iter().cloned());
Self::new_internal(triangles, bb, 0)
}
fn divide_triangles_over_boundingboxes<'a>(
(leftbox, rightbox): (&BoundingBox, &BoundingBox),
triangles: &[&'a Triangle<'a>],
) -> (Vec<&'a Triangle<'a>>, Vec<&'a Triangle<'a>>) {
let mut leftset = Vec::new();
let mut rightset = Vec::new();
for i in triangles {
if leftbox.contains(i) {
leftset.push(*i);
}
if rightbox.contains(i) {
rightset.push(*i);
}
}
(leftset, rightset)
}
fn new_internal(
triangles: Vec<&'d Triangle<'d>>,
bounding_box: BoundingBox,
depth: usize,
) -> Self {
if triangles.is_empty() {
return BVHNode::Leaf {
bounding_box: BoundingBox::EMPTY,
triangles,
};
}
if triangles.len() < 30 {
return BVHNode::Leaf {
bounding_box,
triangles,
};
}
let longest_axis = bounding_box.longest_axis();
struct State<'s> {
leftbox: BoundingBox,
rightbox: BoundingBox,
leftset: Vec<&'s Triangle<'s>>,
rightset: Vec<&'s Triangle<'s>>,
totalcost: f64,
}
let mut smallest: Option<State> = None;
for (leftbox, rightbox) in longest_axis.divide(&bounding_box, 16) {
let (leftset, rightset) =
Self::divide_triangles_over_boundingboxes((&leftbox, &rightbox), &triangles);
let leftcost = leftbox.cost(leftset.len());
let rightcost = rightbox.cost(rightset.len());
let totalcost = leftcost + rightcost;
if let Some(s) = smallest.as_ref() {
if totalcost < s.totalcost {
smallest = Some(State {
leftbox,
rightbox,
leftset,
rightset,
totalcost,
})
}
} else {
smallest = Some(State {
leftbox,
rightbox,
leftset,
rightset,
totalcost,
});
}
}
// Can't fail because smallest is set in the first iteration of the loop.
let smallest = smallest.unwrap();
let current_cost = bounding_box.cost(triangles.len());
debug!("Smallest possible split cost: {}", smallest.totalcost);
debug!("Parent split cost: {}", current_cost);
if smallest.totalcost >= current_cost {
BVHNode::Leaf {
bounding_box,
triangles,
}
} else {
BVHNode::Node {
bounding_box,
left: Box::new(Self::new_internal(
smallest.leftset,
smallest.leftbox,
depth + 1,
)),
right: Box::new(Self::new_internal(
smallest.rightset,
smallest.rightbox,
depth + 1,
)),
}
}
}
pub fn includes_point(&self, point: &Vector) -> bool {
match self {
BVHNode::Leaf { bounding_box, .. } => bounding_box.includes_point(point),
BVHNode::Node { bounding_box, .. } => bounding_box.includes_point(point),
}
}
}
|
mod column_type;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::cell::{Cell, RefCell};
use std::str::FromStr;
use gtk::prelude::*;
use gtk::{self, Builder, Window, Statusbar, Adjustment, TreeView, TreeViewColumn, TreeIter, ListStore, CellRendererText, MenuItem, FileChooserDialog, FileChooserAction, ResponseType, TreeViewGridLines, RadioButton, Entry, Button};
use sa2_set::{SetFile, SetObject, Object, Platform, Dreamcast, GameCube, Pc};
use obj_table::ObjectTable;
use self::column_type::{ColumnType, ObjectID, XRotation, YRotation, ZRotation, XPosition, YPosition, ZPosition, Attribute1, Attribute2, Attribute3};
const GLADE_SRC: &'static str = include_str!("gui.glade");
#[derive(Clone,Debug)]
pub struct SetEditorGui {
set_objs: Rc<RefCell<SetFile>>,
obj_table: Rc<RefCell<Option<ObjectTable>>>,
}
impl SetEditorGui {
pub fn new(set_objs: Option<SetFile>) -> SetEditorGui {
SetEditorGui {
set_objs: Rc::new(RefCell::new(set_objs.unwrap_or(SetFile(Vec::new())))),
obj_table: Rc::new(RefCell::new(None)),
}
}
pub fn run(&mut self) -> Result<(), ()> {
gtk::init()?;
let builder = Builder::new();
builder.add_from_string(GLADE_SRC).unwrap();
// TODO: set selectionmode to single for TreeSelection
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
set_grid.set_headers_clickable(true);
set_grid.set_property_enable_grid_lines(TreeViewGridLines::Both);
let set_list: ListStore = builder.get_object("Set Objects").unwrap();
let level_adjustment: Adjustment = builder.get_object("Level Adjustment").unwrap();
let mut columns = set_grid.get_columns().into_iter();
columns.next().unwrap().set_sort_column_id(0); // Index
self.connect_renderer::<ObjectID>(columns.next().unwrap(), 1, &set_list, &level_adjustment);
columns.next().unwrap().set_sort_column_id(2); // Object Name
self.connect_renderer::<XRotation>(columns.next().unwrap(), 3, &set_list, &level_adjustment);
self.connect_renderer::<YRotation>(columns.next().unwrap(), 4, &set_list, &level_adjustment);
self.connect_renderer::<ZRotation>(columns.next().unwrap(), 5, &set_list, &level_adjustment);
self.connect_renderer::<XPosition>(columns.next().unwrap(), 6, &set_list, &level_adjustment);
self.connect_renderer::<YPosition>(columns.next().unwrap(), 7, &set_list, &level_adjustment);
self.connect_renderer::<ZPosition>(columns.next().unwrap(), 8, &set_list, &level_adjustment);
self.connect_renderer::<Attribute1>(columns.next().unwrap(), 9, &set_list, &level_adjustment);
self.connect_renderer::<Attribute2>(columns.next().unwrap(), 10, &set_list, &level_adjustment);
self.connect_renderer::<Attribute3>(columns.next().unwrap(), 11, &set_list, &level_adjustment);
self.connect_menu(&builder);
let statusbar: Statusbar = builder.get_object("Status Bar").unwrap();
let obj_table_id = statusbar.get_context_id("Object Table Info");
match ObjectTable::from_file(&PathBuf::from("obj_table.json")) {
Ok(obj_table) => {
statusbar.push(obj_table_id, "Successfully loaded object table file.");
*self.obj_table.borrow_mut() = Some(obj_table);
}
Err(e) => {
statusbar.push(obj_table_id, &format!("Error loading object table: {}", e));
}
}
let window: Window = builder.get_object("Set Editor").unwrap();
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
window.show_all();
gtk::main();
Ok(())
}
fn load_file(&self, filename: &Path, set_list: &ListStore, level_adjustment: &Adjustment) -> Result<(), &'static str> {
let mut file = File::open(filename).map_err(|_| "Could not open file.")?;
let set_objs = SetFile::from_read::<Pc, _>(&mut file).map_err(|_| "Could not parse set file.")?;
*self.set_objs.borrow_mut() = set_objs;
self.update_grid(set_list, level_adjustment);
Ok(())
}
fn save_file(set_objs: &Rc<RefCell<SetFile>>, filename: &Path) -> Result<(), &'static str> {
let mut set_file = File::create(filename).map_err(|_| "Could not create set file.")?;
set_objs.borrow_mut().write_data::<Pc, _>(&mut set_file).map_err(|_| "Could not write set data.")?;
Ok(())
}
fn update_grid(&self, set_list: &ListStore, level_adjustment: &Adjustment) {
set_list.clear();
let level_id = level_adjustment.get_value() as u16;
let mut index = 0;
for obj in self.set_objs.borrow_mut().0.iter() {
let empty = String::from("");
let obj_id = format!("{:04X}", obj.object.0);
let obj_table_borrow = self.obj_table.borrow();
let obj_name = obj_table_borrow.as_ref().and_then(|ot| ot.lookup(level_id, obj.object.0)).unwrap_or(&empty);
let rot_x = format!("{:04X}", obj.rotation.x);
let rot_y = format!("{:04X}", obj.rotation.y);
let rot_z = format!("{:04X}", obj.rotation.z);
let pos_x = obj.position.x;
let pos_y = obj.position.y;
let pos_z = obj.position.z;
let attr_1 = obj.attr1;
let attr_2 = obj.attr2;
let attr_3 = obj.attr3;
set_list.insert_with_values(None, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], &[&index, &obj_id, &obj_name, &rot_x, &rot_y, &rot_z, &pos_x, &pos_y, &pos_z, &attr_1, &attr_2, &attr_3]);
index += 1;
}
}
fn connect_renderer<T>(&self, column: TreeViewColumn, id: i32, set_list: &ListStore, level_adjustment: &Adjustment)
where T: ColumnType
{
// XXX: Technically should be fine because all renderers are CellRendererText,
// but downcasting is ugly.
let renderer: CellRendererText = column.get_cells()[0].clone().downcast().unwrap();
let set_list = set_list.clone();
let level_adjustment= level_adjustment.clone();
let self_clone = self.clone();
renderer.connect_edited(move |_, tree_path, text| {
if let Ok(value) = T::from_str(text) {
let iter = set_list.get_iter(&tree_path).unwrap();
let idx = set_list.get_value(&iter, 0).get::<u32>().unwrap() as usize;
value.update_obj(&self_clone.set_objs, idx);
let level_id = level_adjustment.get_value() as u16;
value.update_column(&set_list, &tree_path, &self_clone.obj_table, level_id);
}
});
column.set_sort_column_id(id);
}
fn connect_menu(&self, builder: &Builder) {
let window: Window = builder.get_object("Set Editor").unwrap();
{
let open: MenuItem = builder.get_object("Open").unwrap();
let set_list: ListStore = builder.get_object("Set Objects").unwrap();
let level_adjustment: Adjustment = builder.get_object("Level Adjustment").unwrap();
let statusbar: Statusbar = builder.get_object("Status Bar").unwrap();
let open_id = statusbar.get_context_id("Open Info");
let self_clone = self.clone();
let window = window.clone();
open.connect_activate(move |_| {
let file_chooser = FileChooserDialog::new(Some("Open File"), Some(&window), FileChooserAction::Open);
file_chooser.add_button("_Cancel", ResponseType::Cancel.into());
file_chooser.add_button("_Open", ResponseType::Accept.into());
let response = file_chooser.run();
if response == Into::<i32>::into(ResponseType::Accept) {
if let Some(path) = file_chooser.get_filename() {
match self_clone.load_file(&path, &set_list, &level_adjustment) {
Ok(_) => {
statusbar.push(open_id, &format!("Successfully opened file: {}", path.to_str().unwrap_or("")));
}
Err(e) => {
statusbar.push(open_id, &format!("Error: {}", e));
}
}
}
}
file_chooser.destroy();
});
}
{
let save: MenuItem = builder.get_object("Save As").unwrap();
let statusbar: Statusbar = builder.get_object("Status Bar").unwrap();
let save_id = statusbar.get_context_id("Save Info");
let set_objs = self.set_objs.clone();
let window = window.clone();
save.connect_activate(move |_| {
let file_chooser = FileChooserDialog::new(Some("Save File"), Some(&window), FileChooserAction::Save);
// TODO: Set current name based on type of input
// TODO: Set file filter
file_chooser.set_do_overwrite_confirmation(true);
file_chooser.add_button("_Cancel", ResponseType::Cancel.into());
file_chooser.add_button("_Save", ResponseType::Accept.into());
let response = file_chooser.run();
if response == Into::<i32>::into(ResponseType::Accept) {
if let Some(path) = file_chooser.get_filename() {
// TODO: error handling
match Self::save_file(&set_objs, &path) {
Ok(_) => {
statusbar.push(save_id, &format!("Successfully saved file: {}", path.to_str().unwrap_or("")));
}
Err(e) => {
statusbar.push(save_id, &format!("Error: {}", e));
}
}
}
}
file_chooser.destroy();
});
}
{
let add_object: MenuItem = builder.get_object("Add Object").unwrap();
let set_list: ListStore = builder.get_object("Set Objects").unwrap();
let level_adjustment: Adjustment = builder.get_object("Level Adjustment").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
let self_clone = self.clone();
add_object.connect_activate(move |_| {
let (paths, model) = set_grid.get_selection().get_selected_rows();
let iter_opt = paths.get(0).map(|path| model.get_iter(path).unwrap());
let object = SetObject::default();
let idx = iter_opt.map(|iter| set_list.get_value(&iter, 0).get::<u32>().unwrap() as usize + 1).unwrap_or(0);
self_clone.set_objs.borrow_mut().0.insert(idx, object);
self_clone.update_grid(&set_list, &level_adjustment);
});
}
{
let add_object: MenuItem = builder.get_object("Remove Object").unwrap();
let set_list: ListStore = builder.get_object("Set Objects").unwrap();
let level_adjustment: Adjustment = builder.get_object("Level Adjustment").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
let self_clone = self.clone();
add_object.connect_activate(move |_| {
let (paths, _) = set_grid.get_selection().get_selected_rows();
for path in paths {
let idx = path.get_indices()[0] as usize;
self_clone.set_objs.borrow_mut().0.remove(idx);
}
self_clone.update_grid(&set_list, &level_adjustment);
});
}
{
let column_search: MenuItem = builder.get_object("Column Search").unwrap();
let search_window: Window = builder.get_object("Search Window").unwrap();
search_window.connect_delete_event(|sw, _| {
sw.hide();
Inhibit(true)
});
column_search.connect_activate(move |_| {
search_window.show_all();
});
}
// Search dialog stuff
{
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
let search_entry: Entry = builder.get_object("Search Entry").unwrap();
set_grid.set_search_entry(&search_entry);
}
{
let index_radio_button: RadioButton = builder.get_object("Index Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
index_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(0);
});
}
{
let object_id_radio_button: RadioButton = builder.get_object("Object ID Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
object_id_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(1);
});
}
{
let object_name_radio_button: RadioButton = builder.get_object("Object Name Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
object_name_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(2);
});
}
{
let x_rotation_radio_button: RadioButton = builder.get_object("X Rotation Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
x_rotation_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(3);
});
}
{
let y_rotation_radio_button: RadioButton = builder.get_object("Y Rotation Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
y_rotation_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(4);
});
}
{
let z_rotation_radio_button: RadioButton = builder.get_object("Z Rotation Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
z_rotation_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(5);
});
}
{
let x_position_radio_button: RadioButton = builder.get_object("X Position Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
x_position_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(6);
});
}
{
let y_position_radio_button: RadioButton = builder.get_object("Y Position Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
y_position_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(7);
});
}
{
let z_position_radio_button: RadioButton = builder.get_object("Z Position Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
z_position_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(8);
});
}
{
let attribute_1_radio_button: RadioButton = builder.get_object("Attribute 1 Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
attribute_1_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(9);
});
}
{
let attribute_2_radio_button: RadioButton = builder.get_object("Attribute 2 Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
attribute_2_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(10);
});
}
{
let attribute_3_radio_button: RadioButton = builder.get_object("Attribute 3 Radio Button").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
attribute_3_radio_button.connect_clicked(move |_| {
set_grid.set_search_column(11);
});
}
{
let distance_search: MenuItem = builder.get_object("Distance Search").unwrap();
let point_search_window: Window = builder.get_object("Point Search Window").unwrap();
point_search_window.connect_delete_event(|sw, _| {
sw.hide();
Inhibit(true)
});
distance_search.connect_activate(move |_| {
point_search_window.show_all();
});
}
{
let point_search_button: Button = builder.get_object("Point Search Button").unwrap();
let set_list: ListStore = builder.get_object("Set Objects").unwrap();
let set_grid: TreeView = builder.get_object("Set Grid").unwrap();
let x_position_entry: Entry = builder.get_object("X Position Entry").unwrap();
let y_position_entry: Entry = builder.get_object("Y Position Entry").unwrap();
let z_position_entry: Entry = builder.get_object("Z Position Entry").unwrap();
let statusbar: Statusbar = builder.get_object("Status Bar").unwrap();
let search_id = statusbar.get_context_id("Search Info");
point_search_button.connect_clicked(move |_| {
let position_opt = x_position_entry.get_text().and_then(|text| f32::from_str(&text).ok())
.and_then(|x| y_position_entry.get_text().and_then(|text| f32::from_str(&text).ok()).map(|y| (x, y)))
.and_then(|(x, y)| z_position_entry.get_text().and_then(|text| f32::from_str(&text).ok()).map(|z| (x, y, z)));
if let Some((x, y, z)) = position_opt {
let mut closest: Option<(f32, TreeIter)> = None;
let mut iter = set_list.get_iter_first();
while let Some(row) = iter {
let row_x = set_list.get_value(&row, 6).get::<f32>().unwrap();
let row_y = set_list.get_value(&row, 7).get::<f32>().unwrap();
let row_z = set_list.get_value(&row, 8).get::<f32>().unwrap();
let distance_squared = (row_x - x) * (row_x - x) + (row_y - y) * (row_y - y) + (row_z - z) * (row_z - z);
if closest.is_none() || distance_squared < closest.as_ref().unwrap().0 {
closest = Some((distance_squared, row.clone()));
}
if set_list.iter_next(&row) {
iter = Some(row);
}
else {
iter = None;
}
}
if let Some((_, iter)) = closest {
set_grid.get_selection().select_iter(&iter);
let path = set_list.get_path(&iter).unwrap();
set_grid.set_cursor(&path, None, false);
}
}
else {
statusbar.push(search_id, "Position values cannot be parsed as floats.");
}
});
}
{
let set_list: ListStore = builder.get_object("Set Objects").unwrap();
let level_adjustment: Adjustment = builder.get_object("Level Adjustment").unwrap();
let self_clone = self.clone();
level_adjustment.connect_value_changed(move |adj| {
self_clone.update_grid(&set_list, &adj);
});
}
}
}
|
#![no_std]
#![no_main]
// pick a panicking behavior
use panic_probe as _;
#[allow(unused)]
use stm32f4xx_hal::stm32::interrupt;
use cortex_m::asm;
use cortex_m_rt::entry;
use rtt_target::{rtt_init_print, rprintln};
#[entry]
fn main() -> ! {
rtt_init_print!();
rprintln!("Hello, world!");
loop { asm::bkpt() }
}
|
// error-pattern:quux
use std;
import std::str::*;
import std::uint::*;
fn nop(a: uint, b: uint) : le(a, b) { fail "quux"; }
fn main() {
let a: uint = 5u;
let b: uint = 4u;
claim (le(a, b));
nop(a, b);
}
|
//! CSC
use static_assertions::const_assert_eq;
register! {
Control,
u32,
RW,
Fields [
Bits WIDTH(U32) OFFSET(U0),
]
}
register! {
Coef,
u32,
RW,
Fields [
Bits WIDTH(U32) OFFSET(U0),
]
}
const_assert_eq!(core::mem::size_of::<RegisterBlock>(), 0x40);
#[repr(C)]
pub struct RegisterBlock {
pub ctl: Control::Register, // 0x00
__reserved_0: [u32; 3], // 0x04
pub coef11: Coef::Register, // 0x10
pub coef12: Coef::Register, // 0x14
pub coef13: Coef::Register, // 0x18
pub coef14: Coef::Register, // 0x1C
pub coef21: Coef::Register, // 0x20
pub coef22: Coef::Register, // 0x24
pub coef23: Coef::Register, // 0x28
pub coef24: Coef::Register, // 0x2C
pub coef31: Coef::Register, // 0x30
pub coef32: Coef::Register, // 0x34
pub coef33: Coef::Register, // 0x38
pub coef34: Coef::Register, // 0x3C
}
|
use tracing::Subscriber;
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
pub fn get_subscriber(app_name: String, env_filter: String) -> impl Subscriber + Send + Sync {
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter));
let formatting_layer = BunyanFormattingLayer::new(app_name, std::io::stdout);
Registry::default()
.with(env_filter)
.with(JsonStorageLayer)
.with(formatting_layer)
}
|
use std::io;
enum Cell
{
E,
X,
O,
}
impl Copy for Cell {}
impl Clone for Cell {
fn clone(&self) -> Cell { *self }
}
struct Field
{
field : Vec<Vec<Cell>>,
}
impl Field
{
//"Constructor"
fn new (size: usize) -> Field
{
Field { field: vec![vec!(Cell::E;size); size] }
}
//print field into output stream
fn out (&self)
{
for row in self.field.iter()
{
for _ in row.iter() { print!("+---"); }
println!("+");
print!("|");
for element in row.iter()
{
match *element
{
Cell::E => print!(" |"),
Cell::X => print!(" X |"),
Cell::O => print!(" O |"),
}
}
println!("");
}
for _ in self.field[0].iter() { print!("+---"); }
println!("+");
}
//try to set cell value. If cell is empty sets value end returns true else returns false;
fn try_set_cell(&mut self, column : usize, row : usize, value : Cell) -> bool
{
if column>=self.field[0].len() {return false;}
if row>=self.field.len() {return false;}
match self.field[row][column]
{
Cell::E => {
self.field[row][column] = value;
return true;
},
Cell::X => return false,
Cell::O => return false,
}
}
fn winning_row(&mut self, player : Cell) -> i32
{
for row in self.field.iter()
{
}
return -1;
}
}
//For counting elements, which equal to
trait CountElements<T>
{
fn count (&self, element: T) -> i32;
}
impl<T> CountElements<T> for Vec<T> where T : Eq
{
fn count (&self, item: T) -> i32
{
let mut res = 0;
for element in self.iter()
{
if item==*element
{
res+=1;
}
}
return res;
}
}
//For verifing, if collection contains empty cell
trait HasEmptyCells
{
fn has_empty_cells (&self) -> bool;
}
impl HasEmptyCells for Vec<Cell>
{
fn has_empty_cells (&self) -> bool
{
for element in self.iter()
{
match *element
{
Cell::E => return true,
Cell::X => continue,
Cell::O => continue,
}
}
return false;
}
}
impl HasEmptyCells for Field
{
fn has_empty_cells (&self) -> bool
{
for row in self.field.iter()
{
if row.has_empty_cells()
{
return true;
}
}
return false;
}
}
fn main()
{
let mut field = Field::new(3);
let mut turn = Cell::X;
while field.has_empty_cells()
{
field.out();
println!("Column?");
let column = read_int();
println!("Row?");
let row = read_int();
if field.try_set_cell(column, row, turn)
{
println!("Move Accepted");
match turn
{
Cell::E => panic!("Something is wrong! : turn of empty"),
Cell::X => {turn = Cell::O; println!("Turn of O now")},
Cell::O => {turn = Cell::X; println!("Turn of X now")},
}
}
}
field.out();
}
fn read_int() -> usize
{
loop
{
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
match input.trim().parse() {
Ok(num) => return num,
Err(_) => continue,
};
}
}
|
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#[cfg(all(target_os = "linux", target_pointer_width = "64"))]
pub type size_t = ::std::os::raw::c_ulong;
#[cfg(all(target_os = "windows", target_pointer_width = "64"))]
pub type size_t = ::std::os::raw::c_ulonglong;
#[cfg(target_pointer_width = "32")]
pub type size_t = ::std::os::raw::c_uint;
#[cfg(not(all(target_os = "windows", target_pointer_width = "32")))]
extern "C" {
pub fn LzmaCompress(
dest: *mut ::std::os::raw::c_uchar,
destLen: *mut size_t,
src: *const ::std::os::raw::c_uchar,
srcLen: size_t,
outProps: *mut ::std::os::raw::c_uchar,
outPropsSize: *mut size_t,
level: ::std::os::raw::c_int,
dictSize: ::std::os::raw::c_uint,
lc: ::std::os::raw::c_int,
lp: ::std::os::raw::c_int,
pb: ::std::os::raw::c_int,
fb: ::std::os::raw::c_int,
numThreads: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
pub fn LzmaUncompress(
dest: *mut ::std::os::raw::c_uchar,
destLen: *mut size_t,
src: *const ::std::os::raw::c_uchar,
srcLen: *mut size_t,
props: *const ::std::os::raw::c_uchar,
propsSize: size_t,
) -> ::std::os::raw::c_int;
}
#[cfg(all(target_os = "windows", target_pointer_width = "32"))]
extern "stdcall" {
pub fn LzmaCompress(
dest: *mut ::std::os::raw::c_uchar,
destLen: *mut size_t,
src: *const ::std::os::raw::c_uchar,
srcLen: size_t,
outProps: *mut ::std::os::raw::c_uchar,
outPropsSize: *mut size_t,
level: ::std::os::raw::c_int,
dictSize: ::std::os::raw::c_uint,
lc: ::std::os::raw::c_int,
lp: ::std::os::raw::c_int,
pb: ::std::os::raw::c_int,
fb: ::std::os::raw::c_int,
numThreads: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
pub fn LzmaUncompress(
dest: *mut ::std::os::raw::c_uchar,
destLen: *mut size_t,
src: *const ::std::os::raw::c_uchar,
srcLen: *mut size_t,
props: *const ::std::os::raw::c_uchar,
propsSize: size_t,
) -> ::std::os::raw::c_int;
} |
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type FileInformation = *mut ::core::ffi::c_void;
pub type FileInformationFactory = *mut ::core::ffi::c_void;
pub type FolderInformation = *mut ::core::ffi::c_void;
pub type IStorageItemInformation = *mut ::core::ffi::c_void;
|
//! An idiomatic Rust PulseAudio interface.
// Documentation: https://freedesktop.org/software/pulseaudio/doxygen/
// Ref: https://gist.github.com/toroidal-code/8798775
#[macro_use]
mod error;
pub use self::error::{Error, Result};
mod enums;
pub use self::enums::ContextState;
mod main_loop;
pub use self::main_loop::MainLoop;
mod property_list;
pub use self::property_list::PropertyList;
mod context;
pub use self::context::Context;
|
use std::fmt;
use titlecase::titlecase;
use super::formatter::format_change;
use super::{db, Command, CommandArgs, Error, Result};
pub(super) struct Bulls;
struct Mover {
pub name: String,
pub ticker: String,
pub diff: f32
}
pub struct Movers {
movers: Vec<Mover>
}
impl Bulls {
fn query(&self, db: &db::DB) -> Option<Movers> {
let query =
"with movers as (
select distinct coin_id, first_value(euro) over w as first, last_value(euro) over w as last
from prices where time::date=(select max(time)::date from prices) WINDOW w as (
partition by coin_id order by time range between unbounded preceding and unbounded
following) order by coin_id
)
select name, ticker, first, last, cast((last-first)*100/first as real) as diff
from movers
join coins using(coin_id)
where first != 0
order by diff desc limit 3;";
let rows = db.connection.query(&query, &[]).unwrap();
if rows.len() < 3 {
return None;
}
Some(Movers {movers: rows.into_iter().map(|r| Mover {name: r.get(0), ticker: r.get(1), diff: r.get(4)}).collect::<Vec<Mover>>()})
}
}
impl Command for Bulls {
fn name(&self) -> &'static str {
"!bulls"
}
fn run(&self, db: &db::DB, _: &Option<&str>) -> Result<String> {
let movers = self.query(db);
match movers {
Some(ms) => Ok(ms.to_string()),
None => Err(Error::Contact)
}
}
fn help(&self) -> &'static str {
"!bulls: Get today's big winners."
}
}
impl CommandArgs for Bulls {}
pub(super) struct Bears;
impl Bears {
fn query(&self, db: &db::DB) -> Option<Movers> {
let query =
"with movers as (
select distinct coin_id, first_value(euro) over w as first, last_value(euro) over w as last
from prices where time::date=(select max(time)::date from prices) WINDOW w as (
partition by coin_id order by time range between unbounded preceding and unbounded
following) order by coin_id
)
select name, ticker, first, last, cast((last-first)*100/first as real) as diff
from movers
join coins using(coin_id)
where first != 0
order by diff asc limit 3;";
let rows = db.connection.query(&query, &[]).unwrap();
if rows.len() < 3 {
return None;
}
Some(Movers {movers: rows.into_iter().map(|r| Mover {name: r.get(0), ticker: r.get(1), diff: r.get(4)}).collect::<Vec<Mover>>()})
}
}
impl Command for Bears {
fn name(&self) -> &'static str {
"!bears"
}
fn run(&self, db: &db::DB, _: &Option<&str>) -> Result<String> {
let movers = self.query(&db);
match movers {
Some(ms) => Ok(ms.to_string()),
None => Err(Error::Contact)
}
}
fn help(&self) -> &'static str {
"!bears: Get today's big losers."
}
}
impl CommandArgs for Bears {}
impl fmt::Display for Mover {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ({}) {} Today\x03", titlecase(&self.name), self.ticker.to_uppercase(), format_change(self.diff))
}
}
impl fmt::Display for Movers {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {}", self.movers[0], self.movers[1], self.movers[2])
}
}
|
use std::{
collections::{HashMap, VecDeque},
rc::Rc,
vec::Vec,
};
use crate::{
actors::actor_type::ActorType,
events::{
event::{Event, EventClone},
event_type::EventType,
},
manifest::Manifest,
PacketReader,
};
/// Handles incoming/outgoing events, tracks the delivery status of Events so
/// that guaranteed Events can be re-transmitted to the remote host
#[derive(Debug)]
pub struct EventManager<T: EventType> {
queued_outgoing_events: VecDeque<Rc<Box<dyn Event<T>>>>,
queued_incoming_events: VecDeque<T>,
sent_events: HashMap<u16, Vec<Rc<Box<dyn Event<T>>>>>,
}
impl<T: EventType> EventManager<T> {
/// Creates a new EventManager
pub fn new() -> Self {
EventManager {
queued_outgoing_events: VecDeque::new(),
queued_incoming_events: VecDeque::new(),
sent_events: HashMap::new(),
}
}
/// Occurs when a packet has been notified as delivered. Stops tracking the
/// status of Events in that packet.
pub fn notify_packet_delivered(&mut self, packet_index: u16) {
self.sent_events.remove(&packet_index);
}
/// Occurs when a packet has been notified as having been dropped. Queues up
/// any guaranteed Events that were lost in the packet for retransmission.
pub fn notify_packet_dropped(&mut self, packet_index: u16) {
if let Some(dropped_events_list) = self.sent_events.get(&packet_index) {
for dropped_event in dropped_events_list.into_iter() {
self.queued_outgoing_events.push_back(dropped_event.clone());
}
self.sent_events.remove(&packet_index);
}
}
/// Returns whether the Manager has queued Events that can be transmitted to
/// the remote host
pub fn has_outgoing_events(&self) -> bool {
return self.queued_outgoing_events.len() != 0;
}
/// Gets the next queued Event to be transmitted
pub fn pop_outgoing_event(&mut self, packet_index: u16) -> Option<Rc<Box<dyn Event<T>>>> {
match self.queued_outgoing_events.pop_front() {
Some(event) => {
//place in transmission record if this is a gauranteed event
if Event::is_guaranteed(event.as_ref().as_ref()) {
if !self.sent_events.contains_key(&packet_index) {
let sent_events_list: Vec<Rc<Box<dyn Event<T>>>> = Vec::new();
self.sent_events.insert(packet_index, sent_events_list);
}
if let Some(sent_events_list) = self.sent_events.get_mut(&packet_index) {
sent_events_list.push(event.clone());
}
}
Some(event)
}
None => None,
}
}
/// If the last popped Event from the queue somehow wasn't able to be
/// written into a packet, put the Event back into the front of the queue
pub fn unpop_outgoing_event(&mut self, packet_index: u16, event: &Rc<Box<dyn Event<T>>>) {
let cloned_event = event.clone();
if Event::is_guaranteed(event.as_ref().as_ref()) {
if let Some(sent_events_list) = self.sent_events.get_mut(&packet_index) {
sent_events_list.pop();
if sent_events_list.len() == 0 {
self.sent_events.remove(&packet_index);
}
}
}
self.queued_outgoing_events.push_front(cloned_event);
}
/// Queues an Event to be transmitted to the remote host
pub fn queue_outgoing_event(&mut self, event: &impl Event<T>) {
let clone = Rc::new(EventClone::clone_box(event));
self.queued_outgoing_events.push_back(clone);
}
/// Returns whether any Events have been received that must be handed to the
/// application
pub fn has_incoming_events(&self) -> bool {
return self.queued_incoming_events.len() != 0;
}
/// Get the most recently received Event
pub fn pop_incoming_event(&mut self) -> Option<T> {
return self.queued_incoming_events.pop_front();
}
/// Given incoming packet data, read transmitted Events and store them to be
/// returned to the application
pub fn process_data<U: ActorType>(
&mut self,
reader: &mut PacketReader,
manifest: &Manifest<T, U>,
) {
let event_count = reader.read_u8();
for _x in 0..event_count {
let naia_id: u16 = reader.read_u16();
match manifest.create_event(naia_id, reader) {
Some(new_event) => {
self.queued_incoming_events.push_back(new_event);
}
_ => {}
}
}
}
}
|
use std::cmp::Ordering;
pub type NodeBox<T> = Option<Box<Node<T>>>;
/// A binary tree with data at every node. Each branch may or may not contain
/// another node.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Node<T> {
pub value: T,
pub left: NodeBox<T>,
pub right: NodeBox<T>,
}
impl<T: Default> Node<T> {
pub fn new(data: T) -> Node<T> {
Node { value: data, ..Default::default() }
}
}
impl<T> Node<T> {
/// Iteratively do an idempotent insert.
pub fn insert(&mut self, data: T)
where
T: Default + Ord,
{
let mut next_node = self;
loop {
let current_node = next_node;
let target_node = match current_node.value.cmp(&data) {
Ordering::Equal => break,
Ordering::Greater => &mut current_node.left,
Ordering::Less => &mut current_node.right,
};
match target_node {
Some(branch) => next_node = branch,
None => {
*target_node = Self::boxer(data);
return
},
}
}
}
}
// TODO: Deal with magic numbers, strings, etc.
// TODO: Figure out cleaner Utils scheme
#[cfg(test)]
mod test {
use setup_test;
#[test]
fn test_insert() {
setup_test!(root_base,balanced_tree_base,unbalanced_tree_base,);
let mut balanced_tree_test = root_base.clone();
balanced_tree_test.insert(25);
balanced_tree_test.insert(75);
assert_eq!(balanced_tree_base, balanced_tree_test);
let mut unbalanced_tree_test = root_base;
unbalanced_tree_test.insert(25);
unbalanced_tree_test.insert(0);
assert_eq!(unbalanced_tree_base, unbalanced_tree_test);
}
#[test]
#[ignore]
fn test_print() {
setup_test!(,balanced_tree_base,,);
println!("arr {:#?}", balanced_tree_base);
}
} |
use std::collections::HashMap;
#[derive(Debug)]
pub struct MonDef {
id: String,
species: String,
types: Vec<String>,
abilities: Vec<String>,
evos: Vec<String>,
learnset: Vec<(i64, String)>,
base_exp: i64,
pub hp: i64,
pub atk: i64,
pub spatk: i64,
pub def: i64,
pub spdef: i64,
height: f64,
weight: f64,
}
impl MonDef {
pub fn moves_at_level(&self, lvl: i64) -> Vec<String> {
let move_idx_plus_one = self
.learnset
.iter()
.enumerate()
.find(|(_, (move_lvl, _))| move_lvl > &lvl)
.map(|(n, (_, _))| n + 1)
.unwrap_or(self.learnset.len());
self.learnset[move_idx_plus_one.saturating_sub(6)..move_idx_plus_one]
.iter()
.map(|(_, move_def)| move_def.to_owned())
.collect::<Vec<_>>()
}
}
pub fn build_mon_defs(src: &toml::Value) -> HashMap<String, MonDef> {
let mut defs = HashMap::new();
src.as_array()
.unwrap()
.iter()
.map(|mon| mon.as_table().unwrap())
.for_each(|mon| {
let id = mon["id"].as_str().unwrap().to_owned();
let species = mon["species"].as_str().unwrap().to_owned();
let types = mon["types"]
.as_array()
.map(|vals| {
vals.iter()
.map(toml::Value::as_str)
.map(Option::unwrap)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
})
.unwrap();
let abilities = mon["abilities"]
.as_array()
.map(|vals| {
vals.iter()
.map(toml::Value::as_str)
.map(Option::unwrap)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
})
.unwrap();
let evos = mon["evolutions"]
.as_array()
.map(|vals| {
vals.iter()
.map(toml::Value::as_str)
.map(Option::unwrap)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
})
.unwrap();
let mut learnset = mon["possible_moves"]
.as_array()
.map(|moves| {
moves
.iter()
.map(toml::Value::as_array)
.map(Option::unwrap)
.map(|move_| {
unwrap_matches!(
move_.as_slice(),
[lvl, move_name] => (
lvl.as_integer().unwrap(),
move_name.as_str().unwrap().to_owned()
)
)
})
.collect::<Vec<_>>()
})
.unwrap();
learnset.sort_by(|lhs, rhs| lhs.0.cmp(&rhs.0));
let base_exp = mon["base_exp"].as_integer().unwrap();
let base_stats = mon["base_stats"].as_table().unwrap();
let hp = base_stats["hp"].as_integer().unwrap();
let atk = base_stats["atk"].as_integer().unwrap();
let spatk = base_stats["spatk"].as_integer().unwrap();
let def = base_stats["def"].as_integer().unwrap();
let spdef = base_stats["spdef"].as_integer().unwrap();
let height = mon["weight"].as_float().unwrap();
let weight = mon["height"].as_float().unwrap();
let def = MonDef {
id: id.clone(),
species,
types,
abilities,
evos,
learnset,
base_exp,
hp,
atk,
spatk,
def,
spdef,
height,
weight,
};
defs.insert(id, def);
});
defs
}
#[derive(Debug)]
pub struct MonInstance {
id: String,
def: String,
nickname: String,
ability: String,
level: i64,
current_moves: Vec<String>,
}
pub fn build_mon_instances(src: &toml::Value) -> HashMap<String, MonInstance> {
let mut instances = HashMap::new();
src.as_array()
.unwrap()
.iter()
.map(|mon| mon.as_table().unwrap())
.for_each(|mon| {
let id = mon["id"].as_str().unwrap().to_owned();
let def = mon["def"].as_str().unwrap().to_owned();
let nickname = mon["nickname"].as_str().unwrap().to_owned();
let ability = mon["ability"].as_str().unwrap().to_owned();
let level = mon["level"].as_integer().unwrap();
let current_moves = mon["current_moves"]
.as_array()
.map(|moves| {
moves
.iter()
.map(toml::Value::as_str)
.map(Option::unwrap)
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
})
.unwrap();
let instance = MonInstance {
id: id.clone(),
def,
nickname,
ability,
level,
current_moves,
};
instances.insert(id, instance);
});
instances
}
#[derive(Debug)]
pub enum Effectiveness {
Double,
One,
Half,
}
#[derive(Debug)]
pub struct TypeChart(HashMap<String, HashMap<String, Effectiveness>>);
pub fn build_type_chart(src: &toml::Value) -> TypeChart {
let mut chart = HashMap::new();
let types = src
.as_table()
.unwrap()
.iter()
.map(|(type_name, _)| type_name)
.collect::<Vec<_>>();
for &ty in &types {
let effectivenesses = chart.entry(ty.to_owned()).or_insert_with(HashMap::new);
for &ty in &types {
effectivenesses.insert(ty.to_owned(), Effectiveness::One);
}
}
src.as_table()
.unwrap()
.iter()
.for_each(|(type_name, data)| {
let effectivity = data.as_table().unwrap();
// if type_name == "fire"
// then "weak_to = ["water"]
effectivity["weak_to"]
.as_array()
.unwrap()
.iter()
.map(|ty| ty.as_str().unwrap().to_owned())
.for_each(|ty| {
// chart["water"]["fire"] == Effectiveness::Double
chart
.get_mut(&ty)
.unwrap()
.insert(type_name.to_owned(), Effectiveness::Double);
});
effectivity["resistant_to"]
.as_array()
.unwrap()
.iter()
.map(|ty| ty.as_str().unwrap().to_owned())
.for_each(|ty| {
chart
.get_mut(&ty)
.unwrap()
.insert(type_name.to_owned(), Effectiveness::Half);
});
});
TypeChart(chart)
}
#[derive(Debug)]
pub enum Category {
Physical,
Special,
Status,
}
#[derive(Debug)]
pub struct TargetType {
targets_self: bool,
target_type: TargetTypeModSelf,
}
#[derive(Debug)]
pub enum TargetTypeModSelf {
OneFoe,
AllFoes,
OneAlly,
AllAllies,
OneMon,
AllMons,
Arena,
None,
}
#[derive(Debug)]
pub struct MoveDef {
id: String,
name: String,
accuracy: i64,
base_power: i64,
category: Category,
priority: i64,
target: TargetType,
move_type: String,
atk_boost: i64,
spatk_boost: i64,
def_boost: i64,
spdef_boost: i64,
}
pub fn build_moves(src: &toml::Value) -> HashMap<String, MoveDef> {
let mut moves = HashMap::new();
src.as_array().unwrap().iter().for_each(|move_| {
let move_ = move_.as_table().unwrap();
let id = move_["id"].as_str().unwrap().to_owned();
let name = move_["name"].as_str().unwrap().to_owned();
let accuracy = move_["accuracy"].as_integer().unwrap();
let base_power = move_["base_power"].as_integer().unwrap();
let category = match move_["category"].as_str().unwrap() {
"physical" => Category::Physical,
"special" => Category::Special,
"status" => Category::Status,
_ => panic!(""),
};
let priority = move_["priority"].as_integer().unwrap();
assert!(priority < 6);
let (targets_self, target_type) = if let Some(target) = move_["target"].as_str() {
(None, target)
} else if let Some(target) = move_["target"].as_array() {
assert!(target.len() == 2);
(
Some(target[0].as_bool().unwrap()),
target[1].as_str().unwrap(),
)
} else {
panic!("")
};
let target = TargetType {
targets_self: targets_self.unwrap_or(false),
target_type: match target_type {
"one_foe" => TargetTypeModSelf::OneFoe,
"all_foes" => TargetTypeModSelf::AllFoes,
"one_ally" => TargetTypeModSelf::OneAlly,
"all_allies" => TargetTypeModSelf::AllAllies,
"one_mon" => TargetTypeModSelf::OneMon,
"all_mons" => {
assert!(targets_self.is_some(), "write out a bool explicitly pls");
TargetTypeModSelf::AllMons
}
"arena" => {
assert!(targets_self.is_some(), "write out a bool explicitly pls");
TargetTypeModSelf::Arena
}
"" => {
assert!(targets_self.is_some(), "write out a bool explicitly pls");
TargetTypeModSelf::None
}
_ => panic!(""),
},
};
let move_type = move_["type"].as_str().unwrap().to_owned();
dbg!(move_.get("boosts"));
let (atk_boost, spatk_boost, def_boost, spdef_boost) =
match move_.get("boosts").and_then(toml::Value::as_table) {
Some(boosts) => (
boosts
.get("atk")
.and_then(toml::Value::as_integer)
.unwrap_or(0),
boosts
.get("spatk")
.and_then(toml::Value::as_integer)
.unwrap_or(0),
boosts
.get("def")
.and_then(toml::Value::as_integer)
.unwrap_or(0),
boosts
.get("spdef")
.and_then(toml::Value::as_integer)
.unwrap_or(0),
),
None => (0, 0, 0, 0),
};
let move_ = MoveDef {
id: id.clone(),
name,
accuracy,
base_power,
category,
priority,
target,
move_type,
atk_boost,
spatk_boost,
def_boost,
spdef_boost,
};
moves.insert(id, move_);
});
moves
}
#[derive(Debug)]
pub struct EncounterTable {
pub id: String,
pub mons: Vec<(i64, i64, String)>,
}
pub fn build_encounter_tables(src: &toml::Value) -> HashMap<String, EncounterTable> {
let mut encounters = HashMap::new();
src.as_array().unwrap().iter().for_each(|encounter| {
let encounter = encounter.as_table().unwrap();
let id = encounter["id"].as_str().unwrap();
let mons = encounter["mons"]
.as_array()
.unwrap()
.iter()
.map(|entry| {
let entry = entry.as_array().unwrap();
assert!(entry.len() == 3);
let lvl_lower = entry[0].as_integer().unwrap();
let lvl_upper = entry[1].as_integer().unwrap();
let mon_id = entry[2].as_str().unwrap().to_owned();
(lvl_lower, lvl_upper, mon_id)
})
.collect::<Vec<_>>();
encounters.insert(
id.to_owned(),
EncounterTable {
id: id.to_owned(),
mons,
},
);
});
encounters
}
#[derive(Debug)]
pub struct GameDef {
pub encounter_tables: HashMap<String, EncounterTable>,
pub move_defs: HashMap<String, MoveDef>,
pub type_chart: TypeChart,
pub mon_instances: HashMap<String, MonInstance>,
pub mon_defs: HashMap<String, MonDef>,
}
impl GameDef {
pub fn from_toml(src: &toml::Value) -> Self {
let mon_defs = build_mon_defs(src.get("mon_defs").unwrap());
let mon_instances = build_mon_instances(src.get("mon_instances").unwrap());
let type_chart = build_type_chart(src.get("type_data").unwrap());
let move_defs = build_moves(src.get("moves").unwrap());
let encounter_tables = build_encounter_tables(src.get("encounter_tables").unwrap());
GameDef {
mon_defs,
mon_instances,
type_chart,
move_defs,
encounter_tables,
}
}
}
|
#[macro_use]
pub mod console;
mod application;
mod aspect;
mod attribute;
pub mod html;
mod lazy;
mod listener;
mod mailbox;
mod property;
pub mod router;
pub mod subscription;
pub mod svg;
pub mod url;
mod velement;
mod vnode;
mod vtext;
pub use self::application::{start, Application};
pub use self::aspect::Aspect;
pub use self::attribute::Attribute;
pub use self::lazy::Lazy;
pub use self::listener::Listener;
pub use self::mailbox::Mailbox;
pub use self::property::Property;
pub use self::subscription::{Subscription, Unsubscribe};
pub use self::velement::{h, s};
pub use self::velement::{VElement, VKeyedElement, VNonKeyedElement};
pub use self::vnode::VNode;
pub use self::vtext::VText;
use std::borrow::Cow;
pub type S = Cow<'static, str>;
pub fn select(selector: &str) -> Option<web_sys::Element> {
web_sys::window()?
.document()?
.query_selector(selector)
.ok()?
}
pub fn set_panic_hook() {
use std::sync::Once;
static PANIC_HOOK: Once = Once::new();
PANIC_HOOK.call_once(|| {
std::panic::set_hook(Box::new(|panic| {
crate::console::error(&panic.to_string());
}));
});
}
|
use std::io;
use std::os::unix::io::{RawFd, AsRawFd, FromRawFd};
use failure::Error;
use nix::unistd;
use nix::fcntl::{fcntl, FcntlArg, OFlag};
use nix::sys::termios::{tcgetattr, tcsetattr, cfmakeraw};
use nix::sys::termios::{Termios, SetArg};
use libc;
use futures::prelude::*;
use tokio::prelude::*;
use tokio::reactor::PollEvented2;
use evented_file::EventedFile;
fn dup_nonblock(fd: RawFd) -> Result<RawFd, failure::Error> {
// Note: Since `dup` returns `RawFd`, we need to manually `close` it
// on errors.
let fd = unistd::dup(fd)?;
let mut flags = match fcntl(fd, FcntlArg::F_GETFL) {
Ok(flags) => OFlag::from_bits_truncate(flags),
Err(e) => {
let _ = unistd::close(fd);
return Err(e.into());
}
};
flags.insert(OFlag::O_NONBLOCK);
match fcntl(fd, FcntlArg::F_SETFL(flags)) {
Ok(_) => Ok(fd),
Err(e) => {
let _ = unistd::close(fd);
Err(e.into())
}
}
}
pub struct RawTermRead {
stdin: PollEvented2<EventedFile>,
}
pub struct RawTermWrite {
prev_attrs: Termios,
stdout: PollEvented2<EventedFile>,
}
pub fn pair() -> Result<(RawTermRead, RawTermWrite), Error> {
Ok((RawTermRead::new()?, RawTermWrite::new()?))
}
impl RawTermRead {
pub fn new() -> Result<Self, Error> {
let stdin = PollEvented2::new({
let fd = dup_nonblock(libc::STDIN_FILENO)?;
unsafe { EventedFile::from_raw_fd(fd) }
});
Ok(RawTermRead {
stdin: stdin,
})
}
}
impl Read for RawTermRead {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.stdin.read(buf)
}
}
impl AsyncRead for RawTermRead {
}
impl RawTermWrite {
pub fn new() -> Result<Self, Error> {
let stdout = PollEvented2::new({
let fd = dup_nonblock(libc::STDOUT_FILENO)?;
unsafe { EventedFile::from_raw_fd(fd) }
});
let attrs = tcgetattr(stdout.get_ref().as_raw_fd())?;
let mut raw_attrs = attrs.clone();
cfmakeraw(&mut raw_attrs);
tcsetattr(stdout.get_ref().as_raw_fd(), SetArg::TCSANOW, &raw_attrs)?;
Ok(RawTermWrite {
prev_attrs: attrs,
stdout: stdout,
})
}
}
impl Drop for RawTermWrite {
fn drop(&mut self) {
let _ = tcsetattr(self.stdout.get_ref().as_raw_fd(),
SetArg::TCSANOW, &self.prev_attrs);
}
}
impl Write for RawTermWrite {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.stdout.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.stdout.flush()
}
}
impl AsyncWrite for RawTermWrite {
fn shutdown(&mut self) -> io::Result<Async<()>> {
self.stdout.shutdown()
}
}
|
pub fn mutability() {
println!("\n--- mutability() ---");
let immutable = 1;
println!("immutable={}", immutable);
//immutable = 2; //not allowed because immutable by default
let immutable = 2; //allowed because a is shadowed
println!("immutable={}", immutable);
let mut mutable = 1;
println!("mutable={}", mutable);
mutable = 2;
println!("mutable={}", mutable);
//mutable = "Mutable"; //mutation of type is not allowed!
} |
use super::atom::atom_val;
use super::error::PineResult;
use super::input::{Input, StrRange};
use super::utils::skip_ws;
use nom::{branch::alt, bytes::complete::tag, combinator::map};
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum BinaryOp {
Plus,
Minus,
Mul,
Div,
Mod,
Lt,
Leq,
Gt,
Geq,
Eq,
Neq,
BoolAnd,
BoolOr,
}
#[derive(Debug, Clone, PartialEq)]
pub struct BinaryOpNode {
pub op: BinaryOp,
pub range: StrRange,
}
impl BinaryOpNode {
pub fn new(op: BinaryOp, range: StrRange) -> BinaryOpNode {
BinaryOpNode { op, range }
}
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum UnaryOp {
Plus,
Minus,
BoolNot,
}
#[derive(Debug, Clone, PartialEq)]
pub struct UnaryOpNode {
pub op: UnaryOp,
pub range: StrRange,
}
impl UnaryOpNode {
pub fn new(op: UnaryOp, range: StrRange) -> UnaryOpNode {
UnaryOpNode { op, range }
}
}
pub fn unary_op(input: Input) -> PineResult<UnaryOpNode> {
let (input, _) = skip_ws(input)?;
alt((
map(tag("+"), |s| {
UnaryOpNode::new(UnaryOp::Plus, StrRange::from_input(&s))
}),
map(tag("-"), |s| {
UnaryOpNode::new(UnaryOp::Minus, StrRange::from_input(&s))
}),
map(atom_val("not"), |s| {
UnaryOpNode::new(UnaryOp::BoolNot, StrRange::from_input(&s))
}),
))(input)
}
pub fn binary_op(input: Input) -> PineResult<BinaryOpNode> {
let (input, _) = skip_ws(input)?;
alt((
map(tag("+"), |s| {
BinaryOpNode::new(BinaryOp::Plus, StrRange::from_input(&s))
}),
map(tag("-"), |s| {
BinaryOpNode::new(BinaryOp::Minus, StrRange::from_input(&s))
}),
map(tag("*"), |s| {
BinaryOpNode::new(BinaryOp::Mul, StrRange::from_input(&s))
}),
map(tag("/"), |s| {
BinaryOpNode::new(BinaryOp::Div, StrRange::from_input(&s))
}),
map(tag("%"), |s| {
BinaryOpNode::new(BinaryOp::Mod, StrRange::from_input(&s))
}),
map(tag("<="), |s| {
BinaryOpNode::new(BinaryOp::Leq, StrRange::from_input(&s))
}),
map(tag(">="), |s| {
BinaryOpNode::new(BinaryOp::Geq, StrRange::from_input(&s))
}),
map(tag("<"), |s| {
BinaryOpNode::new(BinaryOp::Lt, StrRange::from_input(&s))
}),
map(tag(">"), |s| {
BinaryOpNode::new(BinaryOp::Gt, StrRange::from_input(&s))
}),
map(tag("=="), |s| {
BinaryOpNode::new(BinaryOp::Eq, StrRange::from_input(&s))
}),
map(tag("!="), |s| {
BinaryOpNode::new(BinaryOp::Neq, StrRange::from_input(&s))
}),
map(atom_val("and"), |s| {
BinaryOpNode::new(BinaryOp::BoolAnd, StrRange::from_input(&s))
}),
map(atom_val("or"), |s| {
BinaryOpNode::new(BinaryOp::BoolOr, StrRange::from_input(&s))
}),
))(input)
}
#[cfg(test)]
mod tests {
use super::super::input::Position;
use super::*;
use std::convert::TryInto;
fn test_op(s: &str, op: BinaryOp, ch1: u32, ch2: u32) {
let test_input = Input::new_with_str(s);
let input_len: u32 = test_input.len().try_into().unwrap();
assert_eq!(
binary_op(test_input),
Ok((
Input::new("", Position::new(0, input_len), Position::max()),
BinaryOpNode::new(
op,
StrRange::new(Position::new(0, ch1), Position::new(0, ch2))
)
))
);
}
#[test]
fn binary_op_test() {
test_op(" +", BinaryOp::Plus, 1, 2);
test_op(" -", BinaryOp::Minus, 1, 2);
test_op(" *", BinaryOp::Mul, 1, 2);
test_op(" /", BinaryOp::Div, 1, 2);
test_op(" %", BinaryOp::Mod, 1, 2);
test_op(" >", BinaryOp::Gt, 1, 2);
test_op(" >=", BinaryOp::Geq, 1, 3);
test_op(" <", BinaryOp::Lt, 1, 2);
test_op(" <=", BinaryOp::Leq, 1, 3);
test_op(" ==", BinaryOp::Eq, 1, 3);
test_op(" !=", BinaryOp::Neq, 1, 3);
test_op(" and", BinaryOp::BoolAnd, 1, 4);
test_op(" or", BinaryOp::BoolOr, 1, 3);
}
fn test_unary_op(s: &str, op: UnaryOp, ch1: u32, ch2: u32) {
let test_input = Input::new_with_str(s);
let input_len: u32 = test_input.len().try_into().unwrap();
assert_eq!(
unary_op(test_input),
Ok((
Input::new("", Position::new(0, input_len), Position::max()),
UnaryOpNode::new(
op,
StrRange::new(Position::new(0, ch1), Position::new(0, ch2))
)
))
);
}
#[test]
fn unary_op_test() {
test_unary_op(" +", UnaryOp::Plus, 1, 2);
test_unary_op(" -", UnaryOp::Minus, 1, 2);
test_unary_op(" not", UnaryOp::BoolNot, 1, 4);
}
}
|
//! Modules for the runtime representation and interpretation of Piccolo bytecode.
pub mod chunk;
pub mod memory;
pub mod object;
pub mod op;
pub mod value;
pub mod vm;
pub type ConstantIdx = u16;
pub type LocalSlotIdx = u16;
pub type LocalScopeDepth = u16;
pub type Line = usize;
pub type ChunkOffset = usize;
pub type HeapPtr = usize;
pub type StringPtr = usize;
#[test]
fn ptr_funnies() {
use crate::{Object, Value};
#[derive(PartialEq, Debug)]
struct Upvalue {
pub data: Value,
}
impl Object for Upvalue {
fn type_name(&self) -> &'static str {
"upvalue"
}
}
impl core::fmt::Display for Upvalue {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{:?}", self.data)
}
}
#[derive(Debug, PartialEq)]
struct S(i64);
impl Object for S {
fn type_name(&self) -> &'static str {
"S"
}
fn eq(&self, rhs: &dyn Object) -> Option<bool> {
Some(rhs.downcast_ref::<S>()?.0 == self.0)
}
fn set(&mut self, _property: &str, value: Value) -> Option<()> {
match value {
Value::Integer(v) => self.0 = v,
_ => panic!(),
}
Some(())
}
}
impl core::fmt::Display for S {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{:?}", self)
}
}
unsafe {
let mut v: Vec<*mut dyn Object> = vec![Box::into_raw(Box::new(Upvalue {
data: Value::Integer(1),
}))];
// ok this seems fine
let x = v[0];
x.as_mut().unwrap().downcast_mut::<Upvalue>().unwrap().data = Value::Integer(3);
assert_eq!(
x.as_ref().unwrap().downcast_ref::<Upvalue>().unwrap().data,
Value::Integer(3)
);
assert!(std::ptr::eq(v[0], x));
// wtf
let y = v[0];
y.as_mut().unwrap().downcast_mut::<Upvalue>().unwrap().data = Value::Integer(32);
assert_eq!(
x.as_ref().unwrap().downcast_ref::<Upvalue>().unwrap().data,
Value::Integer(32)
);
assert_eq!(
y.as_ref().unwrap().downcast_ref::<Upvalue>().unwrap().data,
Value::Integer(32)
);
assert!(std::ptr::eq(v[0], x) && std::ptr::eq(v[0], y));
// y and x still refer to the old box, we need to drop it later
v[0] = Box::into_raw(Box::new(S(32)));
assert_eq!(v[0].as_ref().unwrap().downcast_ref::<S>().unwrap(), &S(32));
assert!(!std::ptr::eq(v[0], x) && !std::ptr::eq(v[0], y));
let v: Vec<Box<dyn Object>> = v.into_iter().map(|p| Box::from_raw(p)).collect();
drop(v);
drop(Box::from_raw(y));
}
}
|
//! Write systems to disk.
use error::Result;
use grafen::system::{Component, System};
use std::fs::File;
use std::io::{BufWriter, Write};
/// Output a system to disk as a GROMOS formatted file.
/// The filename extension is adjusted to .gro.
///
/// # Errors
/// Returns an error if the file could not be written to.
pub fn write_gromos(system: &System) -> Result<()> {
let path = system.output_path.with_extension("gro");
let file = File::create(path)?;
let mut writer = BufWriter::new(file);
writer.write_fmt(format_args!("{}\n", system.title))?;
writer.write_fmt(format_args!("{}\n", system.num_atoms()))?;
let mut res_num_total = 1;
let mut atom_num_total = 1;
for component in &system.components {
let (x0, y0, z0) = component.get_origin().to_tuple();
for residue in component.iter_residues() {
let res_name = residue.get_residue();
for (atom_name, position) in residue.get_atoms() {
// GROMOS loops the atom and residue indices at five digits, and so do we.
let res_num = res_num_total % 100_000;
let atom_num = atom_num_total % 100_000;
let (x, y, z) = (x0 + position.x, y0 + position.y, z0 + position.z);
write!(&mut writer, "{:>5}{:<5}{:>5}{:>5}{:>8.3}{:>8.3}{:>8.3}\n",
res_num, res_name.borrow(), atom_name.borrow(), atom_num,
x, y, z)?;
atom_num_total += 1;
}
res_num_total += 1;
}
}
let (dx, dy, dz) = system.box_size().to_tuple();
writer.write_fmt(format_args!("{:12.8} {:12.8} {:12.8}\n", dx, dy, dz))?;
Ok(())
}
|
use crate::{DocBase, VarType};
pub fn gen_doc() -> Vec<DocBase> {
let fn_doc = DocBase {
var_type: VarType::Function,
name: "highest",
signatures: vec![],
description: "Highest value for a given number of bars back.",
example: "",
returns: "Highest value.",
arguments: "",
remarks: "Two args version: x is a series and y is a length.
One arg version: x is a length. Algorithm uses high as a source series.",
links: "[lowest](#fun-lowest)",
};
vec![fn_doc]
}
|
//! External interrupt and event controller
use crate::rcc;
use stm32l0x3::{exti, EXTI, SYSCFG_COMP};
/// Extension trait that constrains the `EXTI` peripheral
pub trait ExtiExt {
/// Constrains the `EXTI` peripheral so it plays nicely with the other abstractions
fn constrain(self) -> Exti;
}
impl ExtiExt for EXTI {
fn constrain(self) -> Exti {
Exti {
exti0: EXTI0 {},
exti1: EXTI1 {},
exti2: EXTI2 {},
exti3: EXTI3 {},
exti4: EXTI4 {},
exti5: EXTI5 {},
exti6: EXTI6 {},
exti7: EXTI7 {},
exti8: EXTI8 {},
exti9: EXTI9 {},
exti10: EXTI10 {},
exti11: EXTI11 {},
exti12: EXTI12 {},
exti13: EXTI13 {},
exti14: EXTI14 {},
exti15: EXTI15 {},
}
}
}
/// Constrained EXTI peripheral
pub struct Exti {
pub exti0: EXTI0,
pub exti1: EXTI1,
pub exti2: EXTI2,
pub exti3: EXTI3,
pub exti4: EXTI4,
pub exti5: EXTI5,
pub exti6: EXTI6,
pub exti7: EXTI7,
pub exti8: EXTI8,
pub exti9: EXTI9,
pub exti10: EXTI10,
pub exti11: EXTI11,
pub exti12: EXTI12,
pub exti13: EXTI13,
pub exti14: EXTI14,
pub exti15: EXTI15,
}
pub enum GpioExtiSource {
GPIOA,
GPIOB,
GPIOC,
GPIOD,
GPIOE,
GPIOH,
}
impl GpioExtiSource {
fn syscfg_bits(self) -> u8 {
match self {
GpioExtiSource::GPIOA => 0b0000,
GpioExtiSource::GPIOB => 0b0001,
GpioExtiSource::GPIOC => 0b0010,
GpioExtiSource::GPIOD => 0b0011,
GpioExtiSource::GPIOE => 0b0100,
GpioExtiSource::GPIOH => 0b0101,
}
}
}
pub enum ExtiTrigger {
Rising,
Falling,
RisingAndFalling,
}
pub trait GpioExti {
fn configure_gpio_interrupt(
&mut self,
apb2: &mut rcc::APB2,
syscfg: &mut SYSCFG_COMP,
source: GpioExtiSource,
trigger: ExtiTrigger,
);
fn mask(&mut self);
fn unmask(&mut self);
fn is_pending(&self) -> bool;
fn clear_pending(&self);
}
macro_rules! exti_gpio_line {
($EXTIX:ident, $extix: ident, $SYSCFGR:ident, $imr:ident, $rtsr:ident, $ftsr:ident, $pif: ident) => {
pub struct $EXTIX {}
impl GpioExti for $EXTIX {
fn configure_gpio_interrupt(
&mut self,
apb2: &mut rcc::APB2,
syscfg: &mut SYSCFG_COMP,
source: GpioExtiSource,
trigger: ExtiTrigger,
) {
apb2.enr().modify(|_, w| w.syscfgen().set_bit());
syscfg
.$SYSCFGR
.modify(|_, w| unsafe { w.$extix().bits(source.syscfg_bits()) });
unsafe {
(*EXTI::ptr()).imr.modify(|_, w| w.$imr().set_bit());
}
match trigger {
ExtiTrigger::Rising | ExtiTrigger::RisingAndFalling => unsafe {
(*EXTI::ptr()).rtsr.modify(|_, w| w.$rtsr().set_bit());
},
_ => unsafe {
(*EXTI::ptr()).rtsr.modify(|_, w| w.$rtsr().clear_bit());
},
}
match trigger {
ExtiTrigger::Falling | ExtiTrigger::RisingAndFalling => unsafe {
(*EXTI::ptr()).ftsr.modify(|_, w| w.$ftsr().set_bit());
},
_ => unsafe {
(*EXTI::ptr()).ftsr.modify(|_, w| w.$ftsr().clear_bit());
},
}
}
fn mask(&mut self) {
unsafe {
(*EXTI::ptr()).imr.modify(|_, w| w.$imr().clear_bit());
}
}
fn unmask(&mut self) {
unsafe {
(*EXTI::ptr()).imr.modify(|_, w| w.$imr().set_bit());
}
}
fn is_pending(&self) -> bool {
unsafe { (*EXTI::ptr()).pr.read().$pif().bit() }
}
fn clear_pending(&self) {
unsafe {
(*EXTI::ptr()).pr.write(|w| w.$pif().set_bit());
}
}
}
};
}
exti_gpio_line!(EXTI0, exti0, exticr1, im0, rt0, ft0, pif0);
exti_gpio_line!(EXTI1, exti1, exticr1, im1, rt1, ft1, pif1);
exti_gpio_line!(EXTI2, exti2, exticr1, im2, rt2, ft2, pif2);
exti_gpio_line!(EXTI3, exti3, exticr1, im3, rt3, ft3, pif3);
exti_gpio_line!(EXTI4, exti4, exticr2, im4, rt4, ft4, pif4);
exti_gpio_line!(EXTI5, exti5, exticr2, im5, rt5, ft5, pif5);
exti_gpio_line!(EXTI6, exti6, exticr2, im6, rt6, ft6, pif6);
exti_gpio_line!(EXTI7, exti7, exticr2, im7, rt7, ft7, pif7);
exti_gpio_line!(EXTI8, exti8, exticr3, im8, rt8, ft8, pif8);
exti_gpio_line!(EXTI9, exti9, exticr3, im9, rt9, ft9, pif9);
exti_gpio_line!(EXTI10, exti10, exticr3, im10, rt10, ft10, pif10);
exti_gpio_line!(EXTI11, exti11, exticr3, im11, rt11, ft11, pif11);
exti_gpio_line!(EXTI12, exti12, exticr4, im12, rt12, ft12, pif12);
exti_gpio_line!(EXTI13, exti13, exticr4, im13, rt13, ft13, pif13);
exti_gpio_line!(EXTI14, exti14, exticr4, im14, rt14, ft14, pif14);
exti_gpio_line!(EXTI15, exti15, exticr4, im15, rt15, ft15, pif15);
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct ForegroundText(pub i32);
impl ForegroundText {
pub const Dark: ForegroundText = ForegroundText(0i32);
pub const Light: ForegroundText = ForegroundText(1i32);
}
impl ::core::convert::From<i32> for ForegroundText {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for ForegroundText {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for ForegroundText {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.StartScreen.ForegroundText;i4)");
}
impl ::windows::core::DefaultType for ForegroundText {
type DefaultType = Self;
}
#[repr(transparent)]
#[doc(hidden)]
pub struct IJumpList(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IJumpList {
type Vtable = IJumpList_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0234c3e_cd6f_4cb6_a611_61fd505f3ed1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IJumpList_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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut JumpListSystemGroupKind) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: JumpListSystemGroupKind) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IJumpListItem(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IJumpListItem {
type Vtable = IJumpListItem_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7adb6717_8b5d_4820_995b_9b418dbe48b0);
}
#[repr(C)]
#[doc(hidden)]
pub struct IJumpListItem_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 JumpListItemKind) -> ::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 bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, 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, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IJumpListItemStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IJumpListItemStatics {
type Vtable = IJumpListItemStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf1bfc4e8_c7aa_49cb_8dde_ecfccd7ad7e4);
}
#[repr(C)]
#[doc(hidden)]
pub struct IJumpListItemStatics_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, arguments: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::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 IJumpListStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IJumpListStatics {
type Vtable = IJumpListStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa7e0c681_e67e_4b74_8250_3f322c4d92c3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IJumpListStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryTile(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTile {
type Vtable = ISecondaryTile_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e9e51e0_2bb5_4bc0_bb8d_42b23abcc88d);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTile_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, value: ::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, value: ::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, value: ::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, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: TileOptions) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TileOptions) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ForegroundText) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ForegroundText) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::Color) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::Color) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, invocationpoint: super::super::Foundation::Point, 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, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] 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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, invocationpoint: super::super::Foundation::Point, 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, selection: super::super::Foundation::Rect, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(all(feature = "Foundation", feature = "UI_Popups"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, selection: super::super::Foundation::Rect, preferredplacement: super::Popups::Placement, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "UI_Popups")))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryTile2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTile2 {
type Vtable = ISecondaryTile2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb2f6cc35_3250_4990_923c_294ab4b694dd);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTile2_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, value: ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryTileFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTileFactory {
type Vtable = ISecondaryTileFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x57f52ca0_51bc_4abf_8ebf_627a0398b05a);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTileFactory_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, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, shortname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, arguments: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, tileoptions: TileOptions, logoreference: ::windows::core::RawPtr, 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, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, shortname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, arguments: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, tileoptions: TileOptions, logoreference: ::windows::core::RawPtr, widelogoreference: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryTileFactory2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTileFactory2 {
type Vtable = ISecondaryTileFactory2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x274b8a3b_522d_448e_9eb2_d0672ab345c8);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTileFactory2_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, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, displayname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, arguments: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, square150x150logo: ::windows::core::RawPtr, desiredsize: TileSize, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryTileStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTileStatics {
type Vtable = ISecondaryTileStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x99908dae_d051_4676_87fe_9ec242d83c74);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTileStatics_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, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut bool) -> ::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,
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, applicationid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize,
#[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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISecondaryTileVisualElements(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTileVisualElements {
type Vtable = ISecondaryTileVisualElements_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1d8df333_815e_413f_9f50_a81da70a96b2);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTileVisualElements_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: ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ForegroundText) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ForegroundText) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: super::Color) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::Color) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: 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 ISecondaryTileVisualElements2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTileVisualElements2 {
type Vtable = ISecondaryTileVisualElements2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfd2e31d0_57dc_4794_8ecf_5682f5f3e6ef);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTileVisualElements2_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: ::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)]
#[doc(hidden)]
pub struct ISecondaryTileVisualElements3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTileVisualElements3 {
type Vtable = ISecondaryTileVisualElements3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x56b55ad6_d15c_40f4_81e7_57ffd8f8a4e9);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTileVisualElements3_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: ::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)]
#[doc(hidden)]
pub struct ISecondaryTileVisualElements4(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISecondaryTileVisualElements4 {
type Vtable = ISecondaryTileVisualElements4_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x66566117_b544_40d2_8d12_74d4ec24d04c);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISecondaryTileVisualElements4_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 IStartScreenManager(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IStartScreenManager {
type Vtable = IStartScreenManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4a1dcbcb_26e9_4eb4_8933_859eb6ecdb29);
}
#[repr(C)]
#[doc(hidden)]
pub struct IStartScreenManager_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 = "System")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "System"))] usize,
#[cfg(feature = "ApplicationModel_Core")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, applistentry: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(not(feature = "ApplicationModel_Core"))] usize,
#[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, applistentry: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "ApplicationModel_Core", feature = "Foundation")))] usize,
#[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, applistentry: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "ApplicationModel_Core", feature = "Foundation")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IStartScreenManager2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IStartScreenManager2 {
type Vtable = IStartScreenManager2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08a716b6_316b_4ad9_acb8_fe9cf00bd608);
}
#[repr(C)]
#[doc(hidden)]
pub struct IStartScreenManager2_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, tileid: ::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, tileid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IStartScreenManagerStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IStartScreenManagerStatics {
type Vtable = IStartScreenManagerStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7865ef0f_b585_464e_8993_34e8f8738d48);
}
#[repr(C)]
#[doc(hidden)]
pub struct IStartScreenManagerStatics_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,
#[cfg(feature = "System")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, user: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "System"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ITileMixedRealityModel(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITileMixedRealityModel {
type Vtable = ITileMixedRealityModel_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0764e5b_887d_4242_9a19_3d0a4ea78031);
}
#[repr(C)]
#[doc(hidden)]
pub struct ITileMixedRealityModel_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: ::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,
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics", feature = "Perception_Spatial"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics", feature = "Perception_Spatial")))] usize,
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics", feature = "Perception_Spatial"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Foundation_Numerics", feature = "Perception_Spatial")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ITileMixedRealityModel2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITileMixedRealityModel2 {
type Vtable = ITileMixedRealityModel2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x439470b2_d7c5_410b_8319_9486a27b6c67);
}
#[repr(C)]
#[doc(hidden)]
pub struct ITileMixedRealityModel2_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, value: TileMixedRealityModelActivationBehavior) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TileMixedRealityModelActivationBehavior) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVisualElementsRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVisualElementsRequest {
type Vtable = IVisualElementsRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc138333a_9308_4072_88cc_d068db347c68);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVisualElementsRequest_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,
#[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")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVisualElementsRequestDeferral(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVisualElementsRequestDeferral {
type Vtable = IVisualElementsRequestDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa1656eb0_0126_4357_8204_bd82bb2a046d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVisualElementsRequestDeferral_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVisualElementsRequestedEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVisualElementsRequestedEventArgs {
type Vtable = IVisualElementsRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b6fc982_3a0d_4ece_af96_cd17e1b00b2d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVisualElementsRequestedEventArgs_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)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct JumpList(pub ::windows::core::IInspectable);
impl JumpList {
#[cfg(feature = "Foundation_Collections")]
pub fn Items(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<JumpListItem>> {
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::IVector<JumpListItem>>(result__)
}
}
pub fn SystemGroupKind(&self) -> ::windows::core::Result<JumpListSystemGroupKind> {
let this = self;
unsafe {
let mut result__: JumpListSystemGroupKind = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<JumpListSystemGroupKind>(result__)
}
}
pub fn SetSystemGroupKind(&self, value: JumpListSystemGroupKind) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "Foundation")]
pub fn SaveAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn LoadCurrentAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<JumpList>> {
Self::IJumpListStatics(|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<JumpList>>(result__)
})
}
pub fn IsSupported() -> ::windows::core::Result<bool> {
Self::IJumpListStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
})
}
pub fn IJumpListStatics<R, F: FnOnce(&IJumpListStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<JumpList, IJumpListStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for JumpList {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.JumpList;{b0234c3e-cd6f-4cb6-a611-61fd505f3ed1})");
}
unsafe impl ::windows::core::Interface for JumpList {
type Vtable = IJumpList_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0234c3e_cd6f_4cb6_a611_61fd505f3ed1);
}
impl ::windows::core::RuntimeName for JumpList {
const NAME: &'static str = "Windows.UI.StartScreen.JumpList";
}
impl ::core::convert::From<JumpList> for ::windows::core::IUnknown {
fn from(value: JumpList) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&JumpList> for ::windows::core::IUnknown {
fn from(value: &JumpList) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for JumpList {
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 JumpList {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<JumpList> for ::windows::core::IInspectable {
fn from(value: JumpList) -> Self {
value.0
}
}
impl ::core::convert::From<&JumpList> for ::windows::core::IInspectable {
fn from(value: &JumpList) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for JumpList {
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 JumpList {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for JumpList {}
unsafe impl ::core::marker::Sync for JumpList {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct JumpListItem(pub ::windows::core::IInspectable);
impl JumpListItem {
pub fn Kind(&self) -> ::windows::core::Result<JumpListItemKind> {
let this = self;
unsafe {
let mut result__: JumpListItemKind = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<JumpListItemKind>(result__)
}
}
pub fn Arguments(&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 RemovedByUser(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn Description(&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 SetDescription<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn DisplayName(&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).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn GroupName(&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).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetGroupName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetLogo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn CreateWithArguments<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(arguments: Param0, displayname: Param1) -> ::windows::core::Result<JumpListItem> {
Self::IJumpListItemStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), arguments.into_param().abi(), displayname.into_param().abi(), &mut result__).from_abi::<JumpListItem>(result__)
})
}
pub fn CreateSeparator() -> ::windows::core::Result<JumpListItem> {
Self::IJumpListItemStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<JumpListItem>(result__)
})
}
pub fn IJumpListItemStatics<R, F: FnOnce(&IJumpListItemStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<JumpListItem, IJumpListItemStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for JumpListItem {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.JumpListItem;{7adb6717-8b5d-4820-995b-9b418dbe48b0})");
}
unsafe impl ::windows::core::Interface for JumpListItem {
type Vtable = IJumpListItem_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7adb6717_8b5d_4820_995b_9b418dbe48b0);
}
impl ::windows::core::RuntimeName for JumpListItem {
const NAME: &'static str = "Windows.UI.StartScreen.JumpListItem";
}
impl ::core::convert::From<JumpListItem> for ::windows::core::IUnknown {
fn from(value: JumpListItem) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&JumpListItem> for ::windows::core::IUnknown {
fn from(value: &JumpListItem) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for JumpListItem {
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 JumpListItem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<JumpListItem> for ::windows::core::IInspectable {
fn from(value: JumpListItem) -> Self {
value.0
}
}
impl ::core::convert::From<&JumpListItem> for ::windows::core::IInspectable {
fn from(value: &JumpListItem) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for JumpListItem {
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 JumpListItem {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for JumpListItem {}
unsafe impl ::core::marker::Sync for JumpListItem {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct JumpListItemKind(pub i32);
impl JumpListItemKind {
pub const Arguments: JumpListItemKind = JumpListItemKind(0i32);
pub const Separator: JumpListItemKind = JumpListItemKind(1i32);
}
impl ::core::convert::From<i32> for JumpListItemKind {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JumpListItemKind {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for JumpListItemKind {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.StartScreen.JumpListItemKind;i4)");
}
impl ::windows::core::DefaultType for JumpListItemKind {
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 JumpListSystemGroupKind(pub i32);
impl JumpListSystemGroupKind {
pub const None: JumpListSystemGroupKind = JumpListSystemGroupKind(0i32);
pub const Frequent: JumpListSystemGroupKind = JumpListSystemGroupKind(1i32);
pub const Recent: JumpListSystemGroupKind = JumpListSystemGroupKind(2i32);
}
impl ::core::convert::From<i32> for JumpListSystemGroupKind {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for JumpListSystemGroupKind {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for JumpListSystemGroupKind {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.StartScreen.JumpListSystemGroupKind;i4)");
}
impl ::windows::core::DefaultType for JumpListSystemGroupKind {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryTile(pub ::windows::core::IInspectable);
impl SecondaryTile {
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<SecondaryTile, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn SetTileId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn TileId(&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 SetArguments<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&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() }
}
pub fn Arguments(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetShortName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn ShortName(&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).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetDisplayName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn DisplayName(&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).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetLogo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetSmallLogo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SmallLogo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetWideLogo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn WideLogo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetLockScreenBadgeLogo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn LockScreenBadgeLogo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
pub fn SetLockScreenDisplayBadgeAndTileText(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn LockScreenDisplayBadgeAndTileText(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetTileOptions(&self, value: TileOptions) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn TileOptions(&self) -> ::windows::core::Result<TileOptions> {
let this = self;
unsafe {
let mut result__: TileOptions = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TileOptions>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetForegroundText(&self, value: ForegroundText) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "deprecated")]
pub fn ForegroundText(&self) -> ::windows::core::Result<ForegroundText> {
let this = self;
unsafe {
let mut result__: ForegroundText = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ForegroundText>(result__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetBackgroundColor<'a, Param0: ::windows::core::IntoParam<'a, super::Color>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
pub fn BackgroundColor(&self) -> ::windows::core::Result<super::Color> {
let this = self;
unsafe {
let mut result__: super::Color = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Color>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RequestCreateAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RequestCreateAsyncWithPoint<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Point>>(&self, invocationpoint: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), invocationpoint.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RequestCreateAsyncWithRect<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, selection: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "UI_Popups"))]
pub fn RequestCreateAsyncWithRectAndPlacement<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, selection: Param0, preferredplacement: super::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RequestDeleteAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RequestDeleteAsyncWithPoint<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Point>>(&self, invocationpoint: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).35)(::core::mem::transmute_copy(this), invocationpoint.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RequestDeleteAsyncWithRect<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, selection: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).36)(::core::mem::transmute_copy(this), selection.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "UI_Popups"))]
pub fn RequestDeleteAsyncWithRectAndPlacement<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Rect>>(&self, selection: Param0, preferredplacement: super::Popups::Placement) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).37)(::core::mem::transmute_copy(this), selection.into_param().abi(), preferredplacement, &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn UpdateAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).38)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
pub fn SetPhoneticName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISecondaryTile2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn PhoneticName(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<ISecondaryTile2>(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 VisualElements(&self) -> ::windows::core::Result<SecondaryTileVisualElements> {
let this = &::windows::core::Interface::cast::<ISecondaryTile2>(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::<SecondaryTileVisualElements>(result__)
}
}
pub fn SetRoamingEnabled(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISecondaryTile2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn RoamingEnabled(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ISecondaryTile2>(self)?;
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__)
}
}
#[cfg(feature = "Foundation")]
pub fn VisualElementsRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<SecondaryTile, VisualElementsRequestedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> {
let this = &::windows::core::Interface::cast::<ISecondaryTile2>(self)?;
unsafe {
let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveVisualElementsRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISecondaryTile2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn CreateTile<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(
tileid: Param0,
shortname: Param1,
displayname: Param2,
arguments: Param3,
tileoptions: TileOptions,
logoreference: Param5,
) -> ::windows::core::Result<SecondaryTile> {
Self::ISecondaryTileFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), tileid.into_param().abi(), shortname.into_param().abi(), displayname.into_param().abi(), arguments.into_param().abi(), tileoptions, logoreference.into_param().abi(), &mut result__).from_abi::<SecondaryTile>(result__)
})
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn CreateWideTile<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param5: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param6: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(
tileid: Param0,
shortname: Param1,
displayname: Param2,
arguments: Param3,
tileoptions: TileOptions,
logoreference: Param5,
widelogoreference: Param6,
) -> ::windows::core::Result<SecondaryTile> {
Self::ISecondaryTileFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), tileid.into_param().abi(), shortname.into_param().abi(), displayname.into_param().abi(), arguments.into_param().abi(), tileoptions, logoreference.into_param().abi(), widelogoreference.into_param().abi(), &mut result__).from_abi::<SecondaryTile>(result__)
})
}
pub fn CreateWithId<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(tileid: Param0) -> ::windows::core::Result<SecondaryTile> {
Self::ISecondaryTileFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), tileid.into_param().abi(), &mut result__).from_abi::<SecondaryTile>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn CreateMinimalTile<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(tileid: Param0, displayname: Param1, arguments: Param2, square150x150logo: Param3, desiredsize: TileSize) -> ::windows::core::Result<SecondaryTile> {
Self::ISecondaryTileFactory2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), tileid.into_param().abi(), displayname.into_param().abi(), arguments.into_param().abi(), square150x150logo.into_param().abi(), desiredsize, &mut result__).from_abi::<SecondaryTile>(result__)
})
}
pub fn Exists<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(tileid: Param0) -> ::windows::core::Result<bool> {
Self::ISecondaryTileStatics(|this| unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), tileid.into_param().abi(), &mut result__).from_abi::<bool>(result__)
})
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<SecondaryTile>>> {
Self::ISecondaryTileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<SecondaryTile>>>(result__)
})
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllForApplicationAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(applicationid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<SecondaryTile>>> {
Self::ISecondaryTileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), applicationid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<SecondaryTile>>>(result__)
})
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))]
pub fn FindAllForPackageAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<SecondaryTile>>> {
Self::ISecondaryTileStatics(|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<super::super::Foundation::Collections::IVectorView<SecondaryTile>>>(result__)
})
}
pub fn ISecondaryTileFactory<R, F: FnOnce(&ISecondaryTileFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SecondaryTile, ISecondaryTileFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ISecondaryTileFactory2<R, F: FnOnce(&ISecondaryTileFactory2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SecondaryTile, ISecondaryTileFactory2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn ISecondaryTileStatics<R, F: FnOnce(&ISecondaryTileStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<SecondaryTile, ISecondaryTileStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryTile {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.SecondaryTile;{9e9e51e0-2bb5-4bc0-bb8d-42b23abcc88d})");
}
unsafe impl ::windows::core::Interface for SecondaryTile {
type Vtable = ISecondaryTile_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9e9e51e0_2bb5_4bc0_bb8d_42b23abcc88d);
}
impl ::windows::core::RuntimeName for SecondaryTile {
const NAME: &'static str = "Windows.UI.StartScreen.SecondaryTile";
}
impl ::core::convert::From<SecondaryTile> for ::windows::core::IUnknown {
fn from(value: SecondaryTile) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryTile> for ::windows::core::IUnknown {
fn from(value: &SecondaryTile) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryTile {
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 SecondaryTile {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryTile> for ::windows::core::IInspectable {
fn from(value: SecondaryTile) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryTile> for ::windows::core::IInspectable {
fn from(value: &SecondaryTile) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryTile {
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 SecondaryTile {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryTile {}
unsafe impl ::core::marker::Sync for SecondaryTile {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SecondaryTileVisualElements(pub ::windows::core::IInspectable);
impl SecondaryTileVisualElements {
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetSquare30x30Logo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Square30x30Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn SetSquare70x70Logo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&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() }
}
#[cfg(feature = "deprecated")]
#[cfg(feature = "Foundation")]
pub fn Square70x70Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetSquare150x150Logo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Square150x150Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetWide310x150Logo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Wide310x150Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetSquare310x310Logo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Square310x310Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
pub fn SetForegroundText(&self, value: ForegroundText) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ForegroundText(&self) -> ::windows::core::Result<ForegroundText> {
let this = self;
unsafe {
let mut result__: ForegroundText = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ForegroundText>(result__)
}
}
pub fn SetBackgroundColor<'a, Param0: ::windows::core::IntoParam<'a, super::Color>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn BackgroundColor(&self) -> ::windows::core::Result<super::Color> {
let this = self;
unsafe {
let mut result__: super::Color = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Color>(result__)
}
}
pub fn SetShowNameOnSquare150x150Logo(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ShowNameOnSquare150x150Logo(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetShowNameOnWide310x150Logo(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ShowNameOnWide310x150Logo(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetShowNameOnSquare310x310Logo(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ShowNameOnSquare310x310Logo(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetSquare71x71Logo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISecondaryTileVisualElements2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Square71x71Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = &::windows::core::Interface::cast::<ISecondaryTileVisualElements2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn SetSquare44x44Logo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISecondaryTileVisualElements3>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Square44x44Logo(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = &::windows::core::Interface::cast::<ISecondaryTileVisualElements3>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
pub fn MixedRealityModel(&self) -> ::windows::core::Result<TileMixedRealityModel> {
let this = &::windows::core::Interface::cast::<ISecondaryTileVisualElements4>(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::<TileMixedRealityModel>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for SecondaryTileVisualElements {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.SecondaryTileVisualElements;{1d8df333-815e-413f-9f50-a81da70a96b2})");
}
unsafe impl ::windows::core::Interface for SecondaryTileVisualElements {
type Vtable = ISecondaryTileVisualElements_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1d8df333_815e_413f_9f50_a81da70a96b2);
}
impl ::windows::core::RuntimeName for SecondaryTileVisualElements {
const NAME: &'static str = "Windows.UI.StartScreen.SecondaryTileVisualElements";
}
impl ::core::convert::From<SecondaryTileVisualElements> for ::windows::core::IUnknown {
fn from(value: SecondaryTileVisualElements) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SecondaryTileVisualElements> for ::windows::core::IUnknown {
fn from(value: &SecondaryTileVisualElements) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SecondaryTileVisualElements {
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 SecondaryTileVisualElements {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SecondaryTileVisualElements> for ::windows::core::IInspectable {
fn from(value: SecondaryTileVisualElements) -> Self {
value.0
}
}
impl ::core::convert::From<&SecondaryTileVisualElements> for ::windows::core::IInspectable {
fn from(value: &SecondaryTileVisualElements) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SecondaryTileVisualElements {
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 SecondaryTileVisualElements {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for SecondaryTileVisualElements {}
unsafe impl ::core::marker::Sync for SecondaryTileVisualElements {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct StartScreenManager(pub ::windows::core::IInspectable);
impl StartScreenManager {
#[cfg(feature = "System")]
pub fn User(&self) -> ::windows::core::Result<super::super::System::User> {
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::System::User>(result__)
}
}
#[cfg(feature = "ApplicationModel_Core")]
pub fn SupportsAppListEntry<'a, Param0: ::windows::core::IntoParam<'a, super::super::ApplicationModel::Core::AppListEntry>>(&self, applistentry: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), applistentry.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))]
pub fn ContainsAppListEntryAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::ApplicationModel::Core::AppListEntry>>(&self, applistentry: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), applistentry.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(all(feature = "ApplicationModel_Core", feature = "Foundation"))]
pub fn RequestAddAppListEntryAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::ApplicationModel::Core::AppListEntry>>(&self, applistentry: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), applistentry.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
pub fn GetDefault() -> ::windows::core::Result<StartScreenManager> {
Self::IStartScreenManagerStatics(|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::<StartScreenManager>(result__)
})
}
#[cfg(feature = "System")]
pub fn GetForUser<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::User>>(user: Param0) -> ::windows::core::Result<StartScreenManager> {
Self::IStartScreenManagerStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), user.into_param().abi(), &mut result__).from_abi::<StartScreenManager>(result__)
})
}
#[cfg(feature = "Foundation")]
pub fn ContainsSecondaryTileAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, tileid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = &::windows::core::Interface::cast::<IStartScreenManager2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), tileid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn TryRemoveSecondaryTileAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, tileid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<bool>> {
let this = &::windows::core::Interface::cast::<IStartScreenManager2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), tileid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<bool>>(result__)
}
}
pub fn IStartScreenManagerStatics<R, F: FnOnce(&IStartScreenManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<StartScreenManager, IStartScreenManagerStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for StartScreenManager {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.StartScreenManager;{4a1dcbcb-26e9-4eb4-8933-859eb6ecdb29})");
}
unsafe impl ::windows::core::Interface for StartScreenManager {
type Vtable = IStartScreenManager_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4a1dcbcb_26e9_4eb4_8933_859eb6ecdb29);
}
impl ::windows::core::RuntimeName for StartScreenManager {
const NAME: &'static str = "Windows.UI.StartScreen.StartScreenManager";
}
impl ::core::convert::From<StartScreenManager> for ::windows::core::IUnknown {
fn from(value: StartScreenManager) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&StartScreenManager> for ::windows::core::IUnknown {
fn from(value: &StartScreenManager) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for StartScreenManager {
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 StartScreenManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<StartScreenManager> for ::windows::core::IInspectable {
fn from(value: StartScreenManager) -> Self {
value.0
}
}
impl ::core::convert::From<&StartScreenManager> for ::windows::core::IInspectable {
fn from(value: &StartScreenManager) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for StartScreenManager {
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 StartScreenManager {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for StartScreenManager {}
unsafe impl ::core::marker::Sync for StartScreenManager {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct TileMixedRealityModel(pub ::windows::core::IInspectable);
impl TileMixedRealityModel {
#[cfg(feature = "Foundation")]
pub fn SetUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn Uri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__)
}
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics", feature = "Perception_Spatial"))]
pub fn SetBoundingBox<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::IReference<super::super::Perception::Spatial::SpatialBoundingBox>>>(&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() }
}
#[cfg(all(feature = "Foundation", feature = "Foundation_Numerics", feature = "Perception_Spatial"))]
pub fn BoundingBox(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Perception::Spatial::SpatialBoundingBox>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Perception::Spatial::SpatialBoundingBox>>(result__)
}
}
pub fn SetActivationBehavior(&self, value: TileMixedRealityModelActivationBehavior) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITileMixedRealityModel2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ActivationBehavior(&self) -> ::windows::core::Result<TileMixedRealityModelActivationBehavior> {
let this = &::windows::core::Interface::cast::<ITileMixedRealityModel2>(self)?;
unsafe {
let mut result__: TileMixedRealityModelActivationBehavior = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TileMixedRealityModelActivationBehavior>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for TileMixedRealityModel {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.TileMixedRealityModel;{b0764e5b-887d-4242-9a19-3d0a4ea78031})");
}
unsafe impl ::windows::core::Interface for TileMixedRealityModel {
type Vtable = ITileMixedRealityModel_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb0764e5b_887d_4242_9a19_3d0a4ea78031);
}
impl ::windows::core::RuntimeName for TileMixedRealityModel {
const NAME: &'static str = "Windows.UI.StartScreen.TileMixedRealityModel";
}
impl ::core::convert::From<TileMixedRealityModel> for ::windows::core::IUnknown {
fn from(value: TileMixedRealityModel) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&TileMixedRealityModel> for ::windows::core::IUnknown {
fn from(value: &TileMixedRealityModel) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TileMixedRealityModel {
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 TileMixedRealityModel {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<TileMixedRealityModel> for ::windows::core::IInspectable {
fn from(value: TileMixedRealityModel) -> Self {
value.0
}
}
impl ::core::convert::From<&TileMixedRealityModel> for ::windows::core::IInspectable {
fn from(value: &TileMixedRealityModel) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TileMixedRealityModel {
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 TileMixedRealityModel {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for TileMixedRealityModel {}
unsafe impl ::core::marker::Sync for TileMixedRealityModel {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct TileMixedRealityModelActivationBehavior(pub i32);
impl TileMixedRealityModelActivationBehavior {
pub const Default: TileMixedRealityModelActivationBehavior = TileMixedRealityModelActivationBehavior(0i32);
pub const None: TileMixedRealityModelActivationBehavior = TileMixedRealityModelActivationBehavior(1i32);
}
impl ::core::convert::From<i32> for TileMixedRealityModelActivationBehavior {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for TileMixedRealityModelActivationBehavior {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for TileMixedRealityModelActivationBehavior {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.StartScreen.TileMixedRealityModelActivationBehavior;i4)");
}
impl ::windows::core::DefaultType for TileMixedRealityModelActivationBehavior {
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 TileOptions(pub u32);
impl TileOptions {
pub const None: TileOptions = TileOptions(0u32);
pub const ShowNameOnLogo: TileOptions = TileOptions(1u32);
pub const ShowNameOnWideLogo: TileOptions = TileOptions(2u32);
pub const CopyOnDeployment: TileOptions = TileOptions(4u32);
}
impl ::core::convert::From<u32> for TileOptions {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for TileOptions {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for TileOptions {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.StartScreen.TileOptions;u4)");
}
impl ::windows::core::DefaultType for TileOptions {
type DefaultType = Self;
}
impl ::core::ops::BitOr for TileOptions {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for TileOptions {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for TileOptions {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for TileOptions {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for TileOptions {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct TileSize(pub i32);
impl TileSize {
pub const Default: TileSize = TileSize(0i32);
pub const Square30x30: TileSize = TileSize(1i32);
pub const Square70x70: TileSize = TileSize(2i32);
pub const Square150x150: TileSize = TileSize(3i32);
pub const Wide310x150: TileSize = TileSize(4i32);
pub const Square310x310: TileSize = TileSize(5i32);
pub const Square71x71: TileSize = TileSize(6i32);
pub const Square44x44: TileSize = TileSize(7i32);
}
impl ::core::convert::From<i32> for TileSize {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for TileSize {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for TileSize {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.StartScreen.TileSize;i4)");
}
impl ::windows::core::DefaultType for TileSize {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VisualElementsRequest(pub ::windows::core::IInspectable);
impl VisualElementsRequest {
pub fn VisualElements(&self) -> ::windows::core::Result<SecondaryTileVisualElements> {
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::<SecondaryTileVisualElements>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn AlternateVisualElements(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<SecondaryTileVisualElements>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<SecondaryTileVisualElements>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn Deadline(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__)
}
}
pub fn GetDeferral(&self) -> ::windows::core::Result<VisualElementsRequestDeferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<VisualElementsRequestDeferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for VisualElementsRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.VisualElementsRequest;{c138333a-9308-4072-88cc-d068db347c68})");
}
unsafe impl ::windows::core::Interface for VisualElementsRequest {
type Vtable = IVisualElementsRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc138333a_9308_4072_88cc_d068db347c68);
}
impl ::windows::core::RuntimeName for VisualElementsRequest {
const NAME: &'static str = "Windows.UI.StartScreen.VisualElementsRequest";
}
impl ::core::convert::From<VisualElementsRequest> for ::windows::core::IUnknown {
fn from(value: VisualElementsRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&VisualElementsRequest> for ::windows::core::IUnknown {
fn from(value: &VisualElementsRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for VisualElementsRequest {
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 VisualElementsRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<VisualElementsRequest> for ::windows::core::IInspectable {
fn from(value: VisualElementsRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&VisualElementsRequest> for ::windows::core::IInspectable {
fn from(value: &VisualElementsRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for VisualElementsRequest {
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 VisualElementsRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for VisualElementsRequest {}
unsafe impl ::core::marker::Sync for VisualElementsRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VisualElementsRequestDeferral(pub ::windows::core::IInspectable);
impl VisualElementsRequestDeferral {
pub fn Complete(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for VisualElementsRequestDeferral {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.VisualElementsRequestDeferral;{a1656eb0-0126-4357-8204-bd82bb2a046d})");
}
unsafe impl ::windows::core::Interface for VisualElementsRequestDeferral {
type Vtable = IVisualElementsRequestDeferral_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa1656eb0_0126_4357_8204_bd82bb2a046d);
}
impl ::windows::core::RuntimeName for VisualElementsRequestDeferral {
const NAME: &'static str = "Windows.UI.StartScreen.VisualElementsRequestDeferral";
}
impl ::core::convert::From<VisualElementsRequestDeferral> for ::windows::core::IUnknown {
fn from(value: VisualElementsRequestDeferral) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&VisualElementsRequestDeferral> for ::windows::core::IUnknown {
fn from(value: &VisualElementsRequestDeferral) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for VisualElementsRequestDeferral {
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 VisualElementsRequestDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<VisualElementsRequestDeferral> for ::windows::core::IInspectable {
fn from(value: VisualElementsRequestDeferral) -> Self {
value.0
}
}
impl ::core::convert::From<&VisualElementsRequestDeferral> for ::windows::core::IInspectable {
fn from(value: &VisualElementsRequestDeferral) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for VisualElementsRequestDeferral {
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 VisualElementsRequestDeferral {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for VisualElementsRequestDeferral {}
unsafe impl ::core::marker::Sync for VisualElementsRequestDeferral {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VisualElementsRequestedEventArgs(pub ::windows::core::IInspectable);
impl VisualElementsRequestedEventArgs {
pub fn Request(&self) -> ::windows::core::Result<VisualElementsRequest> {
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::<VisualElementsRequest>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for VisualElementsRequestedEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.StartScreen.VisualElementsRequestedEventArgs;{7b6fc982-3a0d-4ece-af96-cd17e1b00b2d})");
}
unsafe impl ::windows::core::Interface for VisualElementsRequestedEventArgs {
type Vtable = IVisualElementsRequestedEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b6fc982_3a0d_4ece_af96_cd17e1b00b2d);
}
impl ::windows::core::RuntimeName for VisualElementsRequestedEventArgs {
const NAME: &'static str = "Windows.UI.StartScreen.VisualElementsRequestedEventArgs";
}
impl ::core::convert::From<VisualElementsRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: VisualElementsRequestedEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&VisualElementsRequestedEventArgs> for ::windows::core::IUnknown {
fn from(value: &VisualElementsRequestedEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for VisualElementsRequestedEventArgs {
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 VisualElementsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<VisualElementsRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: VisualElementsRequestedEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&VisualElementsRequestedEventArgs> for ::windows::core::IInspectable {
fn from(value: &VisualElementsRequestedEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for VisualElementsRequestedEventArgs {
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 VisualElementsRequestedEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for VisualElementsRequestedEventArgs {}
unsafe impl ::core::marker::Sync for VisualElementsRequestedEventArgs {}
|
pub struct Runtime {
pub module: String,
pub module_instance: String,
pub store: String,
}
impl Runtime {
fn new() -> Self {
Runtime {
module: "m1".to_string(),
module_instance: "m2".to_string(),
store: "m3".to_string(),
}
}
fn exec() {
println!("exec ...");
}
}
|
#[macro_use]
extern crate defmac;
fn solve(p: usize, m: usize) {
let mut circle = linked_list::LinkedList::new();
circle.push_front(0);
let mut score = vec![0; p];
let mut cur = circle.cursor();
cur.next();
defmac!(forward => if cur.next().is_none() { cur.next(); } );
defmac!(backward => if cur.prev().is_none() { cur.prev(); } );
for i in 1..=m {
if i % 23 != 0 {
for _ in 0..2 {
forward!();
}
cur.insert(i);
} else {
for _ in 0..7 {
backward!();
}
score[i%p] += i + cur.remove().unwrap();
}
}
let best = score.iter().max().unwrap();
println!("{}", best);
}
fn main() {
let p = 416;
let m = 71975;
solve(p, m);
solve(p, m * 100);
}
|
use proconio::input;
fn main() {
input! {
n: usize,
a: [u32; n],
};
let ans = a.into_iter().filter(|&x| x % 2 == 0).collect::<Vec<_>>();
for i in 0..ans.len() {
print!("{}", ans[i]);
if i + 1 < ans.len() {
print!(" ");
} else {
print!("\n");
}
}
}
|
pub type Label = String;
#[derive(Debug, PartialEq, Clone)]
pub enum Source {
Expansion,
Accumulator,
Memory,
Operand(u8),
LabelLo(Label),
LabelHi(Label),
}
#[derive(Debug, PartialEq, Clone)]
pub enum Destination {
Memory,
MemAddressLo,
MemAddressHi,
Accumulator,
AccumulatorPlus,
AccumulatorNand,
ProgramCounter,
ProgramCounterLatch,
Led,
CarrySet,
CarryReset,
ExpansionSelect,
Serial,
}
#[derive(Debug, PartialEq, Clone)]
pub struct Operation {
pub src: Source,
pub dest: Destination,
pub cond_1: bool,
pub cond_carry: bool,
}
|
use crate::prelude::*;
#[repr(C)]
#[derive(Debug, Default)]
pub struct VkPhysicalDeviceLimits {
pub maxImageDimension1D: u32,
pub maxImageDimension2D: u32,
pub maxImageDimension3D: u32,
pub maxImageDimensionCube: u32,
pub maxImageArrayLayers: u32,
pub maxTexelBufferElements: u32,
pub maxUniformBufferRange: u32,
pub maxStorageBufferRange: u32,
pub maxPushConstantsSize: u32,
pub maxMemoryAllocationCount: u32,
pub maxSamplerAllocationCount: u32,
pub bufferImageGranularity: VkDeviceSize,
pub sparseAddressSpaceSize: VkDeviceSize,
pub maxBoundDescriptorSets: u32,
pub maxPerStageDescriptorSamplers: u32,
pub maxPerStageDescriptorUniformBuffers: u32,
pub maxPerStageDescriptorStorageBuffers: u32,
pub maxPerStageDescriptorSampledImages: u32,
pub maxPerStageDescriptorStorageImages: u32,
pub maxPerStageDescriptorInputAttachments: u32,
pub maxPerStageResources: u32,
pub maxDescriptorSetSamplers: u32,
pub maxDescriptorSetUniformBuffers: u32,
pub maxDescriptorSetUniformBuffersDynamic: u32,
pub maxDescriptorSetStorageBuffers: u32,
pub maxDescriptorSetStorageBuffersDynamic: u32,
pub maxDescriptorSetSampledImages: u32,
pub maxDescriptorSetStorageImages: u32,
pub maxDescriptorSetInputAttachments: u32,
pub maxVertexInputAttributes: u32,
pub maxVertexInputBindings: u32,
pub maxVertexInputAttributeOffset: u32,
pub maxVertexInputBindingStride: u32,
pub maxVertexOutputComponents: u32,
pub maxTessellationGenerationLevel: u32,
pub maxTessellationPatchSize: u32,
pub maxTessellationControlPerVertexInputComponents: u32,
pub maxTessellationControlPerVertexOutputComponents: u32,
pub maxTessellationControlPerPatchOutputComponents: u32,
pub maxTessellationControlTotalOutputComponents: u32,
pub maxTessellationEvaluationInputComponents: u32,
pub maxTessellationEvaluationOutputComponents: u32,
pub maxGeometryShaderInvocations: u32,
pub maxGeometryInputComponents: u32,
pub maxGeometryOutputComponents: u32,
pub maxGeometryOutputVertices: u32,
pub maxGeometryTotalOutputComponents: u32,
pub maxFragmentInputComponents: u32,
pub maxFragmentOutputAttachments: u32,
pub maxFragmentDualSrcAttachments: u32,
pub maxFragmentCombinedOutputResources: u32,
pub maxComputeSharedMemorySize: u32,
pub maxComputeWorkGroupCount: [u32; 3],
pub maxComputeWorkGroupInvocations: u32,
pub maxComputeWorkGroupSize: [u32; 3],
pub subPixelPrecisionBits: u32,
pub subTexelPrecisionBits: u32,
pub mipmapPrecisionBits: u32,
pub maxDrawIndexedIndexValue: u32,
pub maxDrawIndirectCount: u32,
pub maxSamplerLodBias: f32,
pub maxSamplerAnisotropy: f32,
pub maxViewports: u32,
pub maxViewportDimensions: [u32; 2],
pub viewportBoundsRange: [f32; 2],
pub viewportSubPixelBits: u32,
pub minMemoryMapAlignment: usize,
pub minTexelBufferOffsetAlignment: VkDeviceSize,
pub minUniformBufferOffsetAlignment: VkDeviceSize,
pub minStorageBufferOffsetAlignment: VkDeviceSize,
pub minTexelOffset: i32,
pub maxTexelOffset: u32,
pub minTexelGatherOffset: i32,
pub maxTexelGatherOffset: u32,
pub minInterpolationOffset: f32,
pub maxInterpolationOffset: f32,
pub subPixelInterpolationOffsetBits: u32,
pub maxFramebufferWidth: u32,
pub maxFramebufferHeight: u32,
pub maxFramebufferLayers: u32,
pub framebufferColorSampleCounts: VkSampleCountFlagBits,
pub framebufferDepthSampleCounts: VkSampleCountFlagBits,
pub framebufferStencilSampleCounts: VkSampleCountFlagBits,
pub framebufferNoAttachmentsSampleCounts: VkSampleCountFlagBits,
pub maxColorAttachments: u32,
pub sampledImageColorSampleCounts: VkSampleCountFlagBits,
pub sampledImageIntegerSampleCounts: VkSampleCountFlagBits,
pub sampledImageDepthSampleCounts: VkSampleCountFlagBits,
pub sampledImageStencilSampleCounts: VkSampleCountFlagBits,
pub storageImageSampleCounts: VkSampleCountFlagBits,
pub maxSampleMaskWords: u32,
pub timestampComputeAndGraphics: VkBool32,
pub timestampPeriod: f32,
pub maxClipDistances: u32,
pub maxCullDistances: u32,
pub maxCombinedClipAndCullDistances: u32,
pub discreteQueuePriorities: u32,
pub pointSizeRange: [f32; 2],
pub lineWidthRange: [f32; 2],
pub pointSizeGranularity: f32,
pub lineWidthGranularity: f32,
pub strictLines: VkBool32,
pub standardSampleLocations: VkBool32,
pub optimalBufferCopyOffsetAlignment: VkDeviceSize,
pub optimalBufferCopyRowPitchAlignment: VkDeviceSize,
pub nonCoherentAtomSize: VkDeviceSize,
}
|
use std::{
cell::RefCell,
collections::HashMap,
fmt::{Debug, Display},
rc::Rc,
};
use super::{
environment::Environment, instance::Instance, interpreter::Interpreter, stmt::Stmt,
value::Value,
};
pub trait Callable {
fn arity(&self) -> usize;
fn call(&self, interpreter: &mut Interpreter, arguments: Vec<Value>) -> Result<Value, String>;
}
#[derive(Clone)]
pub struct NativeFunction {
name: String,
arity: usize,
callable: fn(&Interpreter, Vec<Value>) -> Result<Value, String>,
}
impl Display for NativeFunction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "(fn {} {})", self.name, self.arity)
}
}
impl PartialEq for NativeFunction {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.arity == other.arity
}
}
impl Debug for NativeFunction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "(nativefn {} {})", self.name, self.arity)
}
}
impl NativeFunction {
pub fn new(
name: String,
arity: usize,
callable: fn(&Interpreter, Vec<Value>) -> Result<Value, String>,
) -> Self {
Self {
name,
arity,
callable,
}
}
}
impl Callable for NativeFunction {
fn arity(&self) -> usize {
self.arity
}
fn call(&self, interpreter: &mut Interpreter, arguments: Vec<Value>) -> Result<Value, String> {
if arguments.len() != self.arity() {
return Err(format!(
"Expected {} arguments but got {} arguments",
self.arity(),
arguments.len()
));
}
(self.callable)(interpreter, arguments)
}
}
#[derive(Clone)]
pub struct Function {
is_initializer: bool,
declaration: Stmt,
closure: Rc<RefCell<Environment>>,
}
impl Function {
pub fn new(declaration: Stmt, closure: Rc<RefCell<Environment>>, is_initializer: bool) -> Self {
if let Stmt::FunctionDeclaration(_, _, _) = declaration {
Self {
declaration,
closure,
is_initializer,
}
} else {
panic!()
}
}
pub fn bind(&self, instance: &Instance) -> Result<Value, String> {
let mut environment = Environment::new(HashMap::new(), Some(self.closure.clone()));
environment.define("this".to_string(), Value::Instance(instance.clone()));
Ok(Value::Function(Function::new(
self.declaration.clone(),
Rc::from(RefCell::from(environment)),
self.is_initializer,
)))
}
}
impl Display for Function {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Stmt::FunctionDeclaration(name, parameters, _) = &self.declaration {
write!(f, "(fn {}(", name.lexeme)?;
for parameter in parameters {
write!(f, " {}", parameter)?;
}
write!(f, "))")
} else {
panic!()
}
}
}
impl PartialEq for Function {
fn eq(&self, other: &Self) -> bool {
self.declaration == other.declaration
}
}
impl Debug for Function {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Stmt::FunctionDeclaration(name, parameters, _) = &self.declaration {
write!(f, "(fn {}(", name.lexeme)?;
for parameter in parameters {
write!(f, " {}", parameter)?;
}
write!(f, "))")
} else {
panic!()
}
}
}
impl Callable for Function {
fn arity(&self) -> usize {
if let Stmt::FunctionDeclaration(_, parameters, _) = &self.declaration {
parameters.len()
} else {
panic!()
}
}
fn call(&self, interpreter: &mut Interpreter, arguments: Vec<Value>) -> Result<Value, String> {
if arguments.len() != self.arity() {
return Err(format!(
"Expected {} arguments but got {} arguments",
self.arity(),
arguments.len()
));
}
let mut environment = Environment::new(HashMap::new(), Some(self.closure.clone()));
if let Stmt::FunctionDeclaration(_, parameters, body) = &self.declaration {
for (parameter, argument) in parameters.iter().zip(arguments) {
environment.define(parameter.lexeme.clone(), argument);
}
match interpreter.execute_block(body.to_vec(), environment) {
Ok(_) => Ok(if self.is_initializer {
self.closure.borrow().get_at(0, "this".to_string())?
} else {
Value::Nil
}),
Err(value) => {
if self.is_initializer {
self.closure.borrow().get_at(0, "this".to_string())
} else {
Ok(value)
}
}
}
} else {
panic!()
}
}
}
|
use std::sync::mpsc::sync_channel;
const N: u32 = 10;
#[tokio::test]
async fn explore_sync_channel() {
let (tx, rx) = sync_channel(0);
let th1 = tokio::spawn(async move {
let start = std::time::Instant::now();
for id in 0..N {
println!("sent value = {:?} at {:?}", id, start.elapsed());
tx.send(id);
}
});
let th2 = tokio::task::spawn_blocking(move || {
std::thread::sleep(std::time::Duration::from_millis(100));
while let Ok(value) = rx.recv() {
println!("got value = {:?}", value);
std::thread::sleep(std::time::Duration::from_millis(100));
}
});
tokio::join!(th1, th2);
}
|
extern crate serde;
use serde::Serialize;
use serde::Deserialize;
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthRequestData {
#[serde(skip_serializing_if = "Option::is_none")]
pub personal_number: Option<String>,
pub end_user_ip: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub requirement: Option<Requirement>
}
impl AuthRequestData {
pub fn new(end_user_ip:&str) -> AuthRequestData {
AuthRequestData{personal_number: None, end_user_ip: String::from(end_user_ip), requirement: Some(Requirement{card_reader: Some(CardReader::Class2), certificate_policies: vec![CertificatePolicy::BankidOnFile, CertificatePolicy::BankidMobile], auto_start_token_required: Some(true), allow_fingerprint: None})}
}
pub fn new_with_personal_number(personal_number: String, end_user_ip: String) -> AuthRequestData {
AuthRequestData{personal_number: Some(personal_number), end_user_ip: end_user_ip, requirement: None}
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignRequestData {
#[serde(skip_serializing_if = "Option::is_none")]
pub personal_number: Option<String>,
pub end_user_ip: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub requirement: Option<Requirement>,
pub user_visible_data: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_non_visible_data: Option<String>
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthSignResponse {
pub auto_start_token: Option<String>,
pub order_ref: String
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CardReader {
#[serde(rename = "class1")] Class1, // default value in BankID service
#[serde(rename = "class2")] Class2
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CollectResponse {
pub order_ref: String,
pub status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
pub hint_code: Option<HintCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub completion_data: Option<CompletionData>,
}
impl std::fmt::Display for CollectResponse {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let hint_code = match &self.hint_code {
Some(hint_code) => match hint_code {
HintCode::PendingOutstandingTransaction => " hint_code: PendingOutstandingTransaction",
HintCode::PendingNoClient=> " hint_code: PendingNoClient",
HintCode::PendingStarted=> " hint_code: PendingStarted",
HintCode::PendingUserSign=> " hint_code: PendingUserSign",
HintCode::FailedExpiredTransaction=> " hint_code: FailedExpiredTransaction",
HintCode::FailedCertificateErr=> " hint_code: FailedCertificateErr",
HintCode::FailedUserCancel=> " hint_code: FailedUserCancel",
HintCode::FailedCancelled=> " hint_code: FailedCancelled",
HintCode::FailedStartFailed=> " hint_code: FailedStartFailed",
HintCode::Unknown=> " hint_code: Unknown",
},
None => " hint_code: None",
};
write!(f, "CollectResponse(order_ref: {} status: {} hint_code: {})", self.order_ref, self.status, hint_code)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CollectRequestData {
pub order_ref: String,
}
#[derive(Serialize, Deserialize, Clone)]
pub enum HintCode {
#[serde(rename = "outstandingTransaction")] PendingOutstandingTransaction,
#[serde(rename = "noClient")] PendingNoClient,
#[serde(rename = "started")] PendingStarted,
#[serde(rename = "userSign")] PendingUserSign,
#[serde(rename = "expiredTransaction")] FailedExpiredTransaction,
#[serde(rename = "certificateErr")] FailedCertificateErr,
#[serde(rename = "userCancel")] FailedUserCancel,
#[serde(rename = "cancelled")] FailedCancelled,
#[serde(rename = "startFailed")] FailedStartFailed,
#[serde(other)] Unknown
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum Status {
Pending,
Failed,
Complete
}
impl std::fmt::Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
Status::Pending => f.write_str("Pending"),
Status::Failed => f.write_str("Failed"),
Status::Complete => f.write_str("Complete")
}
}
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CompletionData {
pub user: UserData,
pub device: Option<DeviceData>,
pub cert: Option<CertData>,
pub signature: Option<String>, // TODO unkown if this is optional...check
pub ocsp_response: Option<String>, // TODO unkown if this is optional...check
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserData {
pub personal_number: String,
pub name: String,
pub given_name: String,
pub surname: String
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DeviceData {
pub ip_address: String
}
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CertData {
pub not_before: String,
pub not_after: String,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CertificatePolicy {
// production values
#[serde(rename = "1.2.752.78.1.1")] BankidOnFile,
#[serde(rename = "1.2.752.78.1.2")] BankidOnSmartCard,
#[serde(rename = "1.2.752.78.1.5")] BankidMobile,
#[serde(rename = "1.2.752.71.1.3")] NordeaEidOnFileSmartCard,
// test values
#[serde(rename = "1.2.3.4.5")] TestBankidOnFile,
#[serde(rename = "1.2.3.4.10")] TestBankidOnSmartCard,
#[serde(rename = "1.2.3.4.25")] TestBankidMobile,
#[serde(rename = "1.2.752.71.1.3")] TestNordeaEidOnFileSmartCard,
#[serde(rename = "1.2.752.60.1.6")] TestBankidForSomeBankidBanks
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Requirement {
pub card_reader: Option<CardReader>,
pub certificate_policies: Vec<CertificatePolicy>,
// issuerCn is not implemented
// from bankid spec:
// if issuerCn is not defined allallow_fingerprint relevant BankID
// and Nordea issuers are allowed.
#[serde(skip_serializing_if = "Option::is_none")]
pub auto_start_token_required: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_fingerprint: Option<bool>
} |
use proconio::{input, marker::Usize1};
fn main() {
input! {
n: usize,
a: [Usize1; n],
};
let mut called = vec![false; n];
for i in 0..n {
if called[i] == false {
called[a[i]] = true;
}
}
let mut ans = Vec::new();
for i in 0..n {
if called[i] == false {
ans.push(i + 1);
}
}
println!("{}", ans.len());
for i in 0..ans.len() {
print!("{}", ans[i]);
if i + 1 < ans.len() {
print!(" ");
} else {
print!("\n");
}
}
}
|
use memblock::*;
fn main() {
let mut source = MemBlock::new((5, 5));
let mut copy = MemBlock::new((2, 2));
let dma_target = (0, 1);
println!("Source:");
source.table();
for y in 0..copy.size().1 {
for x in 0..copy.size().0 {
copy.write((x, y), 0xFFFFFFFF);
}
}
println!("\nCopy:");
copy.table();
println!("\nDma `©` onto `&source` at location: {:?}", dma_target);
source.dma(dma_target, ©);
println!("\nSource:");
source.table();
}
|
use crate::display::Display;
use crate::keyboard::Keyboard;
use crate::ram::Ram;
///
/// CHIP-8 memory map
///
/// +---------------+= 0xFFF (4095) End of Chip-8 RAM
/// | |
/// | |
/// | |
/// | |
/// | |
/// | 0x200 to 0xFFF|
/// | Chip-8 |
/// | Program / Data|
/// | Space |
/// | |
/// | |
/// | |
/// +- - - - - - - -+= 0x600 (1536) Start of ETI 660 Chip-8 programs
/// | |
/// | |
/// | |
/// +---------------+= 0x200 (512) Start of most Chip-8 programs
/// | 0x000 to 0x1FF|
/// | Reserved for |
/// | interpreter |
/// +---------------+= 0x000 (0) Start of Chip-8 RAM
///
pub struct Cpu {
/// index register
pub i: u16,
/// program counter
pub pc: u16,
/// registers usually referred to as Vx, where x is a hexadecimal digit (0 through F)
pub v: [u8; 16],
/// Stack: used to store the address that the interpreter should return to when finished with a subroutine
/// Chip-8 allows for up to 16 levels of nested subroutines.
pub stack: [u16; 16],
/// stack pointer
pub sp: u8,
/// Delay timer
pub dt: u8,
/// Sound timer
pub st: u8,
}
fn read_word(memory: [u8; 4096], index: u16) -> u16 {
let i = index as usize;
(memory[i] as u16) << 8 | (memory[i + 1] as u16)
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
i: 0,
pc: 0x200,
v: [0; 16],
stack: [0; 16],
sp: 0,
dt: 0,
st: 0,
}
}
pub fn reset(&mut self) {
self.i = 0;
self.pc = 0x200;
self.v = [0; 16];
self.stack = [0; 16];
self.sp = 0;
self.dt = 0;
self.st = 0;
}
pub fn execute_cycle(&mut self, ram: &mut Ram, keyboard: &mut Keyboard, display: &mut Display) {
let opcode = read_word(ram.memory, self.pc);
self.pc += 2;
self.process_opcode(opcode, ram, keyboard, display);
}
fn process_opcode(&mut self, opcode: u16, ram: &mut Ram, keyboard: &mut Keyboard, display: &mut Display) {
match opcode {
0x00E0 => {
// 00E0 - CLS
// Clear the display.
display.clear();
}
0x00EE => {
// 00EE - RET
// Return from a subroutine.
// The interpreter sets the program counter to the address at the top of the stack,
// then subtracts 1 from the stack pointer.
self.pc = self.stack[self.sp as usize];
self.sp -= 1;
}
0x1000..=0x1FFF => {
// 1nnn - JP addr
// 1nnn - JP addr - Jump to location nnn.
// The interpreter sets the program counter to nnn.
self.pc = opcode & 0x0FFF;
}
0x2000..=0x2FFF => {
// 2nnn - CALL addr
// Call subroutine at nnn.
// The interpreter increments the stack pointer, then puts the current PC on the top of the stack.
// The PC is then set to nnn.
self.sp += 1;
self.stack[self.sp as usize] = self.pc;
self.pc = opcode & 0x0FFF;
}
0x3000..=0x3FFF => {
// 3xkk - SE Vx, byte
// Skip next instruction if Vx = kk.
// The interpreter compares register Vx to kk, and if they are equal, increments the program counter by 2.
let x = (opcode & 0x0F00) >> 8;
let value = (opcode & 0x00FF) as u8;
if self.v[x as usize] == value {
self.pc += 2;
}
}
0x4000..=0x4FFF => {
// 4xkk - SNE Vx, byte
// Skip next instruction if Vx != kk.
// The interpreter compares register Vx to kk, and if they are not equal, increments the program counter by 2.
let x = (opcode & 0x0F00) >> 8;
let value = (opcode & 0x00FF) as u8;
if self.v[x as usize] != value {
self.pc += 2;
}
}
0x5000..=0x5FFF => {
// 5xy0 - SE Vx, Vy
// Skip next instruction if Vx = Vy.
// The interpreter compares register Vx to register Vy, and if they are equal, increments the program counter by 2.
let x = (opcode & 0x0F00) >> 8;
let y = (opcode & 0x00F0) >> 4;
if self.v[x as usize] == self.v[y as usize] {
self.pc += 2;
}
}
0x6000..=0x6FFF => {
// 6xkk - LD Vx, byte
// Set Vx = kk.
// The interpreter puts the value kk into register Vx.
let x = (opcode & 0x0F00) >> 8;
let kk = (opcode & 0x00FF) as u8;
self.v[x as usize] = kk;
}
0x7000..=0x7FFF => {
// 7xkk - ADD Vx, byte
// Set Vx = Vx + kk.
// Adds the value kk to the value of register Vx, then stores the result in Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
let kk = (opcode & 0x00FF) as u8;
self.v[x] = self.v[x].wrapping_add(kk);
}
0x8000..=0x8FF0 => {
// 8xy0 - LD Vx, Vy
// Set Vx = Vy.
// Stores the value of register Vy in register Vx.
let x = (opcode & 0x0F00) >> 8;
let y = (opcode & 0x00F0) >> 4;
self.v[x as usize] = self.v[y as usize];
}
0x8001..=0x8FF1 => {
// 8xy1 - OR Vx, Vy
// Set Vx = Vx OR Vy.
//
// Performs a bitwise OR on the values of Vx and Vy, then stores the result in Vx.
// A bitwise OR compares the corresponding bits from two values, and if either bit is 1,
// then the same bit in the result is also 1. Otherwise, it is 0.
let x = ((opcode & 0x0F00) >> 8) as usize;
let y = ((opcode & 0x00F0) >> 4) as usize;
self.v[x] = self.v[x] | self.v[y];
}
0x8002..=0x8FF2 => {
// 8xy2 - AND Vx, Vy
// Set Vx = Vx AND Vy.
//
// Performs a bitwise AND on the values of Vx and Vy, then stores the result in Vx.
// A bitwise AND compares the corrseponding bits from two values, and if both bits are 1,
// then the same bit in the result is also 1. Otherwise, it is 0.
let x = ((opcode & 0x0F00) >> 8) as usize;
let y = ((opcode & 0x00F0) >> 4) as usize;
self.v[x] = self.v[x] & self.v[y];
}
0x8003..=0x8FF3 => {
// 8xy3 - XOR Vx, Vy
// Set Vx = Vx XOR Vy.
//
// Performs a bitwise exclusive OR on the values of Vx and Vy, then stores the result in Vx.
// An exclusive OR compares the corrseponding bits from two values, and if the bits are not both the same,
// then the corresponding bit in the result is set to 1. Otherwise, it is 0.
let x = ((opcode & 0x0F00) >> 8) as usize;
let y = ((opcode & 0x00F0) >> 4) as usize;
self.v[x] = self.v[x] ^ self.v[y];
}
0x8004..=0x8FF4 => {
// 8xy4 - ADD Vx, Vy
// Set Vx = Vx + Vy, set VF = carry.
//
// The values of Vx and Vy are added together.
// If the result is greater than 8 bits (i.e., > 255,) VF is set to 1, otherwise 0.
// Only the lowest 8 bits of the result are kept, and stored in Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
let y = ((opcode & 0x00F0) >> 4) as usize;
let result = self.v[x] as u16 + self.v[y] as u16;
self.v[0xF as usize] = if result > 255 { 1 } else { 0 };
self.v[x] = self.v[x].wrapping_add(self.v[y]);
}
0x8005..=0x8FF5 => {
// 8xy5 - SUB Vx, Vy
// Set Vx = Vx - Vy, set VF = NOT borrow.
//
// If Vx > Vy, then VF is set to 1, otherwise 0. Then Vy is subtracted from Vx, and the results stored in Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
let y = ((opcode & 0x00F0) >> 4) as usize;
let xx = self.v[x];
let yy = self.v[y];
self.v[0xF as usize] = if xx > yy { 1 } else { 0 };
self.v[x] = xx.wrapping_sub(yy);
}
0x8006..=0x8FF6 => {
// 8xy6 - SHR Vx {, Vy}
// Set Vx = Vx SHR 1.
//
// If the least-significant bit of Vx is 1, then VF is set to 1, otherwise 0. Then Vx is divided by 2.
let x = ((opcode & 0x0F00) >> 8) as usize;
self.v[0xF as usize] = if self.v[x] & 0x01 > 0 { 1 } else { 0 };
self.v[x] = self.v[x] >> 1;
}
0x8007..=0x8FF7 => {
// 8xy7 - SUBN Vx, Vy
// Set Vx = Vy - Vx, set VF = NOT borrow.
//
// If Vy > Vx, then VF is set to 1, otherwise 0. Then Vx is subtracted from Vy, and the results stored in Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
let y = ((opcode & 0x00F0) >> 4) as usize;
let xx = self.v[x];
let yy = self.v[y];
self.v[0xF as usize] = if yy > xx { 1 } else { 0 };
self.v[x] = yy.wrapping_sub(xx);
}
0x800E..=0x8FFE => {
// 8xyE - SHL Vx {, Vy}
// Set Vx = Vx SHL 1.
//
// If the most-significant bit of Vx is 1, then VF is set to 1, otherwise to 0. Then Vx is multiplied by 2.
let x = ((opcode & 0x0F00) >> 8) as usize;
self.v[0xF as usize] = if self.v[x] & 0x80 > 0 { 1 } else { 0 };
self.v[x] <<= 1;
}
0x9000..=0x9FF0 => {
// 9xy0 - SNE Vx, Vy
// Skip next instruction if Vx != Vy.
//
// The values of Vx and Vy are compared, and if they are not equal, the program counter is increased by 2.
let x = ((opcode & 0x0F00) >> 8) as usize;
let y = ((opcode & 0x00F0) >> 4) as usize;
if self.v[x] != self.v[y] {
self.pc += 2;
}
}
0xA000..=0xAFFF => {
// Annn - LD I, addr
// Set I = nnn.
//
// The value of register I is set to nnn.
self.i = opcode & 0x0FFF;
}
0xB000..=0xBFFF => {
// Bnnn - JP V0, addr
// Jump to location nnn + V0.
//
// The program counter is set to nnn plus the value of V0.
let delta = opcode & 0x0FFF;
self.pc = (self.v[0] as u16).wrapping_add(delta);
}
0xC000..=0xCFFF => {
// Cxkk - RND Vx, byte
// Set Vx = random byte AND kk.
//
// The interpreter generates a random number from 0 to 255, which is then ANDed with the value kk.
// The results are stored in Vx. See instruction 8xy2 for more information on AND.
let x = ((opcode & 0x0F00) >> 8) as usize;
let kk = (opcode & 0x00FF) as u8;
//let random: u8 = rand::thread_rng().gen_range(0, 255);
// TODO
let random: u8 = 0x4C;
self.v[x] = kk & random;
}
0xD000..=0xDFFF => {
// Dxyn - DRW Vx, Vy, nibble
// Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision.
//
// The interpreter reads n bytes from memory, starting at the address stored in I.
// These bytes are then displayed as sprites on screen at coordinates (Vx, Vy).
// Sprites are XORed onto the existing screen. If this causes any pixels to be erased,
// VF is set to 1, otherwise it is set to 0. If the sprite is positioned so part of
// it is outside the coordinates of the display, it wraps around to the opposite side of the screen.
// See instruction 8xy3 for more information on XOR, and section 2.4, Display, for more information on the Chip-8 screen and sprites.
let xi = ((opcode & 0x0F00) >> 8) as usize;
let yi = ((opcode & 0x00F0) >> 4) as usize;
let x = self.v[xi] as usize;
let y = self.v[yi] as usize;
let n = (opcode & 0x000F) as u16;
let from = self.i as usize;
let to = (self.i + n) as usize;
let collision = display.draw(x, y, &ram.memory[from..to]);
self.v[0xF] = if collision { 1 } else { 0 };
//println!("{:?}", &ram.memory[from..to]);
}
0xE09E..=0xEF9E => {
// Ex9E - SKP Vx
// Skip next instruction if key with the value of Vx is pressed.
//
// Checks the keyboard, and if the key corresponding to the value of Vx is currently in the down position, PC is increased by 2.
let x = ((opcode & 0x0F00) >> 8) as usize;
if keyboard.is_pressed(self.v[x]) {
self.pc += 2;
}
}
0xE0A1..=0xEFA1 => {
// ExA1 - SKNP Vx
// Skip next instruction if key with the value of Vx is not pressed.
//
// Checks the keyboard, and if the key corresponding to the value of Vx is currently in the up position, PC is increased by 2.
let x = ((opcode & 0x0F00) >> 8) as usize;
if keyboard.is_released(self.v[x]) {
self.pc += 2;
}
}
0xF007..=0xFF07 => {
// Fx07 - LD Vx, DT
// Set Vx = delay timer value.
//
// The value of DT is placed into Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
self.v[x] = self.dt;
}
0xF00A..=0xFF0A => {
// Fx0A - LD Vx, K
// Wait for a key press, store the value of the key in Vx.
//
// All execution stops until a key is pressed, then the value of that key is stored in Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
let key_pressed = keyboard.wait_key();
self.v[x] = key_pressed;
}
0xF015..=0xFF15 => {
// Fx15 - LD DT, Vx
// Set delay timer = Vx.
//
// DT is set equal to the value of Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
self.dt = self.v[x];
}
0xF018..=0xFF18 => {
// Fx18 - LD ST, Vx
// Set sound timer = Vx.
//
// ST is set equal to the value of Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
self.st = self.v[x];
}
0xF01E..=0xFF1E => {
// Fx1E - ADD I, Vx
// Set I = I + Vx.
//
// The values of I and Vx are added, and the results are stored in I.
let x = ((opcode & 0x0F00) >> 8) as usize;
self.i += self.v[x] as u16;
}
0xF029..=0xFF29 => {
// Fx29 - LD F, Vx
// Set I = location of sprite for digit Vx.
//
// The value of I is set to the location for the hexadecimal sprite corresponding to the value of Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
self.i = self.v[x] as u16 * 5;
}
0xF033..=0xFF33 => {
// Fx33 - LD B, Vx
// Store BCD representation of Vx in memory locations I, I+1, and I+2.
//
// The interpreter takes the decimal value of Vx, and places the hundreds digit
// in memory at location in I, the tens digit at location I+1, and the ones digit at location I+2.
let x = ((opcode & 0x0F00) >> 8) as usize;
let i = self.i as usize;
let num = self.v[x];
ram.memory[i] = num / 100;
ram.memory[i + 1] = (num / 10) % 10;
ram.memory[i + 2] = (num % 100) % 10;
}
0xF055..=0xFF55 => {
// Fx55 - LD [I], Vx
// Store registers V0 through Vx in memory starting at location I.
//
// The interpreter copies the values of registers V0 through Vx into memory, starting at the address in I.
let x = ((opcode & 0x0F00) >> 8) as usize;
for i in 0..x {
ram.memory[self.i as usize + i] = self.v[i];
}
}
0xF065..=0xFF65 => {
// Fx65 - LD Vx, [I]
// Read registers V0 through Vx from memory starting at location I.
//
// The interpreter reads values from memory starting at location I into registers V0 through Vx.
let x = ((opcode & 0x0F00) >> 8) as usize;
for i in 0..x {
self.v[i] = ram.memory[self.i as usize + i];
}
}
_ => {
//panic!("Unknown opcode: {:x}", opcode);
}
}
}
}
|
//! The following SMB2 Access Mask flag values can be used when accessing a file, pipe or printer.
use rand::{
distributions::{Distribution, Standard},
Rng,
};
/// File_Pipe_Printer_Access_Mask (4 bytes): For a file, pipe, or printer,
/// the value MUST be constructed using the following values (for a printer,
/// the value MUST have at least one of the following: FILE_WRITE_DATA,
/// FILE_APPEND_DATA, or GENERIC_WRITE).
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum FileAccessMask {
ReadData,
WriteData,
AppendData,
ReadEa,
WriteEa,
DeleteChild,
Execute,
ReadAttributes,
WriteAttributes,
Delete,
ReadControl,
WriteDac,
WriteOwner,
Synchronize,
AccessSystemSecurity,
MaximumAllowed,
GenericAll,
GenericExecute,
GenericWrite,
GenericRead,
}
impl FileAccessMask {
/// Unpacks the byte code of the corresponding file access mask.
pub fn unpack_byte_code(&self) -> u32 {
match self {
FileAccessMask::ReadData => 0x00000001,
FileAccessMask::WriteData => 0x00000002,
FileAccessMask::AppendData => 0x00000004,
FileAccessMask::ReadEa => 0x00000008,
FileAccessMask::WriteEa => 0x00000010,
FileAccessMask::DeleteChild => 0x00000040,
FileAccessMask::Execute => 0x00000020,
FileAccessMask::ReadAttributes => 0x00000080,
FileAccessMask::WriteAttributes => 0x00000100,
FileAccessMask::Delete => 0x00010000,
FileAccessMask::ReadControl => 0x00020000,
FileAccessMask::WriteDac => 0x00040000,
FileAccessMask::WriteOwner => 0x00080000,
FileAccessMask::Synchronize => 0x00100000,
FileAccessMask::AccessSystemSecurity => 0x01000000,
FileAccessMask::MaximumAllowed => 0x02000000,
FileAccessMask::GenericAll => 0x10000000,
FileAccessMask::GenericExecute => 0x20000000,
FileAccessMask::GenericWrite => 0x40000000,
FileAccessMask::GenericRead => 0x80000000,
}
}
/// Returns a sum of the given file access masks as a 4 byte array.
pub fn return_sum_of_chosen_file_access_masks(file_access: Vec<FileAccessMask>) -> Vec<u8> {
let combined_file_access_masks: u32 = file_access.iter().fold(0u32, |acc, access| {
let temp: u64 = acc as u64 + access.unpack_byte_code() as u64;
if temp < u32::MAX as u64 {
acc + access.unpack_byte_code()
} else {
acc
}
});
combined_file_access_masks.to_le_bytes().to_vec()
}
}
impl Distribution<FileAccessMask> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> FileAccessMask {
match rng.gen_range(0..=19) {
0 => FileAccessMask::ReadData,
1 => FileAccessMask::WriteData,
2 => FileAccessMask::AppendData,
3 => FileAccessMask::ReadEa,
4 => FileAccessMask::WriteEa,
5 => FileAccessMask::DeleteChild,
6 => FileAccessMask::Execute,
7 => FileAccessMask::ReadAttributes,
8 => FileAccessMask::WriteAttributes,
9 => FileAccessMask::Delete,
10 => FileAccessMask::ReadControl,
11 => FileAccessMask::WriteDac,
12 => FileAccessMask::WriteOwner,
13 => FileAccessMask::Synchronize,
14 => FileAccessMask::AccessSystemSecurity,
15 => FileAccessMask::MaximumAllowed,
16 => FileAccessMask::GenericAll,
17 => FileAccessMask::GenericExecute,
18 => FileAccessMask::GenericWrite,
_ => FileAccessMask::GenericRead,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_return_sum_of_chosen_file_access_masks() {
assert_eq!(
b"\x89\x00\x12\x00".to_vec(),
FileAccessMask::return_sum_of_chosen_file_access_masks(vec![
FileAccessMask::ReadData,
FileAccessMask::ReadEa,
FileAccessMask::ReadAttributes,
FileAccessMask::ReadControl,
FileAccessMask::Synchronize,
])
);
}
}
|
//! Provides the process function, as well as housing the internals for computing convex hulls.
use io::input::Input;
use io::output::Output;
use shape::orientation::Orientation;
use shape::coord::Coord;
use shape::segment::Segment;
use std::collections::HashSet;
use shape::hull::Hull;
use std::hash::BuildHasher;
/// Processes the input into it's output by generating the convex hulls.
pub fn process(input: &Input) -> Output {
let mut hulls = Vec::new();
let mut path = input.route.clone();
path.push(input.end);
path.insert(0, input.start);
let mut path = path.iter();
let mut origin;
let mut destination = path.next().unwrap(); // Guarunteed to have value
'generate_all_hulls: loop {
origin = destination;
let destination_o = path.next();
if destination_o.is_none() {
break 'generate_all_hulls;
}
destination = destination_o.unwrap();
let mut hull: HashSet<Segment> = HashSet::new();
let mut final_polypoints;
'generate_hull: loop {
let mut polypoints = Segment::from_coords(*origin, *destination)
.get_intersecting_polygon_coords(&input.polygons);
for hull_segment in &hull {
let union = polypoints
.union(&hull_segment.get_intersecting_polygon_coords(&input.polygons))
.cloned()
.collect();
}
if polypoints == union {
final_polypoints = polypoints.clone();
final_polypoints.insert(*origin);
final_polypoints.insert(*destination);
break 'generate_hull;
}
polypoints = union;
polypoints.insert(*origin);
polypoints.insert(*destination);
hull = hull.union(&calculate_hull(&polypoints)).cloned().collect();
}
hull = calculate_hull(&final_polypoints);
hulls.push(Hull::from_segment_set(hull.into_iter().collect()));
}
Output {
input: input.clone(),
hulls: hulls,
}
}
/// Calculates the points that lie in the hull of a set of points.
pub fn calculate_hull<S: BuildHasher>(polypoints: &HashSet<Coord, S>) -> HashSet<Segment> {
let mut hull = HashSet::new();
if !quick_hull(polypoints, &mut hull) {
panic!();
}
hull
}
/// Calculates the quick hull of a set of points, outputting it into a buffer.
/// Returns true when computation is successful.
pub fn quick_hull<S1: BuildHasher, S2: BuildHasher>(
input: &HashSet<Coord, S1>,
hull: &mut HashSet<Segment, S2>,
) -> bool {
if input.len() < 2 {
return false;
}
let (leftest, rightest) = input.iter().fold(
(None, None),
|(mut leftest, mut rightest), &item| {
if leftest.is_none() {
leftest = Some(item);
}
if rightest.is_none() {
rightest = Some(item);
}
if item.x < leftest.unwrap().x {
leftest = Some(item);
}
if item.x > rightest.unwrap().x {
rightest = Some(item);
}
(leftest, rightest)
},
);
let leftest = leftest.unwrap();
let rightest = rightest.unwrap();
quick_hull_recurse(input, leftest, rightest, Orientation::Clockwise, hull);
quick_hull_recurse(
input,
leftest,
rightest,
Orientation::Counterclockwise,
hull,
);
true
}
/// The recursive call component of `quick_hull`.
fn quick_hull_recurse<S1: BuildHasher, S2: BuildHasher>(
input: &HashSet<Coord, S1>,
p1: Coord,
p2: Coord,
orientation: Orientation,
hull: &mut HashSet<Segment, S2>,
) {
let mut divider: Option<Coord> = None;
let mut max_dist = 0;
for &coord in input.iter() {
let dist = Segment::from_coords(p1, p2).coord_distance(coord);
if Orientation::from_coords(p1, p2, coord) == orientation && dist > max_dist {
divider = Some(coord);
max_dist = dist;
}
}
if let Some(divider) = divider {
quick_hull_recurse(
input,
divider,
p1,
Orientation::from_coords(divider, p1, p2).invert(),
hull,
);
quick_hull_recurse(
input,
divider,
p2,
Orientation::from_coords(divider, p2, p1).invert(),
hull,
);
} else {
hull.insert(Segment::from_coords(p1, p2));
}
}
|
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, BufRead};
fn parse_file(file: BufReader<&File>) -> HashMap<(i32, i32), (i32, Vec<i32>)> {
let mut res = HashMap::new();
for line in file.lines() {
let l = line.unwrap();
let tokens:Vec<&str> = l.split(" ").collect();
let id = &tokens[0][1..].parse::<i32>().unwrap();
let xy: Vec<&str> = tokens[2].split(",").collect();
let x = xy[0].parse::<i32>().unwrap();
let y = &xy[1][..xy[1].len()-1].parse::<i32>().unwrap();
let size:Vec<&str> = tokens[3].split("x").collect();
let sizex = size[0].parse::<i32>().unwrap();
let sizey = size[1].parse::<i32>().unwrap();
for sx in 0..sizex {
for sy in 0..sizey {
let entry = res.entry((x + sx, y + sy)).or_insert((0, Vec::new()));
entry.0 += 1;
if !entry.1.contains(id) {
entry.1.push(*id);
}
}
}
}
res
}
fn part01(values: &HashMap<(i32, i32), (i32, Vec<i32>)>) {
let mut sum = 0;
for (_,v) in values.iter() {
if v.0 > 1 {
sum += 1;
}
}
println!("Part01 result = {}", sum);
}
fn part02(values: &HashMap<(i32, i32), (i32, Vec<i32>)>) {
let mut overlaps = [0; 1288];
for (_,v) in values.iter() {
if v.1.len() > 1 {
for ids in &v.1 {
let uid = *ids as usize;
overlaps[uid] += 1;
}
}
}
for (i, elem) in overlaps.iter_mut().enumerate() {
if *elem == 0 && i != 0{
println!("Part 02 result = {}", i);
}
}
}
fn main() {
let f = File::open("input.txt").expect("file not found");
let file = BufReader::new(&f);
let values = parse_file(file);
part01(&values);
part02(&values);
}
|
pub struct Post {}
impl Post {
pub fn new() -> DraftPost {
DraftPost {
content: String::new(),
}
}
}
pub struct DraftPost {
content: String,
}
impl DraftPost {
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn request_review(self) -> PendingReviewPost {
PendingReviewPost {
approval_count: 0,
content: self.content,
}
}
}
pub struct PendingReviewPost {
content: String,
approval_count: u32,
}
pub enum ApprovalResult {
Approved(ApprovedPost),
PendingReview(PendingReviewPost),
}
impl PendingReviewPost {
pub fn approve(self) -> ApprovalResult {
match self.approval_count {
0 => ApprovalResult::PendingReview(PendingReviewPost {
content: self.content,
approval_count: self.approval_count + 1,
}),
1 => ApprovalResult::Approved(ApprovedPost {
content: self.content,
}),
_ => panic!("Invalid approval count"),
}
}
pub fn reject(self) -> DraftPost {
DraftPost {
content: self.content,
}
}
}
pub struct ApprovedPost {
content: String,
}
impl ApprovedPost {
pub fn content(&self) -> &str {
&self.content
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_modify_content_in_draft() {
let mut post = Post::new();
post.add_text("My post");
post.add_text(", with additional text.");
assert_eq!(
"My post, with additional text.", post.content,
"It should be possible to modify the post content in the 'draft' state"
);
}
#[test]
fn single_approve_remains_in_review() {
let mut post = Post::new();
post.add_text("My post");
let post = post.request_review();
match post.approve() {
ApprovalResult::PendingReview(_) => assert!(true),
ApprovalResult::Approved(_) => {
assert!(false, "Post should have required two approvals")
}
}
}
#[test]
fn double_approve_required_for_approved() {
let mut post = Post::new();
post.add_text("My post");
let post = post.request_review();
if let ApprovalResult::PendingReview(post) = post.approve() {
match post.approve() {
ApprovalResult::PendingReview(_) => {
assert!(false, "Post should be approved after two approvals")
}
ApprovalResult::Approved(_) => assert!(true),
}
}
}
#[test]
fn rejection_returns_to_draft() {
let mut post = Post::new();
post.add_text("My post");
let post = post.request_review();
let mut post = post.reject();
post.add_text(", with additional text.");
assert_eq!(
"My post, with additional text.", post.content,
"It should be possible to modify the post content in the 'draft' state"
);
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub enum Arch {
// AMD64 is the x86-64 architecture.
AMD64,
// ARM64 is the aarch64 architecture.
ARM64,
}
// LinuxSysname is the OS name advertised by Quark.
pub const LINUX_SYSNAME : &'static str = "Linux";
// LinuxRelease is the Linux release version number advertised by Quark.
pub const LINUX_RELEASE : &'static str = "4.4.0";
// LinuxVersion is the version info advertised by gVisor.
pub const LINUX_VERSION : &'static str = "#1 SMP Sun Jan 10 15:06:54 PST 2016";
pub struct Version {
// Operating system name (e.g. "Linux").
pub OS: &'static str,
pub Arch: Arch,
// Operating system name (e.g. "Linux").
pub Sysname: &'static str,
// Operating system release (e.g. "4.4-amd64").
pub Release: &'static str,
// Operating system version. On Linux this takes the shape
// "#VERSION CONFIG_FLAGS TIMESTAMP"
// where:
// - VERSION is a sequence counter incremented on every successful build
// - CONFIG_FLAGS is a space-separated list of major enabled kernel features
// (e.g. "SMP" and "PREEMPT")
// - TIMESTAMP is the build timestamp as returned by `date`
pub Version: &'static str,
}
pub const VERSION : Version = Version {
OS: LINUX_SYSNAME,
Arch: Arch::AMD64,
Sysname: LINUX_SYSNAME,
Release: LINUX_RELEASE,
Version: LINUX_VERSION,
}; |
#[doc = "Reader of register ROUTELOC0"]
pub type R = crate::R<u32, super::ROUTELOC0>;
#[doc = "Writer for register ROUTELOC0"]
pub type W = crate::W<u32, super::ROUTELOC0>;
#[doc = "Register ROUTELOC0 `reset()`'s with value 0"]
impl crate::ResetValue for super::ROUTELOC0 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CC0LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
#[doc = "6: Location 6"]
LOC6 = 6,
#[doc = "7: Location 7"]
LOC7 = 7,
#[doc = "8: Location 8"]
LOC8 = 8,
#[doc = "9: Location 9"]
LOC9 = 9,
#[doc = "10: Location 10"]
LOC10 = 10,
#[doc = "11: Location 11"]
LOC11 = 11,
#[doc = "12: Location 12"]
LOC12 = 12,
#[doc = "13: Location 13"]
LOC13 = 13,
#[doc = "14: Location 14"]
LOC14 = 14,
#[doc = "15: Location 15"]
LOC15 = 15,
#[doc = "16: Location 16"]
LOC16 = 16,
#[doc = "17: Location 17"]
LOC17 = 17,
#[doc = "18: Location 18"]
LOC18 = 18,
#[doc = "19: Location 19"]
LOC19 = 19,
#[doc = "20: Location 20"]
LOC20 = 20,
#[doc = "21: Location 21"]
LOC21 = 21,
#[doc = "22: Location 22"]
LOC22 = 22,
#[doc = "23: Location 23"]
LOC23 = 23,
#[doc = "24: Location 24"]
LOC24 = 24,
#[doc = "25: Location 25"]
LOC25 = 25,
#[doc = "26: Location 26"]
LOC26 = 26,
#[doc = "27: Location 27"]
LOC27 = 27,
#[doc = "28: Location 28"]
LOC28 = 28,
#[doc = "29: Location 29"]
LOC29 = 29,
#[doc = "30: Location 30"]
LOC30 = 30,
#[doc = "31: Location 31"]
LOC31 = 31,
}
impl From<CC0LOC_A> for u8 {
#[inline(always)]
fn from(variant: CC0LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CC0LOC`"]
pub type CC0LOC_R = crate::R<u8, CC0LOC_A>;
impl CC0LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CC0LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CC0LOC_A::LOC0),
1 => Val(CC0LOC_A::LOC1),
2 => Val(CC0LOC_A::LOC2),
3 => Val(CC0LOC_A::LOC3),
4 => Val(CC0LOC_A::LOC4),
5 => Val(CC0LOC_A::LOC5),
6 => Val(CC0LOC_A::LOC6),
7 => Val(CC0LOC_A::LOC7),
8 => Val(CC0LOC_A::LOC8),
9 => Val(CC0LOC_A::LOC9),
10 => Val(CC0LOC_A::LOC10),
11 => Val(CC0LOC_A::LOC11),
12 => Val(CC0LOC_A::LOC12),
13 => Val(CC0LOC_A::LOC13),
14 => Val(CC0LOC_A::LOC14),
15 => Val(CC0LOC_A::LOC15),
16 => Val(CC0LOC_A::LOC16),
17 => Val(CC0LOC_A::LOC17),
18 => Val(CC0LOC_A::LOC18),
19 => Val(CC0LOC_A::LOC19),
20 => Val(CC0LOC_A::LOC20),
21 => Val(CC0LOC_A::LOC21),
22 => Val(CC0LOC_A::LOC22),
23 => Val(CC0LOC_A::LOC23),
24 => Val(CC0LOC_A::LOC24),
25 => Val(CC0LOC_A::LOC25),
26 => Val(CC0LOC_A::LOC26),
27 => Val(CC0LOC_A::LOC27),
28 => Val(CC0LOC_A::LOC28),
29 => Val(CC0LOC_A::LOC29),
30 => Val(CC0LOC_A::LOC30),
31 => Val(CC0LOC_A::LOC31),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CC0LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CC0LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CC0LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CC0LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CC0LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CC0LOC_A::LOC5
}
#[doc = "Checks if the value of the field is `LOC6`"]
#[inline(always)]
pub fn is_loc6(&self) -> bool {
*self == CC0LOC_A::LOC6
}
#[doc = "Checks if the value of the field is `LOC7`"]
#[inline(always)]
pub fn is_loc7(&self) -> bool {
*self == CC0LOC_A::LOC7
}
#[doc = "Checks if the value of the field is `LOC8`"]
#[inline(always)]
pub fn is_loc8(&self) -> bool {
*self == CC0LOC_A::LOC8
}
#[doc = "Checks if the value of the field is `LOC9`"]
#[inline(always)]
pub fn is_loc9(&self) -> bool {
*self == CC0LOC_A::LOC9
}
#[doc = "Checks if the value of the field is `LOC10`"]
#[inline(always)]
pub fn is_loc10(&self) -> bool {
*self == CC0LOC_A::LOC10
}
#[doc = "Checks if the value of the field is `LOC11`"]
#[inline(always)]
pub fn is_loc11(&self) -> bool {
*self == CC0LOC_A::LOC11
}
#[doc = "Checks if the value of the field is `LOC12`"]
#[inline(always)]
pub fn is_loc12(&self) -> bool {
*self == CC0LOC_A::LOC12
}
#[doc = "Checks if the value of the field is `LOC13`"]
#[inline(always)]
pub fn is_loc13(&self) -> bool {
*self == CC0LOC_A::LOC13
}
#[doc = "Checks if the value of the field is `LOC14`"]
#[inline(always)]
pub fn is_loc14(&self) -> bool {
*self == CC0LOC_A::LOC14
}
#[doc = "Checks if the value of the field is `LOC15`"]
#[inline(always)]
pub fn is_loc15(&self) -> bool {
*self == CC0LOC_A::LOC15
}
#[doc = "Checks if the value of the field is `LOC16`"]
#[inline(always)]
pub fn is_loc16(&self) -> bool {
*self == CC0LOC_A::LOC16
}
#[doc = "Checks if the value of the field is `LOC17`"]
#[inline(always)]
pub fn is_loc17(&self) -> bool {
*self == CC0LOC_A::LOC17
}
#[doc = "Checks if the value of the field is `LOC18`"]
#[inline(always)]
pub fn is_loc18(&self) -> bool {
*self == CC0LOC_A::LOC18
}
#[doc = "Checks if the value of the field is `LOC19`"]
#[inline(always)]
pub fn is_loc19(&self) -> bool {
*self == CC0LOC_A::LOC19
}
#[doc = "Checks if the value of the field is `LOC20`"]
#[inline(always)]
pub fn is_loc20(&self) -> bool {
*self == CC0LOC_A::LOC20
}
#[doc = "Checks if the value of the field is `LOC21`"]
#[inline(always)]
pub fn is_loc21(&self) -> bool {
*self == CC0LOC_A::LOC21
}
#[doc = "Checks if the value of the field is `LOC22`"]
#[inline(always)]
pub fn is_loc22(&self) -> bool {
*self == CC0LOC_A::LOC22
}
#[doc = "Checks if the value of the field is `LOC23`"]
#[inline(always)]
pub fn is_loc23(&self) -> bool {
*self == CC0LOC_A::LOC23
}
#[doc = "Checks if the value of the field is `LOC24`"]
#[inline(always)]
pub fn is_loc24(&self) -> bool {
*self == CC0LOC_A::LOC24
}
#[doc = "Checks if the value of the field is `LOC25`"]
#[inline(always)]
pub fn is_loc25(&self) -> bool {
*self == CC0LOC_A::LOC25
}
#[doc = "Checks if the value of the field is `LOC26`"]
#[inline(always)]
pub fn is_loc26(&self) -> bool {
*self == CC0LOC_A::LOC26
}
#[doc = "Checks if the value of the field is `LOC27`"]
#[inline(always)]
pub fn is_loc27(&self) -> bool {
*self == CC0LOC_A::LOC27
}
#[doc = "Checks if the value of the field is `LOC28`"]
#[inline(always)]
pub fn is_loc28(&self) -> bool {
*self == CC0LOC_A::LOC28
}
#[doc = "Checks if the value of the field is `LOC29`"]
#[inline(always)]
pub fn is_loc29(&self) -> bool {
*self == CC0LOC_A::LOC29
}
#[doc = "Checks if the value of the field is `LOC30`"]
#[inline(always)]
pub fn is_loc30(&self) -> bool {
*self == CC0LOC_A::LOC30
}
#[doc = "Checks if the value of the field is `LOC31`"]
#[inline(always)]
pub fn is_loc31(&self) -> bool {
*self == CC0LOC_A::LOC31
}
}
#[doc = "Write proxy for field `CC0LOC`"]
pub struct CC0LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CC0LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC0LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC5)
}
#[doc = "Location 6"]
#[inline(always)]
pub fn loc6(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC6)
}
#[doc = "Location 7"]
#[inline(always)]
pub fn loc7(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC7)
}
#[doc = "Location 8"]
#[inline(always)]
pub fn loc8(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC8)
}
#[doc = "Location 9"]
#[inline(always)]
pub fn loc9(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC9)
}
#[doc = "Location 10"]
#[inline(always)]
pub fn loc10(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC10)
}
#[doc = "Location 11"]
#[inline(always)]
pub fn loc11(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC11)
}
#[doc = "Location 12"]
#[inline(always)]
pub fn loc12(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC12)
}
#[doc = "Location 13"]
#[inline(always)]
pub fn loc13(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC13)
}
#[doc = "Location 14"]
#[inline(always)]
pub fn loc14(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC14)
}
#[doc = "Location 15"]
#[inline(always)]
pub fn loc15(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC15)
}
#[doc = "Location 16"]
#[inline(always)]
pub fn loc16(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC16)
}
#[doc = "Location 17"]
#[inline(always)]
pub fn loc17(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC17)
}
#[doc = "Location 18"]
#[inline(always)]
pub fn loc18(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC18)
}
#[doc = "Location 19"]
#[inline(always)]
pub fn loc19(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC19)
}
#[doc = "Location 20"]
#[inline(always)]
pub fn loc20(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC20)
}
#[doc = "Location 21"]
#[inline(always)]
pub fn loc21(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC21)
}
#[doc = "Location 22"]
#[inline(always)]
pub fn loc22(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC22)
}
#[doc = "Location 23"]
#[inline(always)]
pub fn loc23(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC23)
}
#[doc = "Location 24"]
#[inline(always)]
pub fn loc24(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC24)
}
#[doc = "Location 25"]
#[inline(always)]
pub fn loc25(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC25)
}
#[doc = "Location 26"]
#[inline(always)]
pub fn loc26(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC26)
}
#[doc = "Location 27"]
#[inline(always)]
pub fn loc27(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC27)
}
#[doc = "Location 28"]
#[inline(always)]
pub fn loc28(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC28)
}
#[doc = "Location 29"]
#[inline(always)]
pub fn loc29(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC29)
}
#[doc = "Location 30"]
#[inline(always)]
pub fn loc30(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC30)
}
#[doc = "Location 31"]
#[inline(always)]
pub fn loc31(self) -> &'a mut W {
self.variant(CC0LOC_A::LOC31)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x3f) | ((value as u32) & 0x3f);
self.w
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CC1LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
#[doc = "6: Location 6"]
LOC6 = 6,
#[doc = "7: Location 7"]
LOC7 = 7,
#[doc = "8: Location 8"]
LOC8 = 8,
#[doc = "9: Location 9"]
LOC9 = 9,
#[doc = "10: Location 10"]
LOC10 = 10,
#[doc = "11: Location 11"]
LOC11 = 11,
#[doc = "12: Location 12"]
LOC12 = 12,
#[doc = "13: Location 13"]
LOC13 = 13,
#[doc = "14: Location 14"]
LOC14 = 14,
#[doc = "15: Location 15"]
LOC15 = 15,
#[doc = "16: Location 16"]
LOC16 = 16,
#[doc = "17: Location 17"]
LOC17 = 17,
#[doc = "18: Location 18"]
LOC18 = 18,
#[doc = "19: Location 19"]
LOC19 = 19,
#[doc = "20: Location 20"]
LOC20 = 20,
#[doc = "21: Location 21"]
LOC21 = 21,
#[doc = "22: Location 22"]
LOC22 = 22,
#[doc = "23: Location 23"]
LOC23 = 23,
#[doc = "24: Location 24"]
LOC24 = 24,
#[doc = "25: Location 25"]
LOC25 = 25,
#[doc = "26: Location 26"]
LOC26 = 26,
#[doc = "27: Location 27"]
LOC27 = 27,
#[doc = "28: Location 28"]
LOC28 = 28,
#[doc = "29: Location 29"]
LOC29 = 29,
#[doc = "30: Location 30"]
LOC30 = 30,
#[doc = "31: Location 31"]
LOC31 = 31,
}
impl From<CC1LOC_A> for u8 {
#[inline(always)]
fn from(variant: CC1LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CC1LOC`"]
pub type CC1LOC_R = crate::R<u8, CC1LOC_A>;
impl CC1LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CC1LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CC1LOC_A::LOC0),
1 => Val(CC1LOC_A::LOC1),
2 => Val(CC1LOC_A::LOC2),
3 => Val(CC1LOC_A::LOC3),
4 => Val(CC1LOC_A::LOC4),
5 => Val(CC1LOC_A::LOC5),
6 => Val(CC1LOC_A::LOC6),
7 => Val(CC1LOC_A::LOC7),
8 => Val(CC1LOC_A::LOC8),
9 => Val(CC1LOC_A::LOC9),
10 => Val(CC1LOC_A::LOC10),
11 => Val(CC1LOC_A::LOC11),
12 => Val(CC1LOC_A::LOC12),
13 => Val(CC1LOC_A::LOC13),
14 => Val(CC1LOC_A::LOC14),
15 => Val(CC1LOC_A::LOC15),
16 => Val(CC1LOC_A::LOC16),
17 => Val(CC1LOC_A::LOC17),
18 => Val(CC1LOC_A::LOC18),
19 => Val(CC1LOC_A::LOC19),
20 => Val(CC1LOC_A::LOC20),
21 => Val(CC1LOC_A::LOC21),
22 => Val(CC1LOC_A::LOC22),
23 => Val(CC1LOC_A::LOC23),
24 => Val(CC1LOC_A::LOC24),
25 => Val(CC1LOC_A::LOC25),
26 => Val(CC1LOC_A::LOC26),
27 => Val(CC1LOC_A::LOC27),
28 => Val(CC1LOC_A::LOC28),
29 => Val(CC1LOC_A::LOC29),
30 => Val(CC1LOC_A::LOC30),
31 => Val(CC1LOC_A::LOC31),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CC1LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CC1LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CC1LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CC1LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CC1LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CC1LOC_A::LOC5
}
#[doc = "Checks if the value of the field is `LOC6`"]
#[inline(always)]
pub fn is_loc6(&self) -> bool {
*self == CC1LOC_A::LOC6
}
#[doc = "Checks if the value of the field is `LOC7`"]
#[inline(always)]
pub fn is_loc7(&self) -> bool {
*self == CC1LOC_A::LOC7
}
#[doc = "Checks if the value of the field is `LOC8`"]
#[inline(always)]
pub fn is_loc8(&self) -> bool {
*self == CC1LOC_A::LOC8
}
#[doc = "Checks if the value of the field is `LOC9`"]
#[inline(always)]
pub fn is_loc9(&self) -> bool {
*self == CC1LOC_A::LOC9
}
#[doc = "Checks if the value of the field is `LOC10`"]
#[inline(always)]
pub fn is_loc10(&self) -> bool {
*self == CC1LOC_A::LOC10
}
#[doc = "Checks if the value of the field is `LOC11`"]
#[inline(always)]
pub fn is_loc11(&self) -> bool {
*self == CC1LOC_A::LOC11
}
#[doc = "Checks if the value of the field is `LOC12`"]
#[inline(always)]
pub fn is_loc12(&self) -> bool {
*self == CC1LOC_A::LOC12
}
#[doc = "Checks if the value of the field is `LOC13`"]
#[inline(always)]
pub fn is_loc13(&self) -> bool {
*self == CC1LOC_A::LOC13
}
#[doc = "Checks if the value of the field is `LOC14`"]
#[inline(always)]
pub fn is_loc14(&self) -> bool {
*self == CC1LOC_A::LOC14
}
#[doc = "Checks if the value of the field is `LOC15`"]
#[inline(always)]
pub fn is_loc15(&self) -> bool {
*self == CC1LOC_A::LOC15
}
#[doc = "Checks if the value of the field is `LOC16`"]
#[inline(always)]
pub fn is_loc16(&self) -> bool {
*self == CC1LOC_A::LOC16
}
#[doc = "Checks if the value of the field is `LOC17`"]
#[inline(always)]
pub fn is_loc17(&self) -> bool {
*self == CC1LOC_A::LOC17
}
#[doc = "Checks if the value of the field is `LOC18`"]
#[inline(always)]
pub fn is_loc18(&self) -> bool {
*self == CC1LOC_A::LOC18
}
#[doc = "Checks if the value of the field is `LOC19`"]
#[inline(always)]
pub fn is_loc19(&self) -> bool {
*self == CC1LOC_A::LOC19
}
#[doc = "Checks if the value of the field is `LOC20`"]
#[inline(always)]
pub fn is_loc20(&self) -> bool {
*self == CC1LOC_A::LOC20
}
#[doc = "Checks if the value of the field is `LOC21`"]
#[inline(always)]
pub fn is_loc21(&self) -> bool {
*self == CC1LOC_A::LOC21
}
#[doc = "Checks if the value of the field is `LOC22`"]
#[inline(always)]
pub fn is_loc22(&self) -> bool {
*self == CC1LOC_A::LOC22
}
#[doc = "Checks if the value of the field is `LOC23`"]
#[inline(always)]
pub fn is_loc23(&self) -> bool {
*self == CC1LOC_A::LOC23
}
#[doc = "Checks if the value of the field is `LOC24`"]
#[inline(always)]
pub fn is_loc24(&self) -> bool {
*self == CC1LOC_A::LOC24
}
#[doc = "Checks if the value of the field is `LOC25`"]
#[inline(always)]
pub fn is_loc25(&self) -> bool {
*self == CC1LOC_A::LOC25
}
#[doc = "Checks if the value of the field is `LOC26`"]
#[inline(always)]
pub fn is_loc26(&self) -> bool {
*self == CC1LOC_A::LOC26
}
#[doc = "Checks if the value of the field is `LOC27`"]
#[inline(always)]
pub fn is_loc27(&self) -> bool {
*self == CC1LOC_A::LOC27
}
#[doc = "Checks if the value of the field is `LOC28`"]
#[inline(always)]
pub fn is_loc28(&self) -> bool {
*self == CC1LOC_A::LOC28
}
#[doc = "Checks if the value of the field is `LOC29`"]
#[inline(always)]
pub fn is_loc29(&self) -> bool {
*self == CC1LOC_A::LOC29
}
#[doc = "Checks if the value of the field is `LOC30`"]
#[inline(always)]
pub fn is_loc30(&self) -> bool {
*self == CC1LOC_A::LOC30
}
#[doc = "Checks if the value of the field is `LOC31`"]
#[inline(always)]
pub fn is_loc31(&self) -> bool {
*self == CC1LOC_A::LOC31
}
}
#[doc = "Write proxy for field `CC1LOC`"]
pub struct CC1LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CC1LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC1LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC5)
}
#[doc = "Location 6"]
#[inline(always)]
pub fn loc6(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC6)
}
#[doc = "Location 7"]
#[inline(always)]
pub fn loc7(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC7)
}
#[doc = "Location 8"]
#[inline(always)]
pub fn loc8(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC8)
}
#[doc = "Location 9"]
#[inline(always)]
pub fn loc9(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC9)
}
#[doc = "Location 10"]
#[inline(always)]
pub fn loc10(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC10)
}
#[doc = "Location 11"]
#[inline(always)]
pub fn loc11(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC11)
}
#[doc = "Location 12"]
#[inline(always)]
pub fn loc12(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC12)
}
#[doc = "Location 13"]
#[inline(always)]
pub fn loc13(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC13)
}
#[doc = "Location 14"]
#[inline(always)]
pub fn loc14(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC14)
}
#[doc = "Location 15"]
#[inline(always)]
pub fn loc15(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC15)
}
#[doc = "Location 16"]
#[inline(always)]
pub fn loc16(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC16)
}
#[doc = "Location 17"]
#[inline(always)]
pub fn loc17(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC17)
}
#[doc = "Location 18"]
#[inline(always)]
pub fn loc18(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC18)
}
#[doc = "Location 19"]
#[inline(always)]
pub fn loc19(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC19)
}
#[doc = "Location 20"]
#[inline(always)]
pub fn loc20(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC20)
}
#[doc = "Location 21"]
#[inline(always)]
pub fn loc21(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC21)
}
#[doc = "Location 22"]
#[inline(always)]
pub fn loc22(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC22)
}
#[doc = "Location 23"]
#[inline(always)]
pub fn loc23(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC23)
}
#[doc = "Location 24"]
#[inline(always)]
pub fn loc24(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC24)
}
#[doc = "Location 25"]
#[inline(always)]
pub fn loc25(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC25)
}
#[doc = "Location 26"]
#[inline(always)]
pub fn loc26(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC26)
}
#[doc = "Location 27"]
#[inline(always)]
pub fn loc27(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC27)
}
#[doc = "Location 28"]
#[inline(always)]
pub fn loc28(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC28)
}
#[doc = "Location 29"]
#[inline(always)]
pub fn loc29(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC29)
}
#[doc = "Location 30"]
#[inline(always)]
pub fn loc30(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC30)
}
#[doc = "Location 31"]
#[inline(always)]
pub fn loc31(self) -> &'a mut W {
self.variant(CC1LOC_A::LOC31)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3f << 8)) | (((value as u32) & 0x3f) << 8);
self.w
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CC2LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
#[doc = "6: Location 6"]
LOC6 = 6,
#[doc = "7: Location 7"]
LOC7 = 7,
#[doc = "8: Location 8"]
LOC8 = 8,
#[doc = "9: Location 9"]
LOC9 = 9,
#[doc = "10: Location 10"]
LOC10 = 10,
#[doc = "11: Location 11"]
LOC11 = 11,
#[doc = "12: Location 12"]
LOC12 = 12,
#[doc = "13: Location 13"]
LOC13 = 13,
#[doc = "14: Location 14"]
LOC14 = 14,
#[doc = "15: Location 15"]
LOC15 = 15,
#[doc = "16: Location 16"]
LOC16 = 16,
#[doc = "17: Location 17"]
LOC17 = 17,
#[doc = "18: Location 18"]
LOC18 = 18,
#[doc = "19: Location 19"]
LOC19 = 19,
#[doc = "20: Location 20"]
LOC20 = 20,
#[doc = "21: Location 21"]
LOC21 = 21,
#[doc = "22: Location 22"]
LOC22 = 22,
#[doc = "23: Location 23"]
LOC23 = 23,
#[doc = "24: Location 24"]
LOC24 = 24,
#[doc = "25: Location 25"]
LOC25 = 25,
#[doc = "26: Location 26"]
LOC26 = 26,
#[doc = "27: Location 27"]
LOC27 = 27,
#[doc = "28: Location 28"]
LOC28 = 28,
#[doc = "29: Location 29"]
LOC29 = 29,
#[doc = "30: Location 30"]
LOC30 = 30,
#[doc = "31: Location 31"]
LOC31 = 31,
}
impl From<CC2LOC_A> for u8 {
#[inline(always)]
fn from(variant: CC2LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CC2LOC`"]
pub type CC2LOC_R = crate::R<u8, CC2LOC_A>;
impl CC2LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CC2LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CC2LOC_A::LOC0),
1 => Val(CC2LOC_A::LOC1),
2 => Val(CC2LOC_A::LOC2),
3 => Val(CC2LOC_A::LOC3),
4 => Val(CC2LOC_A::LOC4),
5 => Val(CC2LOC_A::LOC5),
6 => Val(CC2LOC_A::LOC6),
7 => Val(CC2LOC_A::LOC7),
8 => Val(CC2LOC_A::LOC8),
9 => Val(CC2LOC_A::LOC9),
10 => Val(CC2LOC_A::LOC10),
11 => Val(CC2LOC_A::LOC11),
12 => Val(CC2LOC_A::LOC12),
13 => Val(CC2LOC_A::LOC13),
14 => Val(CC2LOC_A::LOC14),
15 => Val(CC2LOC_A::LOC15),
16 => Val(CC2LOC_A::LOC16),
17 => Val(CC2LOC_A::LOC17),
18 => Val(CC2LOC_A::LOC18),
19 => Val(CC2LOC_A::LOC19),
20 => Val(CC2LOC_A::LOC20),
21 => Val(CC2LOC_A::LOC21),
22 => Val(CC2LOC_A::LOC22),
23 => Val(CC2LOC_A::LOC23),
24 => Val(CC2LOC_A::LOC24),
25 => Val(CC2LOC_A::LOC25),
26 => Val(CC2LOC_A::LOC26),
27 => Val(CC2LOC_A::LOC27),
28 => Val(CC2LOC_A::LOC28),
29 => Val(CC2LOC_A::LOC29),
30 => Val(CC2LOC_A::LOC30),
31 => Val(CC2LOC_A::LOC31),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CC2LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CC2LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CC2LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CC2LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CC2LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CC2LOC_A::LOC5
}
#[doc = "Checks if the value of the field is `LOC6`"]
#[inline(always)]
pub fn is_loc6(&self) -> bool {
*self == CC2LOC_A::LOC6
}
#[doc = "Checks if the value of the field is `LOC7`"]
#[inline(always)]
pub fn is_loc7(&self) -> bool {
*self == CC2LOC_A::LOC7
}
#[doc = "Checks if the value of the field is `LOC8`"]
#[inline(always)]
pub fn is_loc8(&self) -> bool {
*self == CC2LOC_A::LOC8
}
#[doc = "Checks if the value of the field is `LOC9`"]
#[inline(always)]
pub fn is_loc9(&self) -> bool {
*self == CC2LOC_A::LOC9
}
#[doc = "Checks if the value of the field is `LOC10`"]
#[inline(always)]
pub fn is_loc10(&self) -> bool {
*self == CC2LOC_A::LOC10
}
#[doc = "Checks if the value of the field is `LOC11`"]
#[inline(always)]
pub fn is_loc11(&self) -> bool {
*self == CC2LOC_A::LOC11
}
#[doc = "Checks if the value of the field is `LOC12`"]
#[inline(always)]
pub fn is_loc12(&self) -> bool {
*self == CC2LOC_A::LOC12
}
#[doc = "Checks if the value of the field is `LOC13`"]
#[inline(always)]
pub fn is_loc13(&self) -> bool {
*self == CC2LOC_A::LOC13
}
#[doc = "Checks if the value of the field is `LOC14`"]
#[inline(always)]
pub fn is_loc14(&self) -> bool {
*self == CC2LOC_A::LOC14
}
#[doc = "Checks if the value of the field is `LOC15`"]
#[inline(always)]
pub fn is_loc15(&self) -> bool {
*self == CC2LOC_A::LOC15
}
#[doc = "Checks if the value of the field is `LOC16`"]
#[inline(always)]
pub fn is_loc16(&self) -> bool {
*self == CC2LOC_A::LOC16
}
#[doc = "Checks if the value of the field is `LOC17`"]
#[inline(always)]
pub fn is_loc17(&self) -> bool {
*self == CC2LOC_A::LOC17
}
#[doc = "Checks if the value of the field is `LOC18`"]
#[inline(always)]
pub fn is_loc18(&self) -> bool {
*self == CC2LOC_A::LOC18
}
#[doc = "Checks if the value of the field is `LOC19`"]
#[inline(always)]
pub fn is_loc19(&self) -> bool {
*self == CC2LOC_A::LOC19
}
#[doc = "Checks if the value of the field is `LOC20`"]
#[inline(always)]
pub fn is_loc20(&self) -> bool {
*self == CC2LOC_A::LOC20
}
#[doc = "Checks if the value of the field is `LOC21`"]
#[inline(always)]
pub fn is_loc21(&self) -> bool {
*self == CC2LOC_A::LOC21
}
#[doc = "Checks if the value of the field is `LOC22`"]
#[inline(always)]
pub fn is_loc22(&self) -> bool {
*self == CC2LOC_A::LOC22
}
#[doc = "Checks if the value of the field is `LOC23`"]
#[inline(always)]
pub fn is_loc23(&self) -> bool {
*self == CC2LOC_A::LOC23
}
#[doc = "Checks if the value of the field is `LOC24`"]
#[inline(always)]
pub fn is_loc24(&self) -> bool {
*self == CC2LOC_A::LOC24
}
#[doc = "Checks if the value of the field is `LOC25`"]
#[inline(always)]
pub fn is_loc25(&self) -> bool {
*self == CC2LOC_A::LOC25
}
#[doc = "Checks if the value of the field is `LOC26`"]
#[inline(always)]
pub fn is_loc26(&self) -> bool {
*self == CC2LOC_A::LOC26
}
#[doc = "Checks if the value of the field is `LOC27`"]
#[inline(always)]
pub fn is_loc27(&self) -> bool {
*self == CC2LOC_A::LOC27
}
#[doc = "Checks if the value of the field is `LOC28`"]
#[inline(always)]
pub fn is_loc28(&self) -> bool {
*self == CC2LOC_A::LOC28
}
#[doc = "Checks if the value of the field is `LOC29`"]
#[inline(always)]
pub fn is_loc29(&self) -> bool {
*self == CC2LOC_A::LOC29
}
#[doc = "Checks if the value of the field is `LOC30`"]
#[inline(always)]
pub fn is_loc30(&self) -> bool {
*self == CC2LOC_A::LOC30
}
#[doc = "Checks if the value of the field is `LOC31`"]
#[inline(always)]
pub fn is_loc31(&self) -> bool {
*self == CC2LOC_A::LOC31
}
}
#[doc = "Write proxy for field `CC2LOC`"]
pub struct CC2LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CC2LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC2LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC5)
}
#[doc = "Location 6"]
#[inline(always)]
pub fn loc6(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC6)
}
#[doc = "Location 7"]
#[inline(always)]
pub fn loc7(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC7)
}
#[doc = "Location 8"]
#[inline(always)]
pub fn loc8(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC8)
}
#[doc = "Location 9"]
#[inline(always)]
pub fn loc9(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC9)
}
#[doc = "Location 10"]
#[inline(always)]
pub fn loc10(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC10)
}
#[doc = "Location 11"]
#[inline(always)]
pub fn loc11(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC11)
}
#[doc = "Location 12"]
#[inline(always)]
pub fn loc12(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC12)
}
#[doc = "Location 13"]
#[inline(always)]
pub fn loc13(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC13)
}
#[doc = "Location 14"]
#[inline(always)]
pub fn loc14(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC14)
}
#[doc = "Location 15"]
#[inline(always)]
pub fn loc15(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC15)
}
#[doc = "Location 16"]
#[inline(always)]
pub fn loc16(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC16)
}
#[doc = "Location 17"]
#[inline(always)]
pub fn loc17(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC17)
}
#[doc = "Location 18"]
#[inline(always)]
pub fn loc18(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC18)
}
#[doc = "Location 19"]
#[inline(always)]
pub fn loc19(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC19)
}
#[doc = "Location 20"]
#[inline(always)]
pub fn loc20(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC20)
}
#[doc = "Location 21"]
#[inline(always)]
pub fn loc21(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC21)
}
#[doc = "Location 22"]
#[inline(always)]
pub fn loc22(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC22)
}
#[doc = "Location 23"]
#[inline(always)]
pub fn loc23(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC23)
}
#[doc = "Location 24"]
#[inline(always)]
pub fn loc24(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC24)
}
#[doc = "Location 25"]
#[inline(always)]
pub fn loc25(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC25)
}
#[doc = "Location 26"]
#[inline(always)]
pub fn loc26(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC26)
}
#[doc = "Location 27"]
#[inline(always)]
pub fn loc27(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC27)
}
#[doc = "Location 28"]
#[inline(always)]
pub fn loc28(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC28)
}
#[doc = "Location 29"]
#[inline(always)]
pub fn loc29(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC29)
}
#[doc = "Location 30"]
#[inline(always)]
pub fn loc30(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC30)
}
#[doc = "Location 31"]
#[inline(always)]
pub fn loc31(self) -> &'a mut W {
self.variant(CC2LOC_A::LOC31)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3f << 16)) | (((value as u32) & 0x3f) << 16);
self.w
}
}
#[doc = "I/O Location\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CC3LOC_A {
#[doc = "0: Location 0"]
LOC0 = 0,
#[doc = "1: Location 1"]
LOC1 = 1,
#[doc = "2: Location 2"]
LOC2 = 2,
#[doc = "3: Location 3"]
LOC3 = 3,
#[doc = "4: Location 4"]
LOC4 = 4,
#[doc = "5: Location 5"]
LOC5 = 5,
#[doc = "6: Location 6"]
LOC6 = 6,
#[doc = "7: Location 7"]
LOC7 = 7,
#[doc = "8: Location 8"]
LOC8 = 8,
#[doc = "9: Location 9"]
LOC9 = 9,
#[doc = "10: Location 10"]
LOC10 = 10,
#[doc = "11: Location 11"]
LOC11 = 11,
#[doc = "12: Location 12"]
LOC12 = 12,
#[doc = "13: Location 13"]
LOC13 = 13,
#[doc = "14: Location 14"]
LOC14 = 14,
#[doc = "15: Location 15"]
LOC15 = 15,
#[doc = "16: Location 16"]
LOC16 = 16,
#[doc = "17: Location 17"]
LOC17 = 17,
#[doc = "18: Location 18"]
LOC18 = 18,
#[doc = "19: Location 19"]
LOC19 = 19,
#[doc = "20: Location 20"]
LOC20 = 20,
#[doc = "21: Location 21"]
LOC21 = 21,
#[doc = "22: Location 22"]
LOC22 = 22,
#[doc = "23: Location 23"]
LOC23 = 23,
#[doc = "24: Location 24"]
LOC24 = 24,
#[doc = "25: Location 25"]
LOC25 = 25,
#[doc = "26: Location 26"]
LOC26 = 26,
#[doc = "27: Location 27"]
LOC27 = 27,
#[doc = "28: Location 28"]
LOC28 = 28,
#[doc = "29: Location 29"]
LOC29 = 29,
#[doc = "30: Location 30"]
LOC30 = 30,
#[doc = "31: Location 31"]
LOC31 = 31,
}
impl From<CC3LOC_A> for u8 {
#[inline(always)]
fn from(variant: CC3LOC_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CC3LOC`"]
pub type CC3LOC_R = crate::R<u8, CC3LOC_A>;
impl CC3LOC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CC3LOC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CC3LOC_A::LOC0),
1 => Val(CC3LOC_A::LOC1),
2 => Val(CC3LOC_A::LOC2),
3 => Val(CC3LOC_A::LOC3),
4 => Val(CC3LOC_A::LOC4),
5 => Val(CC3LOC_A::LOC5),
6 => Val(CC3LOC_A::LOC6),
7 => Val(CC3LOC_A::LOC7),
8 => Val(CC3LOC_A::LOC8),
9 => Val(CC3LOC_A::LOC9),
10 => Val(CC3LOC_A::LOC10),
11 => Val(CC3LOC_A::LOC11),
12 => Val(CC3LOC_A::LOC12),
13 => Val(CC3LOC_A::LOC13),
14 => Val(CC3LOC_A::LOC14),
15 => Val(CC3LOC_A::LOC15),
16 => Val(CC3LOC_A::LOC16),
17 => Val(CC3LOC_A::LOC17),
18 => Val(CC3LOC_A::LOC18),
19 => Val(CC3LOC_A::LOC19),
20 => Val(CC3LOC_A::LOC20),
21 => Val(CC3LOC_A::LOC21),
22 => Val(CC3LOC_A::LOC22),
23 => Val(CC3LOC_A::LOC23),
24 => Val(CC3LOC_A::LOC24),
25 => Val(CC3LOC_A::LOC25),
26 => Val(CC3LOC_A::LOC26),
27 => Val(CC3LOC_A::LOC27),
28 => Val(CC3LOC_A::LOC28),
29 => Val(CC3LOC_A::LOC29),
30 => Val(CC3LOC_A::LOC30),
31 => Val(CC3LOC_A::LOC31),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LOC0`"]
#[inline(always)]
pub fn is_loc0(&self) -> bool {
*self == CC3LOC_A::LOC0
}
#[doc = "Checks if the value of the field is `LOC1`"]
#[inline(always)]
pub fn is_loc1(&self) -> bool {
*self == CC3LOC_A::LOC1
}
#[doc = "Checks if the value of the field is `LOC2`"]
#[inline(always)]
pub fn is_loc2(&self) -> bool {
*self == CC3LOC_A::LOC2
}
#[doc = "Checks if the value of the field is `LOC3`"]
#[inline(always)]
pub fn is_loc3(&self) -> bool {
*self == CC3LOC_A::LOC3
}
#[doc = "Checks if the value of the field is `LOC4`"]
#[inline(always)]
pub fn is_loc4(&self) -> bool {
*self == CC3LOC_A::LOC4
}
#[doc = "Checks if the value of the field is `LOC5`"]
#[inline(always)]
pub fn is_loc5(&self) -> bool {
*self == CC3LOC_A::LOC5
}
#[doc = "Checks if the value of the field is `LOC6`"]
#[inline(always)]
pub fn is_loc6(&self) -> bool {
*self == CC3LOC_A::LOC6
}
#[doc = "Checks if the value of the field is `LOC7`"]
#[inline(always)]
pub fn is_loc7(&self) -> bool {
*self == CC3LOC_A::LOC7
}
#[doc = "Checks if the value of the field is `LOC8`"]
#[inline(always)]
pub fn is_loc8(&self) -> bool {
*self == CC3LOC_A::LOC8
}
#[doc = "Checks if the value of the field is `LOC9`"]
#[inline(always)]
pub fn is_loc9(&self) -> bool {
*self == CC3LOC_A::LOC9
}
#[doc = "Checks if the value of the field is `LOC10`"]
#[inline(always)]
pub fn is_loc10(&self) -> bool {
*self == CC3LOC_A::LOC10
}
#[doc = "Checks if the value of the field is `LOC11`"]
#[inline(always)]
pub fn is_loc11(&self) -> bool {
*self == CC3LOC_A::LOC11
}
#[doc = "Checks if the value of the field is `LOC12`"]
#[inline(always)]
pub fn is_loc12(&self) -> bool {
*self == CC3LOC_A::LOC12
}
#[doc = "Checks if the value of the field is `LOC13`"]
#[inline(always)]
pub fn is_loc13(&self) -> bool {
*self == CC3LOC_A::LOC13
}
#[doc = "Checks if the value of the field is `LOC14`"]
#[inline(always)]
pub fn is_loc14(&self) -> bool {
*self == CC3LOC_A::LOC14
}
#[doc = "Checks if the value of the field is `LOC15`"]
#[inline(always)]
pub fn is_loc15(&self) -> bool {
*self == CC3LOC_A::LOC15
}
#[doc = "Checks if the value of the field is `LOC16`"]
#[inline(always)]
pub fn is_loc16(&self) -> bool {
*self == CC3LOC_A::LOC16
}
#[doc = "Checks if the value of the field is `LOC17`"]
#[inline(always)]
pub fn is_loc17(&self) -> bool {
*self == CC3LOC_A::LOC17
}
#[doc = "Checks if the value of the field is `LOC18`"]
#[inline(always)]
pub fn is_loc18(&self) -> bool {
*self == CC3LOC_A::LOC18
}
#[doc = "Checks if the value of the field is `LOC19`"]
#[inline(always)]
pub fn is_loc19(&self) -> bool {
*self == CC3LOC_A::LOC19
}
#[doc = "Checks if the value of the field is `LOC20`"]
#[inline(always)]
pub fn is_loc20(&self) -> bool {
*self == CC3LOC_A::LOC20
}
#[doc = "Checks if the value of the field is `LOC21`"]
#[inline(always)]
pub fn is_loc21(&self) -> bool {
*self == CC3LOC_A::LOC21
}
#[doc = "Checks if the value of the field is `LOC22`"]
#[inline(always)]
pub fn is_loc22(&self) -> bool {
*self == CC3LOC_A::LOC22
}
#[doc = "Checks if the value of the field is `LOC23`"]
#[inline(always)]
pub fn is_loc23(&self) -> bool {
*self == CC3LOC_A::LOC23
}
#[doc = "Checks if the value of the field is `LOC24`"]
#[inline(always)]
pub fn is_loc24(&self) -> bool {
*self == CC3LOC_A::LOC24
}
#[doc = "Checks if the value of the field is `LOC25`"]
#[inline(always)]
pub fn is_loc25(&self) -> bool {
*self == CC3LOC_A::LOC25
}
#[doc = "Checks if the value of the field is `LOC26`"]
#[inline(always)]
pub fn is_loc26(&self) -> bool {
*self == CC3LOC_A::LOC26
}
#[doc = "Checks if the value of the field is `LOC27`"]
#[inline(always)]
pub fn is_loc27(&self) -> bool {
*self == CC3LOC_A::LOC27
}
#[doc = "Checks if the value of the field is `LOC28`"]
#[inline(always)]
pub fn is_loc28(&self) -> bool {
*self == CC3LOC_A::LOC28
}
#[doc = "Checks if the value of the field is `LOC29`"]
#[inline(always)]
pub fn is_loc29(&self) -> bool {
*self == CC3LOC_A::LOC29
}
#[doc = "Checks if the value of the field is `LOC30`"]
#[inline(always)]
pub fn is_loc30(&self) -> bool {
*self == CC3LOC_A::LOC30
}
#[doc = "Checks if the value of the field is `LOC31`"]
#[inline(always)]
pub fn is_loc31(&self) -> bool {
*self == CC3LOC_A::LOC31
}
}
#[doc = "Write proxy for field `CC3LOC`"]
pub struct CC3LOC_W<'a> {
w: &'a mut W,
}
impl<'a> CC3LOC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CC3LOC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Location 0"]
#[inline(always)]
pub fn loc0(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC0)
}
#[doc = "Location 1"]
#[inline(always)]
pub fn loc1(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC1)
}
#[doc = "Location 2"]
#[inline(always)]
pub fn loc2(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC2)
}
#[doc = "Location 3"]
#[inline(always)]
pub fn loc3(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC3)
}
#[doc = "Location 4"]
#[inline(always)]
pub fn loc4(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC4)
}
#[doc = "Location 5"]
#[inline(always)]
pub fn loc5(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC5)
}
#[doc = "Location 6"]
#[inline(always)]
pub fn loc6(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC6)
}
#[doc = "Location 7"]
#[inline(always)]
pub fn loc7(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC7)
}
#[doc = "Location 8"]
#[inline(always)]
pub fn loc8(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC8)
}
#[doc = "Location 9"]
#[inline(always)]
pub fn loc9(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC9)
}
#[doc = "Location 10"]
#[inline(always)]
pub fn loc10(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC10)
}
#[doc = "Location 11"]
#[inline(always)]
pub fn loc11(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC11)
}
#[doc = "Location 12"]
#[inline(always)]
pub fn loc12(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC12)
}
#[doc = "Location 13"]
#[inline(always)]
pub fn loc13(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC13)
}
#[doc = "Location 14"]
#[inline(always)]
pub fn loc14(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC14)
}
#[doc = "Location 15"]
#[inline(always)]
pub fn loc15(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC15)
}
#[doc = "Location 16"]
#[inline(always)]
pub fn loc16(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC16)
}
#[doc = "Location 17"]
#[inline(always)]
pub fn loc17(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC17)
}
#[doc = "Location 18"]
#[inline(always)]
pub fn loc18(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC18)
}
#[doc = "Location 19"]
#[inline(always)]
pub fn loc19(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC19)
}
#[doc = "Location 20"]
#[inline(always)]
pub fn loc20(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC20)
}
#[doc = "Location 21"]
#[inline(always)]
pub fn loc21(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC21)
}
#[doc = "Location 22"]
#[inline(always)]
pub fn loc22(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC22)
}
#[doc = "Location 23"]
#[inline(always)]
pub fn loc23(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC23)
}
#[doc = "Location 24"]
#[inline(always)]
pub fn loc24(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC24)
}
#[doc = "Location 25"]
#[inline(always)]
pub fn loc25(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC25)
}
#[doc = "Location 26"]
#[inline(always)]
pub fn loc26(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC26)
}
#[doc = "Location 27"]
#[inline(always)]
pub fn loc27(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC27)
}
#[doc = "Location 28"]
#[inline(always)]
pub fn loc28(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC28)
}
#[doc = "Location 29"]
#[inline(always)]
pub fn loc29(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC29)
}
#[doc = "Location 30"]
#[inline(always)]
pub fn loc30(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC30)
}
#[doc = "Location 31"]
#[inline(always)]
pub fn loc31(self) -> &'a mut W {
self.variant(CC3LOC_A::LOC31)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3f << 24)) | (((value as u32) & 0x3f) << 24);
self.w
}
}
impl R {
#[doc = "Bits 0:5 - I/O Location"]
#[inline(always)]
pub fn cc0loc(&self) -> CC0LOC_R {
CC0LOC_R::new((self.bits & 0x3f) as u8)
}
#[doc = "Bits 8:13 - I/O Location"]
#[inline(always)]
pub fn cc1loc(&self) -> CC1LOC_R {
CC1LOC_R::new(((self.bits >> 8) & 0x3f) as u8)
}
#[doc = "Bits 16:21 - I/O Location"]
#[inline(always)]
pub fn cc2loc(&self) -> CC2LOC_R {
CC2LOC_R::new(((self.bits >> 16) & 0x3f) as u8)
}
#[doc = "Bits 24:29 - I/O Location"]
#[inline(always)]
pub fn cc3loc(&self) -> CC3LOC_R {
CC3LOC_R::new(((self.bits >> 24) & 0x3f) as u8)
}
}
impl W {
#[doc = "Bits 0:5 - I/O Location"]
#[inline(always)]
pub fn cc0loc(&mut self) -> CC0LOC_W {
CC0LOC_W { w: self }
}
#[doc = "Bits 8:13 - I/O Location"]
#[inline(always)]
pub fn cc1loc(&mut self) -> CC1LOC_W {
CC1LOC_W { w: self }
}
#[doc = "Bits 16:21 - I/O Location"]
#[inline(always)]
pub fn cc2loc(&mut self) -> CC2LOC_W {
CC2LOC_W { w: self }
}
#[doc = "Bits 24:29 - I/O Location"]
#[inline(always)]
pub fn cc3loc(&mut self) -> CC3LOC_W {
CC3LOC_W { w: self }
}
}
|
#[doc = "Reader of register SEED3"]
pub type R = crate::R<u8, super::SEED3>;
#[doc = "Reader of field `seed`"]
pub type SEED_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7"]
#[inline(always)]
pub fn seed(&self) -> SEED_R {
SEED_R::new((self.bits & 0xff) as u8)
}
}
|
#[desc = "Rust hello-world package."]
#[license = "MIT"]
#[version = "0.1.0"]
pub fn world() {
println("Hello, world");
}
|
//! Framed dispatcher service and related utilities
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::mem;
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, FutureResult};
use futures::task::AtomicTask;
use futures::{Async, Future, IntoFuture, Poll, Sink, Stream};
use log::debug;
use crate::cell::Cell;
type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item;
pub struct FramedNewService<S, T, U, C> {
factory: S,
_t: PhantomData<(T, U, C)>,
}
impl<S, T, U, C> FramedNewService<S, T, U, C>
where
C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
pub fn new<F1: IntoNewService<S, C>>(factory: F1) -> Self {
Self {
factory: factory.into_new_service(),
_t: PhantomData,
}
}
}
impl<S, T, U, C> Clone for FramedNewService<S, T, U, C>
where
S: Clone,
{
fn clone(&self) -> Self {
Self {
factory: self.factory.clone(),
_t: PhantomData,
}
}
}
impl<S, T, U, C> NewService<C> for FramedNewService<S, T, U, C>
where
C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>> + Clone,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type InitError = S::InitError;
type Service = FramedService<S, T, U, C>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, cfg: &C) -> Self::Future {
ok(FramedService {
factory: self.factory.clone(),
config: cfg.clone(),
_t: PhantomData,
})
}
}
pub struct FramedService<S, T, U, C> {
factory: S,
config: C,
_t: PhantomData<(T, U)>,
}
impl<S, T, U, C> Clone for FramedService<S, T, U, C>
where
S: Clone,
C: Clone,
{
fn clone(&self) -> Self {
Self {
factory: self.factory.clone(),
config: self.config.clone(),
_t: PhantomData,
}
}
}
impl<S, T, U, C> Service for FramedService<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
C: Clone,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type Future = FramedServiceResponseFuture<S, T, U, C>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Framed<T, U>) -> Self::Future {
FramedServiceResponseFuture {
fut: self.factory.new_service(&self.config),
framed: Some(req),
}
}
}
#[doc(hidden)]
pub struct FramedServiceResponseFuture<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
fut: <S::Future as IntoFuture>::Future,
framed: Option<Framed<T, U>>,
}
impl<S, T, U, C> Future for FramedServiceResponseFuture<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Item = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.fut.poll()? {
Async::NotReady => Ok(Async::NotReady),
Async::Ready(service) => Ok(Async::Ready(FramedTransport::new(
self.framed.take().unwrap(),
service,
))),
}
}
}
/// Framed transport errors
pub enum FramedTransportError<E, U: Encoder + Decoder> {
Service(E),
Encoder(<U as Encoder>::Error),
Decoder(<U as Decoder>::Error),
}
impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
fn from(err: E) -> Self {
FramedTransportError::Service(err)
}
}
/// FramedTransport - is a future that reads frames from Framed object
/// and pass then to the service.
pub struct FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Encoder + Decoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
service: S,
state: TransportState<S, U>,
framed: Framed<T, U>,
inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>,
}
enum TransportState<S: Service, U: Encoder + Decoder> {
Processing,
Error(FramedTransportError<S::Error, U>),
FramedError(FramedTransportError<S::Error, U>),
Stopping,
}
struct FramedTransportInner<I, E> {
buf: VecDeque<Result<I, E>>,
task: AtomicTask,
}
impl<S, T, U> FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
fn poll_read(&mut self) -> bool {
loop {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => loop {
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
self.state =
TransportState::FramedError(FramedTransportError::Decoder(err));
return true;
}
Ok(Async::NotReady) => return false,
Ok(Async::Ready(None)) => {
self.state = TransportState::Stopping;
return true;
}
};
let mut cell = self.inner.clone();
cell.get_mut().task.register();
tokio_current_thread::spawn(self.service.call(item).then(move |item| {
let inner = cell.get_mut();
inner.buf.push_back(item);
inner.task.notify();
Ok(())
}));
},
Ok(Async::NotReady) => return false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
}
/// write to framed object
fn poll_write(&mut self) -> bool {
let inner = self.inner.get_mut();
loop {
while !self.framed.is_write_buf_full() {
if let Some(msg) = inner.buf.pop_front() {
match msg {
Ok(msg) => {
if let Err(err) = self.framed.force_send(msg) {
self.state = TransportState::FramedError(
FramedTransportError::Encoder(err),
);
return true;
}
}
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
} else {
break;
}
}
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Ok(Async::NotReady) => break,
Err(err) => {
debug!("Error sending data: {:?}", err);
self.state =
TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
}
Ok(Async::Ready(_)) => (),
}
} else {
break;
}
}
false
}
}
impl<S, T, U> FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
FramedTransport {
framed,
service: service.into_service(),
state: TransportState::Processing,
inner: Cell::new(FramedTransportInner {
buf: VecDeque::new(),
task: AtomicTask::new(),
}),
}
}
/// Get reference to a service wrapped by `FramedTransport` instance.
pub fn get_ref(&self) -> &S {
&self.service
}
/// Get mutable reference to a service wrapped by `FramedTransport`
/// instance.
pub fn get_mut(&mut self) -> &mut S {
&mut self.service
}
/// Get reference to a framed instance wrapped by `FramedTransport`
/// instance.
pub fn get_framed(&self) -> &Framed<T, U> {
&self.framed
}
/// Get mutable reference to a framed instance wrapped by `FramedTransport`
/// instance.
pub fn get_framed_mut(&mut self) -> &mut Framed<T, U> {
&mut self.framed
}
}
impl<S, T, U> Future for FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Item = ();
type Error = FramedTransportError<S::Error, U>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match mem::replace(&mut self.state, TransportState::Processing) {
TransportState::Processing => {
if self.poll_read() || self.poll_write() {
self.poll()
} else {
Ok(Async::NotReady)
}
}
TransportState::Error(err) => {
if self.framed.is_write_buf_empty()
|| (self.poll_write() || self.framed.is_write_buf_empty())
{
Err(err)
} else {
self.state = TransportState::Error(err);
Ok(Async::NotReady)
}
}
TransportState::FramedError(err) => Err(err),
TransportState::Stopping => Ok(Async::Ready(())),
}
}
}
pub struct IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
factory: F,
_t: PhantomData<(T,)>,
}
impl<T, U, F> IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
pub fn new(factory: F) -> Self {
IntoFramed {
factory,
_t: PhantomData,
}
}
}
impl<T, C, U, F> NewService<C> for IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
type Request = T;
type Response = Framed<T, U>;
type Error = ();
type InitError = ();
type Service = IntoFramedService<T, U, F>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &C) -> Self::Future {
ok(IntoFramedService {
factory: self.factory.clone(),
_t: PhantomData,
})
}
}
pub struct IntoFramedService<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
factory: F,
_t: PhantomData<(T,)>,
}
impl<T, U, F> Service for IntoFramedService<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
type Request = T;
type Response = Framed<T, U>;
type Error = ();
type Future = FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: T) -> Self::Future {
ok(Framed::new(req, (self.factory)()))
}
}
|
use std::env;
use std::fs;
use std::process::Command;
fn main() {
// Tell Cargo that if the given file changes, to rerun this build script.
println!("cargo:rerun-if-changed=../../shaders/");
let engine_dir = env::current_dir().unwrap(); // .
let project_dir = engine_dir.parent().unwrap().parent().unwrap(); // ../../
let shader_source_dir = project_dir.join("shaders"); // ../../shaders
let asset_dir = project_dir.join("assets"); // ../../assets
let shader_target_dir = asset_dir.join("shaders"); // ../../assets/shaders
// create required directories
fs::create_dir_all(&shader_target_dir).unwrap();
// compile shaders
let paths = fs::read_dir(shader_source_dir).unwrap();
for path in paths {
let path = path.as_ref().unwrap().path();
if let Some(ext) = path.extension() {
if ext == "hlsl" {
println!(
"Compiling shader {}",
&path.file_name().unwrap().to_str().unwrap()
);
let _ = compile_shader(&shader_target_dir, &path, "vert");
let _ = compile_shader(&shader_target_dir, &path, "frag");
}
}
}
}
fn compile_shader(
target_dir: &std::path::Path,
source_path: &std::path::Path,
shader_type: &str,
) -> std::process::Output {
let output_path = target_dir.join(format!(
"{}-{}.spv",
&source_path.file_stem().unwrap().to_str().unwrap(),
shader_type
));
let output = Command::new("glslc")
.arg("--target-env=vulkan1.2")
.arg("-fauto-combined-image-sampler")
.arg(format!("-fshader-stage={shader_type}"))
.arg(format!("-fentry-point={shader_type}"))
.arg(&source_path.display().to_string())
.arg(format!("-o{}", output_path.to_string_lossy()))
.output()
.expect("failed to compile shaders using glslc");
println!("Shader Compiler Output: {output:#?}");
assert!(output.status.success());
output
}
|
//! [`recvmsg`], [`sendmsg`], and related functions.
#![allow(unsafe_code)]
use crate::backend::{self, c};
use crate::fd::{AsFd, BorrowedFd, OwnedFd};
use crate::io::{self, IoSlice, IoSliceMut};
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::mem::{size_of, size_of_val, take};
use core::{ptr, slice};
use super::{RecvFlags, SendFlags, SocketAddrAny, SocketAddrV4, SocketAddrV6};
/// Macro for defining the amount of space used by CMSGs.
#[macro_export]
macro_rules! cmsg_space {
// Base Rules
(ScmRights($len:expr)) => {
$crate::net::__cmsg_space(
$len * ::core::mem::size_of::<$crate::fd::BorrowedFd<'static>>(),
)
};
// Combo Rules
(($($($x:tt)*),+)) => {
$(
cmsg_space!($($x)*) +
)+
0
};
}
#[doc(hidden)]
pub fn __cmsg_space(len: usize) -> usize {
unsafe { c::CMSG_SPACE(len.try_into().expect("CMSG_SPACE size overflow")) as usize }
}
/// Ancillary message for [`sendmsg`], [`sendmsg_v4`], [`sendmsg_v6`],
/// [`sendmsg_unix`], and [`sendmsg_any`].
#[non_exhaustive]
pub enum SendAncillaryMessage<'slice, 'fd> {
/// Send file descriptors.
ScmRights(&'slice [BorrowedFd<'fd>]),
}
impl SendAncillaryMessage<'_, '_> {
/// Get the maximum size of an ancillary message.
///
/// This can be helpful in determining the size of the buffer you allocate.
pub fn size(&self) -> usize {
let total_bytes = match self {
Self::ScmRights(slice) => size_of_val(*slice),
};
unsafe {
c::CMSG_SPACE(
total_bytes
.try_into()
.expect("size too large for CMSG_SPACE"),
) as usize
}
}
}
/// Ancillary message for [`recvmsg`].
#[non_exhaustive]
pub enum RecvAncillaryMessage<'a> {
/// Received file descriptors.
ScmRights(AncillaryIter<'a, OwnedFd>),
}
/// Buffer for sending ancillary messages.
pub struct SendAncillaryBuffer<'buf, 'slice, 'fd> {
/// Raw byte buffer for messages.
buffer: &'buf mut [u8],
/// The amount of the buffer that is used.
length: usize,
/// Phantom data for lifetime of `&'slice [BorrowedFd<'fd>]`.
_phantom: PhantomData<&'slice [BorrowedFd<'fd>]>,
}
impl<'buf> From<&'buf mut [u8]> for SendAncillaryBuffer<'buf, '_, '_> {
fn from(buffer: &'buf mut [u8]) -> Self {
Self::new(buffer)
}
}
impl Default for SendAncillaryBuffer<'_, '_, '_> {
fn default() -> Self {
Self::new(&mut [])
}
}
impl<'buf, 'slice, 'fd> SendAncillaryBuffer<'buf, 'slice, 'fd> {
/// Create a new, empty `SendAncillaryBuffer` from a raw byte buffer.
pub fn new(buffer: &'buf mut [u8]) -> Self {
Self {
buffer,
length: 0,
_phantom: PhantomData,
}
}
/// Returns a pointer to the message data.
pub(crate) fn as_control_ptr(&mut self) -> *mut u8 {
// When the length is zero, we may be using a `&[]` address, which
// may be an invalid but non-null pointer, and on some platforms, that
// causes `sendmsg` to fail with `EFAULT` or `EINVAL`
#[cfg(not(linux_kernel))]
if self.length == 0 {
return core::ptr::null_mut();
}
self.buffer.as_mut_ptr()
}
/// Returns the length of the message data.
pub(crate) fn control_len(&self) -> usize {
self.length
}
/// Delete all messages from the buffer.
pub fn clear(&mut self) {
self.length = 0;
}
/// Add an ancillary message to the buffer.
///
/// Returns `true` if the message was added successfully.
pub fn push(&mut self, msg: SendAncillaryMessage<'slice, 'fd>) -> bool {
match msg {
SendAncillaryMessage::ScmRights(fds) => {
let fds_bytes =
unsafe { slice::from_raw_parts(fds.as_ptr().cast::<u8>(), size_of_val(fds)) };
self.push_ancillary(fds_bytes, c::SOL_SOCKET as _, c::SCM_RIGHTS as _)
}
}
}
/// Pushes an ancillary message to the buffer.
fn push_ancillary(&mut self, source: &[u8], cmsg_level: c::c_int, cmsg_type: c::c_int) -> bool {
macro_rules! leap {
($e:expr) => {{
match ($e) {
Some(x) => x,
None => return false,
}
}};
}
// Calculate the length of the message.
let source_len = leap!(u32::try_from(source.len()).ok());
// Calculate the new length of the buffer.
let additional_space = unsafe { c::CMSG_SPACE(source_len) };
let new_length = leap!(self.length.checked_add(additional_space as usize));
let buffer = leap!(self.buffer.get_mut(..new_length));
// Fill the new part of the buffer with zeroes.
buffer[self.length..new_length].fill(0);
self.length = new_length;
// Get the last header in the buffer.
let last_header = leap!(messages::Messages::new(buffer).last());
// Set the header fields.
last_header.cmsg_len = unsafe { c::CMSG_LEN(source_len) } as _;
last_header.cmsg_level = cmsg_level;
last_header.cmsg_type = cmsg_type;
// Get the pointer to the payload and copy the data.
unsafe {
let payload = c::CMSG_DATA(last_header);
ptr::copy_nonoverlapping(source.as_ptr(), payload, source_len as _);
}
true
}
}
impl<'slice, 'fd> Extend<SendAncillaryMessage<'slice, 'fd>>
for SendAncillaryBuffer<'_, 'slice, 'fd>
{
fn extend<T: IntoIterator<Item = SendAncillaryMessage<'slice, 'fd>>>(&mut self, iter: T) {
// TODO: This could be optimized to add every message in one go.
iter.into_iter().all(|msg| self.push(msg));
}
}
/// Buffer for receiving ancillary messages.
pub struct RecvAncillaryBuffer<'buf> {
/// Raw byte buffer for messages.
buffer: &'buf mut [u8],
/// The portion of the buffer we've read from already.
read: usize,
/// The amount of the buffer that is used.
length: usize,
}
impl<'buf> From<&'buf mut [u8]> for RecvAncillaryBuffer<'buf> {
fn from(buffer: &'buf mut [u8]) -> Self {
Self::new(buffer)
}
}
impl Default for RecvAncillaryBuffer<'_> {
fn default() -> Self {
Self::new(&mut [])
}
}
impl<'buf> RecvAncillaryBuffer<'buf> {
/// Create a new, empty `RecvAncillaryBuffer` from a raw byte buffer.
pub fn new(buffer: &'buf mut [u8]) -> Self {
Self {
buffer,
read: 0,
length: 0,
}
}
/// Returns a pointer to the message data.
pub(crate) fn as_control_ptr(&mut self) -> *mut u8 {
// When the length is zero, we may be using a `&[]` address, which
// may be an invalid but non-null pointer, and on some platforms, that
// causes `sendmsg` to fail with `EFAULT` or `EINVAL`
#[cfg(not(linux_kernel))]
if self.buffer.is_empty() {
return core::ptr::null_mut();
}
self.buffer.as_mut_ptr()
}
/// Returns the length of the message data.
pub(crate) fn control_len(&self) -> usize {
self.buffer.len()
}
/// Set the length of the message data.
///
/// # Safety
///
/// The buffer must be filled with valid message data.
pub(crate) unsafe fn set_control_len(&mut self, len: usize) {
self.length = len;
self.read = 0;
}
/// Delete all messages from the buffer.
pub(crate) fn clear(&mut self) {
self.drain().for_each(drop);
}
/// Drain all messages from the buffer.
pub fn drain(&mut self) -> AncillaryDrain<'_> {
AncillaryDrain {
messages: messages::Messages::new(&mut self.buffer[self.read..][..self.length]),
read: &mut self.read,
length: &mut self.length,
}
}
}
impl Drop for RecvAncillaryBuffer<'_> {
fn drop(&mut self) {
self.clear();
}
}
/// An iterator that drains messages from a `RecvAncillaryBuffer`.
pub struct AncillaryDrain<'buf> {
/// Inner iterator over messages.
messages: messages::Messages<'buf>,
/// Increment the number of messages we've read.
read: &'buf mut usize,
/// Decrement the total length.
length: &'buf mut usize,
}
impl<'buf> AncillaryDrain<'buf> {
/// A closure that converts a message into a `RecvAncillaryMessage`.
fn cvt_msg(
read: &mut usize,
length: &mut usize,
msg: &c::cmsghdr,
) -> Option<RecvAncillaryMessage<'buf>> {
unsafe {
// Advance the "read" pointer.
let msg_len = msg.cmsg_len as usize;
*read += msg_len;
*length -= msg_len;
// Get a pointer to the payload.
let payload = c::CMSG_DATA(msg);
let payload_len = msg.cmsg_len as usize - c::CMSG_LEN(0) as usize;
// Get a mutable slice of the payload.
let payload: &'buf mut [u8] = slice::from_raw_parts_mut(payload, payload_len);
// Determine what type it is.
let (level, msg_type) = (msg.cmsg_level, msg.cmsg_type);
match (level as _, msg_type as _) {
(c::SOL_SOCKET, c::SCM_RIGHTS) => {
// Create an iterator that reads out the file descriptors.
let fds = AncillaryIter::new(payload);
Some(RecvAncillaryMessage::ScmRights(fds))
}
_ => None,
}
}
}
}
impl<'buf> Iterator for AncillaryDrain<'buf> {
type Item = RecvAncillaryMessage<'buf>;
fn next(&mut self) -> Option<Self::Item> {
let read = &mut self.read;
let length = &mut self.length;
self.messages.find_map(|ev| Self::cvt_msg(read, length, ev))
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, max) = self.messages.size_hint();
(0, max)
}
fn fold<B, F>(self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
let read = self.read;
let length = self.length;
self.messages
.filter_map(|ev| Self::cvt_msg(read, length, ev))
.fold(init, f)
}
fn count(self) -> usize {
let read = self.read;
let length = self.length;
self.messages
.filter_map(|ev| Self::cvt_msg(read, length, ev))
.count()
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
let read = self.read;
let length = self.length;
self.messages
.filter_map(|ev| Self::cvt_msg(read, length, ev))
.last()
}
fn collect<B: FromIterator<Self::Item>>(self) -> B
where
Self: Sized,
{
let read = self.read;
let length = self.length;
self.messages
.filter_map(|ev| Self::cvt_msg(read, length, ev))
.collect()
}
}
impl FusedIterator for AncillaryDrain<'_> {}
/// `sendmsg(msghdr)`—Sends a message on a socket.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html
/// [Linux]: https://man7.org/linux/man-pages/man2/sendmsg.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
/// [NetBSD]: https://man.netbsd.org/sendmsg.2
/// [OpenBSD]: https://man.openbsd.org/sendmsg.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=sendmsg§ion=2
/// [illumos]: https://illumos.org/man/3SOCKET/sendmsg
#[inline]
pub fn sendmsg(
socket: impl AsFd,
iov: &[IoSlice<'_>],
control: &mut SendAncillaryBuffer<'_, '_, '_>,
flags: SendFlags,
) -> io::Result<usize> {
backend::net::syscalls::sendmsg(socket.as_fd(), iov, control, flags)
}
/// `sendmsg(msghdr)`—Sends a message on a socket to a specific IPv4 address.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html
/// [Linux]: https://man7.org/linux/man-pages/man2/sendmsg.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
/// [NetBSD]: https://man.netbsd.org/sendmsg.2
/// [OpenBSD]: https://man.openbsd.org/sendmsg.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=sendmsg§ion=2
/// [illumos]: https://illumos.org/man/3SOCKET/sendmsg
#[inline]
pub fn sendmsg_v4(
socket: impl AsFd,
addr: &SocketAddrV4,
iov: &[IoSlice<'_>],
control: &mut SendAncillaryBuffer<'_, '_, '_>,
flags: SendFlags,
) -> io::Result<usize> {
backend::net::syscalls::sendmsg_v4(socket.as_fd(), addr, iov, control, flags)
}
/// `sendmsg(msghdr)`—Sends a message on a socket to a specific IPv6 address.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html
/// [Linux]: https://man7.org/linux/man-pages/man2/sendmsg.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
/// [NetBSD]: https://man.netbsd.org/sendmsg.2
/// [OpenBSD]: https://man.openbsd.org/sendmsg.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=sendmsg§ion=2
/// [illumos]: https://illumos.org/man/3SOCKET/sendmsg
#[inline]
pub fn sendmsg_v6(
socket: impl AsFd,
addr: &SocketAddrV6,
iov: &[IoSlice<'_>],
control: &mut SendAncillaryBuffer<'_, '_, '_>,
flags: SendFlags,
) -> io::Result<usize> {
backend::net::syscalls::sendmsg_v6(socket.as_fd(), addr, iov, control, flags)
}
/// `sendmsg(msghdr)`—Sends a message on a socket to a specific Unix-domain
/// address.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html
/// [Linux]: https://man7.org/linux/man-pages/man2/sendmsg.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
/// [NetBSD]: https://man.netbsd.org/sendmsg.2
/// [OpenBSD]: https://man.openbsd.org/sendmsg.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=sendmsg§ion=2
/// [illumos]: https://illumos.org/man/3SOCKET/sendmsg
#[inline]
#[cfg(unix)]
pub fn sendmsg_unix(
socket: impl AsFd,
addr: &super::SocketAddrUnix,
iov: &[IoSlice<'_>],
control: &mut SendAncillaryBuffer<'_, '_, '_>,
flags: SendFlags,
) -> io::Result<usize> {
backend::net::syscalls::sendmsg_unix(socket.as_fd(), addr, iov, control, flags)
}
/// `sendmsg(msghdr)`—Sends a message on a socket to a specific address.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/sendmsg.html
/// [Linux]: https://man7.org/linux/man-pages/man2/sendmsg.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/sendmsg.2.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=sendmsg&sektion=2
/// [NetBSD]: https://man.netbsd.org/sendmsg.2
/// [OpenBSD]: https://man.openbsd.org/sendmsg.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=sendmsg§ion=2
/// [illumos]: https://illumos.org/man/3SOCKET/sendmsg
#[inline]
pub fn sendmsg_any(
socket: impl AsFd,
addr: Option<&SocketAddrAny>,
iov: &[IoSlice<'_>],
control: &mut SendAncillaryBuffer<'_, '_, '_>,
flags: SendFlags,
) -> io::Result<usize> {
match addr {
None => backend::net::syscalls::sendmsg(socket.as_fd(), iov, control, flags),
Some(SocketAddrAny::V4(addr)) => {
backend::net::syscalls::sendmsg_v4(socket.as_fd(), addr, iov, control, flags)
}
Some(SocketAddrAny::V6(addr)) => {
backend::net::syscalls::sendmsg_v6(socket.as_fd(), addr, iov, control, flags)
}
#[cfg(unix)]
Some(SocketAddrAny::Unix(addr)) => {
backend::net::syscalls::sendmsg_unix(socket.as_fd(), addr, iov, control, flags)
}
}
}
/// `recvmsg(msghdr)`—Receives a message from a socket.
///
/// # References
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/recvmsg.html
/// [Linux]: https://man7.org/linux/man-pages/man2/recvmsg.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/recvmsg.2.html
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=recvmsg&sektion=2
/// [NetBSD]: https://man.netbsd.org/recvmsg.2
/// [OpenBSD]: https://man.openbsd.org/recvmsg.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=recvmsg§ion=2
/// [illumos]: https://illumos.org/man/3SOCKET/recvmsg
#[inline]
pub fn recvmsg(
socket: impl AsFd,
iov: &mut [IoSliceMut<'_>],
control: &mut RecvAncillaryBuffer<'_>,
flags: RecvFlags,
) -> io::Result<RecvMsgReturn> {
backend::net::syscalls::recvmsg(socket.as_fd(), iov, control, flags)
}
/// The result of a successful [`recvmsg`] call.
pub struct RecvMsgReturn {
/// The number of bytes received.
pub bytes: usize,
/// The flags received.
pub flags: RecvFlags,
/// The address of the socket we received from, if any.
pub address: Option<SocketAddrAny>,
}
/// An iterator over data in an ancillary buffer.
pub struct AncillaryIter<'data, T> {
/// The data we're iterating over.
data: &'data mut [u8],
/// The raw data we're removing.
_marker: PhantomData<T>,
}
impl<'data, T> AncillaryIter<'data, T> {
/// Create a new iterator over data in an ancillary buffer.
///
/// # Safety
///
/// The buffer must contain valid ancillary data.
unsafe fn new(data: &'data mut [u8]) -> Self {
assert_eq!(data.len() % size_of::<T>(), 0);
Self {
data,
_marker: PhantomData,
}
}
}
impl<'data, T> Drop for AncillaryIter<'data, T> {
fn drop(&mut self) {
self.for_each(drop);
}
}
impl<T> Iterator for AncillaryIter<'_, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
// See if there is a next item.
if self.data.len() < size_of::<T>() {
return None;
}
// Get the next item.
let item = unsafe { self.data.as_ptr().cast::<T>().read_unaligned() };
// Move forward.
let data = take(&mut self.data);
self.data = &mut data[size_of::<T>()..];
Some(item)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
fn count(self) -> usize {
self.len()
}
fn last(mut self) -> Option<Self::Item> {
self.next_back()
}
}
impl<T> FusedIterator for AncillaryIter<'_, T> {}
impl<T> ExactSizeIterator for AncillaryIter<'_, T> {
fn len(&self) -> usize {
self.data.len() / size_of::<T>()
}
}
impl<T> DoubleEndedIterator for AncillaryIter<'_, T> {
fn next_back(&mut self) -> Option<Self::Item> {
// See if there is a next item.
if self.data.len() < size_of::<T>() {
return None;
}
// Get the next item.
let item = unsafe {
let ptr = self.data.as_ptr().add(self.data.len() - size_of::<T>());
ptr.cast::<T>().read_unaligned()
};
// Move forward.
let len = self.data.len();
let data = take(&mut self.data);
self.data = &mut data[..len - size_of::<T>()];
Some(item)
}
}
mod messages {
use crate::backend::c;
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::mem::zeroed;
use core::ptr::NonNull;
/// An iterator over the messages in an ancillary buffer.
pub(super) struct Messages<'buf> {
/// The message header we're using to iterator over the messages.
msghdr: c::msghdr,
/// The current pointer to the next message header to return.
///
/// This has a lifetime of `'buf`.
header: Option<NonNull<c::cmsghdr>>,
/// Capture the original lifetime of the buffer.
_buffer: PhantomData<&'buf mut [u8]>,
}
impl<'buf> Messages<'buf> {
/// Create a new iterator over messages from a byte buffer.
pub(super) fn new(buf: &'buf mut [u8]) -> Self {
let msghdr = {
let mut h: c::msghdr = unsafe { zeroed() };
h.msg_control = buf.as_mut_ptr().cast();
h.msg_controllen = buf.len().try_into().expect("buffer too large for msghdr");
h
};
// Get the first header.
let header = NonNull::new(unsafe { c::CMSG_FIRSTHDR(&msghdr) });
Self {
msghdr,
header,
_buffer: PhantomData,
}
}
}
impl<'a> Iterator for Messages<'a> {
type Item = &'a mut c::cmsghdr;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
// Get the current header.
let header = self.header?;
// Get the next header.
self.header = NonNull::new(unsafe { c::CMSG_NXTHDR(&self.msghdr, header.as_ptr()) });
// If the headers are equal, we're done.
if Some(header) == self.header {
self.header = None;
}
// SAFETY: The lifetime of `header` is tied to this.
Some(unsafe { &mut *header.as_ptr() })
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.header.is_some() {
// The remaining buffer *could* be filled with zero-length
// messages.
let max_size = unsafe { c::CMSG_LEN(0) } as usize;
let remaining_count = self.msghdr.msg_controllen as usize / max_size;
(1, Some(remaining_count))
} else {
(0, Some(0))
}
}
}
impl FusedIterator for Messages<'_> {}
}
|
mod extractor{
} |
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use super::toplevel::{DeclarationList, DeclarationListParser};
use crate::lexer::preprocessor::context::PreprocContext;
use crate::lexer::{Lexer, LocToken, Token};
use crate::parser::declarations::{DeclHint, DeclarationParser, Specifier};
use crate::parser::statement::Statement;
use crate::{check_semicolon, check_semicolon_or_not};
#[derive(Clone, Debug, PartialEq)]
pub struct NsName {
pub(crate) inline: bool,
pub(crate) name: String,
}
pub type NsNames = Vec<NsName>;
#[derive(Clone, Debug, PartialEq)]
pub struct Namespace {
pub(crate) inline: bool,
pub(crate) name: Option<NsNames>,
pub(crate) alias: Option<NsNames>,
pub(crate) body: Option<Box<DeclarationList>>,
}
struct NsNamesParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> NsNamesParser<'a, 'b, PC> {
fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
fn parse(self) -> (Option<LocToken>, Option<NsNames>) {
let mut tok = self.lexer.next_useful();
let mut names = Vec::new();
let mut inline = false;
loop {
match tok.tok {
Token::Inline => {
inline = true;
}
Token::Identifier(id) => {
names.push(NsName { inline, name: id });
}
Token::ColonColon => {
inline = false;
}
_ => {
return (Some(tok), Some(names));
}
}
tok = self.lexer.next_useful();
}
}
}
pub(super) enum NPRes {
Namespace(Namespace),
Declaration(Statement),
}
pub struct NamespaceParser<'a, 'b, PC: PreprocContext> {
lexer: &'b mut Lexer<'a, PC>,
}
impl<'a, 'b, PC: PreprocContext> NamespaceParser<'a, 'b, PC> {
pub(super) fn new(lexer: &'b mut Lexer<'a, PC>) -> Self {
Self { lexer }
}
pub(super) fn parse(self, tok: Option<LocToken>) -> (Option<LocToken>, Option<NPRes>) {
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
let inline = if tok.tok == Token::Inline {
let tok = self.lexer.next_useful();
if tok.tok != Token::Namespace {
let dp = DeclarationParser::new(self.lexer);
let hint = DeclHint::Specifier(Specifier::INLINE);
let (tok, decl) = dp.parse(Some(tok), Some(hint));
let (tok, decl) = check_semicolon_or_not!(self, tok, decl);
return (tok, Some(NPRes::Declaration(decl.unwrap())));
}
true
} else if tok.tok != Token::Namespace {
return (Some(tok), None);
} else {
false
};
let np = NsNamesParser::new(self.lexer);
let (tok, name) = np.parse();
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
match tok.tok {
Token::LeftBrace => {
let dlp = DeclarationListParser::new(self.lexer);
let (tok, body) = dlp.parse(None);
let tok = tok.unwrap_or_else(|| self.lexer.next_useful());
if tok.tok != Token::RightBrace {
unreachable!("Invalid token in namespace definition: {:?}", tok);
}
let ns = Namespace {
inline,
name,
alias: None,
body: body.map(Box::new),
};
(None, Some(NPRes::Namespace(ns)))
}
Token::Equal => {
let np = NsNamesParser::new(self.lexer);
let (tok, alias) = np.parse();
check_semicolon!(self, tok);
let ns = Namespace {
inline,
name,
alias,
body: None,
};
(None, Some(NPRes::Namespace(ns)))
}
_ => {
unreachable!("Invalid token in namespace definition: {:?}", tok);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::preprocessor::context::DefaultContext;
use pretty_assertions::assert_eq;
#[test]
fn test_namespace_one() {
let mut l = Lexer::<DefaultContext>::new(b"A");
let p = NsNamesParser::new(&mut l);
let (_, ns) = p.parse();
assert_eq!(
ns.unwrap(),
vec![NsName {
inline: false,
name: "A".to_string(),
}]
);
}
#[test]
fn test_namespace_multiple() {
let mut l = Lexer::<DefaultContext>::new(b"A::inline B::C::inline D::E");
let p = NsNamesParser::new(&mut l);
let (_, ns) = p.parse();
assert_eq!(
ns.unwrap(),
vec![
NsName {
inline: false,
name: "A".to_string(),
},
NsName {
inline: true,
name: "B".to_string(),
},
NsName {
inline: false,
name: "C".to_string(),
},
NsName {
inline: true,
name: "D".to_string(),
},
NsName {
inline: false,
name: "E".to_string(),
},
]
);
}
}
|
use alloc::heap::{Alloc, Layout, AllocErr};
extern "C" {
pub fn IOMalloc(size: usize) -> *mut u8;
pub fn IOFree(ptr: *mut u8, size: usize);
pub fn IOMallocAligned(size: usize, alignment: usize) -> *mut u8;
pub fn IOFreeAligned(ptr: *mut u8, size: usize);
}
pub struct Allocator;
unsafe impl<'a> Alloc for &'a Allocator {
unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
let op = IOMallocAligned(layout.size(), layout.align());
if op.is_null() {
return Err(AllocErr::invalid_input("Unable to allocate IO kernel memory!"));
}
Ok(op)
}
unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
if !ptr.is_null() && layout.size() > 0 {
IOFreeAligned(ptr, layout.size());
}
}
}
|
pub mod game;
pub mod resources;
pub mod scene_manager;
pub mod camera;
pub mod physics; |
use fn_search_backend_db::diesel::{pg::PgConnection, prelude::*, result::QueryResult};
use fn_search_backend_db::models::FunctionWithRepo;
pub fn get_all_func_sigs(conn: &PgConnection) -> QueryResult<Vec<(String, i64)>> {
use fn_search_backend_db::schema::functions::dsl::*;
Ok(functions
.select((type_signature, id))
.load::<(String, i64)>(conn)?)
}
pub fn get_functions(conn: &PgConnection, ids: &[i64]) -> QueryResult<Vec<FunctionWithRepo>> {
use fn_search_backend_db::schema::repository_function_mat_view::dsl::*;
let fns = repository_function_mat_view
.filter(func_id.eq_any(ids))
.load::<FunctionWithRepo>(conn)?;
Ok(fns)
}
|
use crate::models::{Level, Score};
use deadpool_postgres::Client;
use tokio_pg_mapper::FromTokioPostgresRow;
pub async fn get_levels(client: &Client) -> Vec<Level> {
let statement = client.prepare("select * from levels").await.unwrap();
let levels = client
.query(&statement, &[])
.await
.unwrap()
.iter()
.map(|row| Level::from_row_ref(row).unwrap())
.collect::<Vec<Level>>();
levels
}
pub async fn get_scores(client: &Client) -> Vec<Score> {
let statement = client.prepare("select * from scores").await.unwrap();
let scores = client
.query(&statement, &[])
.await
.unwrap()
.iter()
.map(|row| Score::from_row_ref(row).unwrap())
.collect::<Vec<Score>>();
scores
}
pub async fn get_scores_by_id(client: &Client, challengeid: i32) -> Vec<Score> {
let statement = client.prepare("select * from scores where challengeid = $1").await.unwrap();
let scores = client
.query(&statement, &[&challengeid])
.await
.unwrap()
.iter()
.map(|row| Score::from_row_ref(row).unwrap())
.collect::<Vec<Score>>();
scores
}
pub async fn insert_level(
client: &Client,
creator: String,
startcode: String,
endcode: String,
name: String,
) -> Vec<Level> {
let statement = client.prepare("insert into levels (creator, endcode, startcode, name) values ($1, $2, $3, $4) returning id, endcode, startcode, creator, name").await.unwrap();
let level = client
.query(&statement, &[&creator, &endcode, &startcode, &name])
.await
.expect("Error getting levels")
.iter()
.map(|row| Level::from_row_ref(row).unwrap())
.collect::<Vec<Level>>();
// .pop()
// .ok_or(std::io::Error::new(
// std::io::ErrorKind::Other,
// "Error inserting level",
// ));
return level;
}
pub async fn insert_score(
client: &Client,
username: String,
score: i32,
challengeid: i32
) -> Vec<Score> {
let statement = client.prepare("insert into scores (username, score, challengeid) values ($1, $2, $3) returning id, username, score, challengeid").await.unwrap();
let score = client
.query(&statement, &[&username, &score, &challengeid])
.await
.expect("Error getting levels")
.iter()
.map(|row| Score::from_row_ref(row).unwrap())
.collect::<Vec<Score>>();
// .pop()
// .ok_or(std::io::Error::new(
// std::io::ErrorKind::Other,
// "Error inserting level",
// ));
return score;
} |
#[cfg(feature = "stm32f4xx-hal")]
use stm32f4xx_hal::stm32;
#[cfg(feature = "stm32f7xx-hal")]
use stm32f7xx_hal::pac as stm32;
use stm32::ethernet_mac::{MACMIIAR, MACMIIDR};
use core::option::Option;
use crate::smi::SMI;
#[allow(dead_code)]
mod consts {
pub const PHY_REG_BCR: u8 = 0x00;
pub const PHY_REG_BSR: u8 = 0x01;
pub const PHY_REG_ID1: u8 = 0x02;
pub const PHY_REG_ID2: u8 = 0x03;
pub const PHY_REG_ANTX: u8 = 0x04;
pub const PHY_REG_ANRX: u8 = 0x05;
pub const PHY_REG_ANEXP: u8 = 0x06;
pub const PHY_REG_ANNPTX: u8 = 0x07;
pub const PHY_REG_ANNPRX: u8 = 0x08;
pub const PHY_REG_SSR: u8 = 0x1F; // Special Status Register
pub const PHY_REG_BCR_COLTEST: u16 = 1 << 7;
pub const PHY_REG_BCR_FD: u16 = 1 << 8;
pub const PHY_REG_BCR_ANRST: u16 = 1 << 9;
pub const PHY_REG_BCR_ISOLATE: u16 = 1 << 10;
pub const PHY_REG_BCR_POWERDN: u16 = 1 << 11;
pub const PHY_REG_BCR_AN: u16 = 1 << 12;
pub const PHY_REG_BCR_100M: u16 = 1 << 13;
pub const PHY_REG_BCR_LOOPBACK: u16 = 1 << 14;
pub const PHY_REG_BCR_RESET: u16 = 1 << 15;
pub const PHY_REG_BSR_JABBER: u16 = 1 << 1;
pub const PHY_REG_BSR_UP: u16 = 1 << 2;
pub const PHY_REG_BSR_FAULT: u16 = 1 << 4;
pub const PHY_REG_BSR_ANDONE: u16 = 1 << 5;
pub const PHY_REG_SSR_ANDONE: u16 = 1 << 12;
pub const PHY_REG_SSR_SPEED: u16 = 0b111 << 2;
pub const PHY_REG_SSR_10BASE_HD: u16 = 0b001 << 2;
pub const PHY_REG_SSR_10BASE_FD: u16 = 0b101 << 2;
pub const PHY_REG_SSR_100BASE_HD: u16 = 0b010 << 2;
pub const PHY_REG_SSR_100BASE_FD: u16 = 0b110 << 2;
}
use self::consts::*;
/// Driver for the *LAN8742* PHY using `SMI`
///
/// # References
/// * [Datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/DS_LAN8742_00001989A.pdf)
/// * [libopencm3 driver](https://github.com/libopencm3/libopencm3/blob/master/lib/ethernet/mac_stm32fxx7.c)
pub struct Phy<'a> {
smi: SMI<'a>,
phy: u8,
}
impl<'a> Phy<'a> {
/// Allocate
pub fn new(macmiiar: &'a MACMIIAR, macmiidr: &'a MACMIIDR, phy: u8) -> Self {
let smi = SMI::new(macmiiar, macmiidr);
Phy { smi, phy }
}
/// Read current status registers
///
/// You may keep the returned [`PhyStatus`](struct.PhyStatus.html)
/// to compare it with to a future [`status()`](#method.status).
pub fn status(&self) -> PhyStatus {
PhyStatus {
bsr: self.smi.read(self.phy, PHY_REG_BSR),
ssr: self.smi.read(self.phy, PHY_REG_SSR),
}
}
/// Reset the PHY
pub fn reset(&self) -> &Self {
self.smi.set_bits(self.phy, PHY_REG_BCR, PHY_REG_BCR_RESET);
// wait until reset bit is cleared by phy
while (self.smi.read(self.phy, PHY_REG_BCR) & PHY_REG_BCR_RESET) == PHY_REG_BCR_RESET {}
self
}
/// Enable 10/100 Mbps half/full-duplex auto-negotiation
pub fn set_autoneg(&self) -> &Self {
self.smi.set_bits(
self.phy,
PHY_REG_BCR,
PHY_REG_BCR_AN | PHY_REG_BCR_ANRST | PHY_REG_BCR_100M,
);
self
}
}
/// PHY status register
#[derive(Copy, Clone)]
pub struct PhyStatus {
bsr: u16,
ssr: u16,
}
impl PhyStatus {
/// Has link?
pub fn link_detected(self) -> bool {
(self.bsr & PHY_REG_BSR_UP) == PHY_REG_BSR_UP
}
/// Has auto-negotiated?
pub fn autoneg_done(self) -> bool {
(self.bsr & PHY_REG_BSR_ANDONE) == PHY_REG_BSR_ANDONE
|| (self.ssr & PHY_REG_SSR_ANDONE) == PHY_REG_SSR_ANDONE
}
/// FD, not HD?
pub fn is_full_duplex(self) -> Option<bool> {
match self.ssr & PHY_REG_SSR_SPEED {
PHY_REG_SSR_10BASE_HD | PHY_REG_SSR_100BASE_HD => Some(false),
PHY_REG_SSR_10BASE_FD | PHY_REG_SSR_100BASE_FD => Some(true),
_ => None,
}
}
/// 10, 100, or 0 Mbps
pub fn speed(self) -> u32 {
match self.ssr & PHY_REG_SSR_SPEED {
PHY_REG_SSR_10BASE_HD | PHY_REG_SSR_10BASE_FD => 10,
PHY_REG_SSR_100BASE_HD | PHY_REG_SSR_100BASE_FD => 100,
_ => 0,
}
}
/// Error?
pub fn remote_fault(self) -> bool {
(self.bsr & PHY_REG_BSR_FAULT) == PHY_REG_BSR_FAULT
}
}
/// Compare on base of link detected, full-duplex, and speed
/// attributes.
impl PartialEq for PhyStatus {
fn eq(&self, other: &PhyStatus) -> bool {
(!self.link_detected() && !other.link_detected())
|| (self.link_detected() == other.link_detected()
&& self.is_full_duplex() == other.is_full_duplex()
&& self.speed() == other.speed())
}
}
|
extern crate time;
extern crate term;
use std::io::net::udp::UdpSocket;
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::collections::HashMap;
use std::num::SignedInt;
//use std::io::prelude::*;
use message::Message;
use resource::Resource;
use question::Question;
use data::Data;
#[deriving(Clone)]
pub struct Server {
pub socket: UdpSocket,
pub ip_lookup: HashMap<u16,SocketAddr>,
pub msg_lookup: HashMap<u16,Message>,
pub waiting_queue: Vec<Message>,
pub cache: HashMap<Vec<u8>,Resource>,
pub soa_cache: HashMap<Vec<u8>,Resource>,
pub option: int
}
impl Server {
pub fn new(addr: Vec<u8>, opt: int) -> Server {
let mut t = term::stdout().unwrap();
let mut sock = SocketAddr {ip: Ipv4Addr(addr[0], addr[1], addr[2], addr[3]), port: 53};
write!(t, "\nServer starting on: ");
t.fg(term::color::RED).unwrap();
(write!(t, "{}.{}.{}.{}\n", addr[0], addr[1], addr[2], addr[3])).unwrap();
t.reset();
return Server {
ip_lookup: HashMap::new(),
msg_lookup: HashMap::new(),
waiting_queue: vec![],
socket: match UdpSocket::bind(sock) {
Ok(s) => s,
Err(e) => {panic!(e)},
},
cache: HashMap::new(),
soa_cache: HashMap::new(),
option: opt
};
}
pub fn run(&mut self) {
println!("Running...\n");
loop {
let mut buffer = [0, ..512];
match self.socket.recv_from(&mut buffer) {
Ok((length, src)) => {
self.process(&mut buffer, length, src);
},
Err(e) => {
println!("{}", e);
},
}
}
}
pub fn process(&mut self, buffer: &mut [u8], length: uint, src: SocketAddr) {
self.update_waiting_queue();
let mut message = Message::new();
match message.read_in(buffer, length) {
Ok(()) => {},
Err(a) => {
println!("{}", a);
return;
}
}
match self.option {
1 => {
message.print();
},
2 => {
message.questions[0].qname.print_as_hostname();
},
_ => {}
}
for i in range(0, self.waiting_queue.len()) {
if self.waiting_queue[i].header.id == message.header.id {
self.waiting_queue.remove(i);
break;
}
}
match self.check_cache(&mut message) {
Some(mut res) => {
match message.questions[0].qname.tld() {
Some(tld) => {
let mut i = 0;
while i < res.len() {
if res[i].rname.equals(tld.clone()) {
match res[i].ip_addr() {
Some(ip) => {
self.send_message(&mut message, ip);
return;
}
None => {}
}
}
i = i + 1;
}
}
None => {}
}
message.header.qr = 0x8000;
message.header.ancount = res.len() as u16;
message.answers.push_all(res.as_slice());
self.send_message(&mut message, src);
},
None => {
self.message_direction(&mut message, src);
},
}
return;
}
fn update_waiting_queue(&mut self) {
let mut i = 0;
while i < self.waiting_queue.len() {
if ((time::precise_time_ns() as i64) - self.waiting_queue[i].timestamp).abs() > (800000000) {
let mut msg = self.waiting_queue[i].clone();
let sock = self.waiting_queue[i].next_server();
match sock {
Some(addr) => {
self.send_message(&mut msg, addr);
self.waiting_queue[i].timestamp = time::precise_time_ns() as i64;
i = i + 1;
},
None => {
self.waiting_queue.remove(i);
}
}
} else {
i = i + 1;
}
}
}
fn message_direction(&mut self, message: &mut Message, src: SocketAddr) {
match message.header.qr {
0x0000 => {self.request(message, src);},
0x8000 => {self.response(message);},
_ => {return;},
}
return;
}
fn response(&mut self, message: &mut Message) {
match (message.header.ancount, message.header.nscount, message.header.arcount) {
/// ancount nscount arcount action
(0, 0, 0) => {return},
(1, _, _) => {self.process_single_answer(message)},
(2...999, _, _) => {self.process_multiple_answers(message)},
(0, 1...999, 0) => {self.process_name_servers(message)},
(0, _, 1...999) => {self.process_additional_records(message)},
(_, _, _) => {return;}
}
}
fn request(&mut self, message: &mut Message, src: SocketAddr) {
self.ip_lookup.insert(message.header.id, src);
self.send_message(message, SocketAddr {ip: Ipv4Addr(198, 41, 0, 4), port: 53});
message.timestamp = time::precise_time_ns() as i64;
self.waiting_queue.push(message.clone());
return;
}
fn process_single_answer(&mut self, message: &mut Message) {
self.update_cache(message);
if (message.contains_type(5)) && (message.header.ancount == 1) {
let mut ns_query = Message::new();
ns_query.generate_query(message.answers[0].rdata.write());
match self.check_cache(&mut ns_query) {
Some(res) => {
message.answers.push_all(res.as_slice());
message.header.ancount = res.len() as u16;
match self.query_origin_addr(message) {
Some(addr) => {
self.send_message(message, addr);
return;
},
None => {
return;
},
}
},
None => {},
}
self.msg_lookup.insert(ns_query.header.id, message.clone());
self.send_message(&mut ns_query, SocketAddr {ip: Ipv4Addr(198, 41, 0, 4), port: 53});
ns_query.timestamp = time::precise_time_ns() as i64;
self.waiting_queue.push(ns_query.clone());
return;
}
while self.is_server_query_server(message) == true {
match self.server_query_response(message) {
Some(mut msg) => {
if msg.contains_type(5) {
msg.header.qr = 0x8000;
msg.answers.push_all(message.answers.as_slice());
msg.header.ancount = msg.header.ancount + message.header.ancount;
match self.query_origin_addr(&mut msg) {
Some(addr) => {
self.send_message(&mut msg, addr);
return;
},
None => {
*message = msg.clone();
continue;
},
}
} else {
msg.header.qr = 0x0000;
msg.drop_records();
match message.answers[0].ip_addr() {
Some(ip) => {
self.send_message(&mut msg, ip);
},
None => {}
}
self.msg_lookup.remove(&message.header.id);
msg.timestamp = time::precise_time_ns() as i64;
self.waiting_queue.push(msg.clone());
return;
}
},
None => {
match self.query_origin_addr(message) {
Some(a) => {
self.send_message(message, a);
return;
},
None => {
return;
}
}
},
}
}
match self.query_origin_addr(message) {
Some(a) => {
self.send_message(message, a);
return;
},
None => {
return;
}
}
}
fn process_multiple_answers(&mut self, message: &mut Message) {
self.update_cache(message);
if message.contains_type(1) && message.contains_type(5) {
match self.query_origin_addr(message) {
Some(addr) => {
self.send_message(message, addr);
return;
},
None => {return;}
}
}
if message.contains_type(1) {
match self.query_origin_addr(message) {
Some(addr) => {
self.send_message(message, addr);
return;
},
None => {return;}
}
}
}
fn process_additional_records(&mut self, message: &mut Message) {
self.update_cache(message);
match message.next_server() {
Some(addr) => {
message.header.qr = 0x0000;
self.send_message(message, addr);
message.timestamp = time::precise_time_ns() as i64;
self.waiting_queue.push(message.clone());
return;
},
None => {
return;
}
}
}
fn process_name_servers(&mut self, message: &mut Message) {
self.update_cache(message);
if message.questions[0].qtype == 0x0006 {
let sa: SocketAddr = self.query_origin_addr(message).unwrap();
self.send_message(message, sa);
return;
}
let mut ns_query = Message::new();
ns_query.generate_query(message.authority[0].rdata.write());
match self.check_cache(&mut ns_query) {
Some(res) => {
for r in res.iter() {
match r.clone().ip_addr() {
Some(ip) => {
message.header.qr = 0x0000;
self.send_message(message, ip);
return;
}
None => {}
}
}
},
None => {},
}
self.msg_lookup.insert(ns_query.header.id, message.clone());
self.send_message(&mut ns_query, SocketAddr {ip: Ipv4Addr(198, 41, 0, 4), port: 53});
ns_query.timestamp = time::precise_time_ns() as i64;
self.waiting_queue.push(ns_query.clone());
return;
}
fn send_message<'a>(&'a mut self, message: &'a mut Message, sock: SocketAddr) -> &mut Message {
match self.socket.send_to(message.clone().write().as_slice(), sock) {
Ok(()) => {
return message;
},
Err(e) => {
println!("{}, failed to send", e);
return message;
},
};
}
fn check_cache(&mut self, message: &mut Message) -> Option<Vec<Resource>> {
if message.header.qdcount > 0 {
let mut name = Data::new();
name = message.questions[0].qname.clone();
match self.retrieve_from_cache(&mut name) {
Some(res) => {
return Some(res);
}
None => {
name = match message.questions[0].qname.tld().clone() {
Some(n) => {n}
None => {Data::new()}
};
match self.retrieve_from_cache(&mut name) {
Some(res) => {
return Some(res);
}
None => {
return None;
}
}
}
}
} else {
return None;
}
}
fn retrieve_from_cache(&mut self, name: &mut Data) -> Option<Vec<Resource>> {
let mut res: Vec<Resource> = vec![];
while self.cache.contains_key(&name.write()) == true {
let mut temp_res = self.cache[name.write()].clone();
let mut num: i64 = (temp_res.ttl as i64) * 1000000000;
if (num + temp_res.cache_timeout) < time::precise_time_ns() as i64 {
self.cache.remove(&name.write());
return Some(res);
} else {
res.push(temp_res.clone());
*name = temp_res.rdata.clone();
}
}
if res.len() > 0 {
return Some(res);
} else {
return None;
}
}
fn update_cache(&mut self, message: &mut Message) {
for i in range(0, message.header.ancount as uint) {
match self.cache.contains_key(&message.answers[i].rname.write()) {
true => {
continue;
},
false => {
message.answers[i].cache_timeout = time::precise_time_ns() as i64;
self.cache.insert(message.answers[i].rname.write(), message.answers[i].clone());
}
}
}
for i in range(0, message.header.arcount as uint) {
match self.cache.contains_key(&message.additional[i].rname.write()) {
true => {
continue;
},
false => {
/*
if message.header.nscount > 0 {
message.additional[i].rname = message.authority[0].r.clone();
}
*/
message.additional[i].cache_timeout = time::precise_time_ns() as i64;
self.cache.insert(message.additional[i].rname.write(), message.additional[i].clone());
}
}
}
}
fn query_origin_addr(&mut self, message: &mut Message) -> Option<SocketAddr> {
match self.ip_lookup.contains_key(&message.header.id) {
true => {
let addr = self.ip_lookup[message.header.id].clone();
self.ip_lookup.remove(&message.header.id);
Some(addr)
},
false => {
None
},
}
}
fn server_query_response(&mut self, message: &mut Message) -> Option<Message> {
match self.msg_lookup.contains_key(&message.header.id) {
true => {
let mut msg = self.msg_lookup[message.header.id].clone();
self.msg_lookup.remove(&message.header.id);
Some(msg)
},
false => {
None
}
}
}
fn is_server_query_server(&mut self, message: &mut Message) -> bool {
match self.msg_lookup.contains_key(&message.header.id) {
true => {
return true;
},
false => {
return false;
}
}
}
} |
pub mod db;
pub mod graphql;
pub mod member;
pub mod project;
pub mod response;
pub mod user;
|
#[derive(juniper::ScalarValue)]
enum ScalarValue {
Variant { first: i32, second: u64 },
}
fn main() {}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qvariantanimation.h
// dst-file: /src/core/qvariantanimation.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 super::qabstractanimation::*; // 773
use std::ops::Deref;
use super::qvariant::*; // 773
// use super::qvector::*; // 775
use super::qobjectdefs::*; // 773
use super::qeasingcurve::*; // 773
use super::qobject::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QVariantAnimation_Class_Size() -> c_int;
// proto: void QVariantAnimation::setDuration(int msecs);
fn C_ZN17QVariantAnimation11setDurationEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QVariantAnimation::setKeyValueAt(qreal step, const QVariant & value);
fn C_ZN17QVariantAnimation13setKeyValueAtEdRK8QVariant(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: *mut c_void);
// proto: QVariant QVariantAnimation::endValue();
fn C_ZNK17QVariantAnimation8endValueEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QVariant QVariantAnimation::keyValueAt(qreal step);
fn C_ZNK17QVariantAnimation10keyValueAtEd(qthis: u64 /* *mut c_void*/, arg0: c_double) -> *mut c_void;
// proto: void QVariantAnimation::~QVariantAnimation();
fn C_ZN17QVariantAnimationD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QVariant QVariantAnimation::currentValue();
fn C_ZNK17QVariantAnimation12currentValueEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QVariantAnimation::duration();
fn C_ZNK17QVariantAnimation8durationEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: KeyValues QVariantAnimation::keyValues();
fn C_ZNK17QVariantAnimation9keyValuesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QVariantAnimation::setStartValue(const QVariant & value);
fn C_ZN17QVariantAnimation13setStartValueERK8QVariant(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QVariant QVariantAnimation::startValue();
fn C_ZNK17QVariantAnimation10startValueEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const QMetaObject * QVariantAnimation::metaObject();
fn C_ZNK17QVariantAnimation10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QVariantAnimation::setEndValue(const QVariant & value);
fn C_ZN17QVariantAnimation11setEndValueERK8QVariant(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QEasingCurve QVariantAnimation::easingCurve();
fn C_ZNK17QVariantAnimation11easingCurveEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QVariantAnimation::QVariantAnimation(QObject * parent);
fn C_ZN17QVariantAnimationC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: void QVariantAnimation::setEasingCurve(const QEasingCurve & easing);
fn C_ZN17QVariantAnimation14setEasingCurveERK12QEasingCurve(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
fn QVariantAnimation_SlotProxy_connect__ZN17QVariantAnimation12valueChangedERK8QVariant(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QVariantAnimation)=1
#[derive(Default)]
pub struct QVariantAnimation {
qbase: QAbstractAnimation,
pub qclsinst: u64 /* *mut c_void*/,
pub _valueChanged: QVariantAnimation_valueChanged_signal,
}
impl /*struct*/ QVariantAnimation {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QVariantAnimation {
return QVariantAnimation{qbase: QAbstractAnimation::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QVariantAnimation {
type Target = QAbstractAnimation;
fn deref(&self) -> &QAbstractAnimation {
return & self.qbase;
}
}
impl AsRef<QAbstractAnimation> for QVariantAnimation {
fn as_ref(& self) -> & QAbstractAnimation {
return & self.qbase;
}
}
// proto: void QVariantAnimation::setDuration(int msecs);
impl /*struct*/ QVariantAnimation {
pub fn setDuration<RetType, T: QVariantAnimation_setDuration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setDuration(self);
// return 1;
}
}
pub trait QVariantAnimation_setDuration<RetType> {
fn setDuration(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: void QVariantAnimation::setDuration(int msecs);
impl<'a> /*trait*/ QVariantAnimation_setDuration<()> for (i32) {
fn setDuration(self , rsthis: & QVariantAnimation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QVariantAnimation11setDurationEi()};
let arg0 = self as c_int;
unsafe {C_ZN17QVariantAnimation11setDurationEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QVariantAnimation::setKeyValueAt(qreal step, const QVariant & value);
impl /*struct*/ QVariantAnimation {
pub fn setKeyValueAt<RetType, T: QVariantAnimation_setKeyValueAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setKeyValueAt(self);
// return 1;
}
}
pub trait QVariantAnimation_setKeyValueAt<RetType> {
fn setKeyValueAt(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: void QVariantAnimation::setKeyValueAt(qreal step, const QVariant & value);
impl<'a> /*trait*/ QVariantAnimation_setKeyValueAt<()> for (f64, &'a QVariant) {
fn setKeyValueAt(self , rsthis: & QVariantAnimation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QVariantAnimation13setKeyValueAtEdRK8QVariant()};
let arg0 = self.0 as c_double;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN17QVariantAnimation13setKeyValueAtEdRK8QVariant(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QVariant QVariantAnimation::endValue();
impl /*struct*/ QVariantAnimation {
pub fn endValue<RetType, T: QVariantAnimation_endValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.endValue(self);
// return 1;
}
}
pub trait QVariantAnimation_endValue<RetType> {
fn endValue(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: QVariant QVariantAnimation::endValue();
impl<'a> /*trait*/ QVariantAnimation_endValue<QVariant> for () {
fn endValue(self , rsthis: & QVariantAnimation) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation8endValueEv()};
let mut ret = unsafe {C_ZNK17QVariantAnimation8endValueEv(rsthis.qclsinst)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QVariant QVariantAnimation::keyValueAt(qreal step);
impl /*struct*/ QVariantAnimation {
pub fn keyValueAt<RetType, T: QVariantAnimation_keyValueAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.keyValueAt(self);
// return 1;
}
}
pub trait QVariantAnimation_keyValueAt<RetType> {
fn keyValueAt(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: QVariant QVariantAnimation::keyValueAt(qreal step);
impl<'a> /*trait*/ QVariantAnimation_keyValueAt<QVariant> for (f64) {
fn keyValueAt(self , rsthis: & QVariantAnimation) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation10keyValueAtEd()};
let arg0 = self as c_double;
let mut ret = unsafe {C_ZNK17QVariantAnimation10keyValueAtEd(rsthis.qclsinst, arg0)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QVariantAnimation::~QVariantAnimation();
impl /*struct*/ QVariantAnimation {
pub fn free<RetType, T: QVariantAnimation_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QVariantAnimation_free<RetType> {
fn free(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: void QVariantAnimation::~QVariantAnimation();
impl<'a> /*trait*/ QVariantAnimation_free<()> for () {
fn free(self , rsthis: & QVariantAnimation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QVariantAnimationD2Ev()};
unsafe {C_ZN17QVariantAnimationD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QVariant QVariantAnimation::currentValue();
impl /*struct*/ QVariantAnimation {
pub fn currentValue<RetType, T: QVariantAnimation_currentValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentValue(self);
// return 1;
}
}
pub trait QVariantAnimation_currentValue<RetType> {
fn currentValue(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: QVariant QVariantAnimation::currentValue();
impl<'a> /*trait*/ QVariantAnimation_currentValue<QVariant> for () {
fn currentValue(self , rsthis: & QVariantAnimation) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation12currentValueEv()};
let mut ret = unsafe {C_ZNK17QVariantAnimation12currentValueEv(rsthis.qclsinst)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QVariantAnimation::duration();
impl /*struct*/ QVariantAnimation {
pub fn duration<RetType, T: QVariantAnimation_duration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.duration(self);
// return 1;
}
}
pub trait QVariantAnimation_duration<RetType> {
fn duration(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: int QVariantAnimation::duration();
impl<'a> /*trait*/ QVariantAnimation_duration<i32> for () {
fn duration(self , rsthis: & QVariantAnimation) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation8durationEv()};
let mut ret = unsafe {C_ZNK17QVariantAnimation8durationEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: KeyValues QVariantAnimation::keyValues();
impl /*struct*/ QVariantAnimation {
pub fn keyValues<RetType, T: QVariantAnimation_keyValues<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.keyValues(self);
// return 1;
}
}
pub trait QVariantAnimation_keyValues<RetType> {
fn keyValues(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: KeyValues QVariantAnimation::keyValues();
impl<'a> /*trait*/ QVariantAnimation_keyValues<u64> for () {
fn keyValues(self , rsthis: & QVariantAnimation) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation9keyValuesEv()};
let mut ret = unsafe {C_ZNK17QVariantAnimation9keyValuesEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: void QVariantAnimation::setStartValue(const QVariant & value);
impl /*struct*/ QVariantAnimation {
pub fn setStartValue<RetType, T: QVariantAnimation_setStartValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setStartValue(self);
// return 1;
}
}
pub trait QVariantAnimation_setStartValue<RetType> {
fn setStartValue(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: void QVariantAnimation::setStartValue(const QVariant & value);
impl<'a> /*trait*/ QVariantAnimation_setStartValue<()> for (&'a QVariant) {
fn setStartValue(self , rsthis: & QVariantAnimation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QVariantAnimation13setStartValueERK8QVariant()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN17QVariantAnimation13setStartValueERK8QVariant(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QVariant QVariantAnimation::startValue();
impl /*struct*/ QVariantAnimation {
pub fn startValue<RetType, T: QVariantAnimation_startValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.startValue(self);
// return 1;
}
}
pub trait QVariantAnimation_startValue<RetType> {
fn startValue(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: QVariant QVariantAnimation::startValue();
impl<'a> /*trait*/ QVariantAnimation_startValue<QVariant> for () {
fn startValue(self , rsthis: & QVariantAnimation) -> QVariant {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation10startValueEv()};
let mut ret = unsafe {C_ZNK17QVariantAnimation10startValueEv(rsthis.qclsinst)};
let mut ret1 = QVariant::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QVariantAnimation::metaObject();
impl /*struct*/ QVariantAnimation {
pub fn metaObject<RetType, T: QVariantAnimation_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QVariantAnimation_metaObject<RetType> {
fn metaObject(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: const QMetaObject * QVariantAnimation::metaObject();
impl<'a> /*trait*/ QVariantAnimation_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QVariantAnimation) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation10metaObjectEv()};
let mut ret = unsafe {C_ZNK17QVariantAnimation10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QVariantAnimation::setEndValue(const QVariant & value);
impl /*struct*/ QVariantAnimation {
pub fn setEndValue<RetType, T: QVariantAnimation_setEndValue<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setEndValue(self);
// return 1;
}
}
pub trait QVariantAnimation_setEndValue<RetType> {
fn setEndValue(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: void QVariantAnimation::setEndValue(const QVariant & value);
impl<'a> /*trait*/ QVariantAnimation_setEndValue<()> for (&'a QVariant) {
fn setEndValue(self , rsthis: & QVariantAnimation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QVariantAnimation11setEndValueERK8QVariant()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN17QVariantAnimation11setEndValueERK8QVariant(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QEasingCurve QVariantAnimation::easingCurve();
impl /*struct*/ QVariantAnimation {
pub fn easingCurve<RetType, T: QVariantAnimation_easingCurve<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.easingCurve(self);
// return 1;
}
}
pub trait QVariantAnimation_easingCurve<RetType> {
fn easingCurve(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: QEasingCurve QVariantAnimation::easingCurve();
impl<'a> /*trait*/ QVariantAnimation_easingCurve<QEasingCurve> for () {
fn easingCurve(self , rsthis: & QVariantAnimation) -> QEasingCurve {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QVariantAnimation11easingCurveEv()};
let mut ret = unsafe {C_ZNK17QVariantAnimation11easingCurveEv(rsthis.qclsinst)};
let mut ret1 = QEasingCurve::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QVariantAnimation::QVariantAnimation(QObject * parent);
impl /*struct*/ QVariantAnimation {
pub fn new<T: QVariantAnimation_new>(value: T) -> QVariantAnimation {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QVariantAnimation_new {
fn new(self) -> QVariantAnimation;
}
// proto: void QVariantAnimation::QVariantAnimation(QObject * parent);
impl<'a> /*trait*/ QVariantAnimation_new for (Option<&'a QObject>) {
fn new(self) -> QVariantAnimation {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QVariantAnimationC2EP7QObject()};
let ctysz: c_int = unsafe{QVariantAnimation_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN17QVariantAnimationC2EP7QObject(arg0)};
let rsthis = QVariantAnimation{qbase: QAbstractAnimation::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QVariantAnimation::setEasingCurve(const QEasingCurve & easing);
impl /*struct*/ QVariantAnimation {
pub fn setEasingCurve<RetType, T: QVariantAnimation_setEasingCurve<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setEasingCurve(self);
// return 1;
}
}
pub trait QVariantAnimation_setEasingCurve<RetType> {
fn setEasingCurve(self , rsthis: & QVariantAnimation) -> RetType;
}
// proto: void QVariantAnimation::setEasingCurve(const QEasingCurve & easing);
impl<'a> /*trait*/ QVariantAnimation_setEasingCurve<()> for (&'a QEasingCurve) {
fn setEasingCurve(self , rsthis: & QVariantAnimation) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QVariantAnimation14setEasingCurveERK12QEasingCurve()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN17QVariantAnimation14setEasingCurveERK12QEasingCurve(rsthis.qclsinst, arg0)};
// return 1;
}
}
#[derive(Default)] // for QVariantAnimation_valueChanged
pub struct QVariantAnimation_valueChanged_signal{poi:u64}
impl /* struct */ QVariantAnimation {
pub fn valueChanged(&self) -> QVariantAnimation_valueChanged_signal {
return QVariantAnimation_valueChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QVariantAnimation_valueChanged_signal {
pub fn connect<T: QVariantAnimation_valueChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QVariantAnimation_valueChanged_signal_connect {
fn connect(self, sigthis: QVariantAnimation_valueChanged_signal);
}
// valueChanged(const class QVariant &)
extern fn QVariantAnimation_valueChanged_signal_connect_cb_0(rsfptr:fn(QVariant), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QVariant::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QVariantAnimation_valueChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(QVariant)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QVariant::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QVariantAnimation_valueChanged_signal_connect for fn(QVariant) {
fn connect(self, sigthis: QVariantAnimation_valueChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QVariantAnimation_valueChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QVariantAnimation_SlotProxy_connect__ZN17QVariantAnimation12valueChangedERK8QVariant(arg0, arg1, arg2)};
}
}
impl /* trait */ QVariantAnimation_valueChanged_signal_connect for Box<Fn(QVariant)> {
fn connect(self, sigthis: QVariantAnimation_valueChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QVariantAnimation_valueChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QVariantAnimation_SlotProxy_connect__ZN17QVariantAnimation12valueChangedERK8QVariant(arg0, arg1, arg2)};
}
}
// <= body block end
|
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "tags")]
pub struct Model {
#[sea_orm(primary_key)]
#[serde(skip_deserializing)]
pub id: i32,
#[sea_orm(unique)]
pub slug: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
impl Related<super::entry::Entity> for Entity {
fn to() -> RelationDef {
super::entry_tag::Relation::Entry.def()
}
fn via() -> Option<RelationDef> {
Some(super::entry_tag::Relation::Tag.def().rev())
}
}
|
mod lib;
use anyhow::{anyhow, Result};
use lib::{Eoip, TunnelConfig};
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const HELP_MESSAGE: &str = r#"eoip-rs
USAGE:
eoip-rs [OPTIONS]
OPTIONS:
-l, --local IP address of local tunnel endpoint
-r, --remote IP address of remote tunnel endpoint
-t, --tunid Tunnel ID
-I, --interface Name of the created tap interface
-k, --keepalive Interval of keepalive packet transmissions [seconds]
-W, --timeout How often the peer needs to send data to be
considered alive [seconds]
-h, --help Shows this message
-v, --version Shows version information
"#;
fn parse_args() -> Result<TunnelConfig> {
use lexopt::prelude::*;
let mut local = None;
let mut remote = None;
let mut tunnel_id = None;
let mut tap_name = None;
let mut keepalive_interval = None;
let mut recv_timeout = None;
let mut parser = lexopt::Parser::from_env();
while let Some(arg) = parser.next()? {
match arg {
Short('l') | Long("local") => local = Some(parser.value()?.parse()?),
Short('r') | Long("remote") => remote = Some(parser.value()?.parse()?),
Short('t') | Long("tunid") => tunnel_id = Some(parser.value()?.parse()?),
Short('I') | Long("interface") => tap_name = Some(parser.value()?.parse()?),
Short('k') | Long("keepalive") => keepalive_interval = Some(parser.value()?.parse()?),
Short('W') | Long("timeout") => recv_timeout = Some(parser.value()?.parse()?),
Short('h') | Long("help") => {
print!("{}", HELP_MESSAGE);
std::process::exit(0);
}
Short('v') | Long("version") => {
println!("eoip-rs {}", VERSION);
std::process::exit(0);
}
_ => return Err(arg.unexpected().into()),
}
}
Ok(TunnelConfig::new(
local,
remote.ok_or(anyhow!("Remote address is required"))?,
tunnel_id.ok_or(anyhow!("Tunnel ID is required"))?,
tap_name,
keepalive_interval,
recv_timeout,
))
}
fn main() -> Result<()> {
Eoip::new(parse_args()?)?.run();
}
|
use std::f64::consts;
use std::fmt;
use std::mem;
use std::slice;
use approx;
use num;
use angle;
use angle::{Angle, FromAngle, IntoAngle, Turns, Rad, Deg};
use channel::{PosNormalBoundedChannel, AngularChannel, ChannelFormatCast, ChannelCast,
PosNormalChannelScalar, AngularChannelScalar, ColorChannel};
use color::{Color, PolarColor, Invert, Lerp, Bounded, FromTuple};
use color;
use convert::{GetHue, FromColor, TryFromColor};
use rgb::Rgb;
pub struct HsiTag;
pub enum OutOfGamutMode {
Clip,
Preserve,
SimpleRescale,
SaturationRescale,
}
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
pub struct Hsi<T, A = Deg<T>> {
pub hue: AngularChannel<A>,
pub saturation: PosNormalBoundedChannel<T>,
pub intensity: PosNormalBoundedChannel<T>,
}
impl<T, A> Hsi<T, A>
where T: PosNormalChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T>
{
pub fn from_channels(hue: A, saturation: T, intensity: T) -> Self {
Hsi {
hue: AngularChannel::new(hue),
saturation: PosNormalBoundedChannel::new(saturation),
intensity: PosNormalBoundedChannel::new(intensity),
}
}
impl_color_color_cast_angular!(Hsi {hue, saturation, intensity},
chan_traits={PosNormalChannelScalar});
pub fn hue(&self) -> A {
self.hue.0.clone()
}
pub fn saturation(&self) -> T {
self.saturation.0.clone()
}
pub fn intensity(&self) -> T {
self.intensity.0.clone()
}
pub fn hue_mut(&mut self) -> &mut A {
&mut self.hue.0
}
pub fn saturation_mut(&mut self) -> &mut T {
&mut self.saturation.0
}
pub fn intensity_mut(&mut self) -> &mut T {
&mut self.intensity.0
}
pub fn set_hue(&mut self, val: A) {
self.hue.0 = val;
}
pub fn set_saturation(&mut self, val: T) {
self.saturation.0 = val;
}
pub fn set_intensity(&mut self, val: T) {
self.intensity.0 = val;
}
pub fn is_same_as_ehsi(&self) -> bool {
let deg_hue = Deg::from_angle(self.hue().clone()) % Deg(num::cast::<_, T>(120.0).unwrap());
let i_limit = num::cast::<_, T>(2.0 / 3.0).unwrap() -
(deg_hue - Deg(num::cast::<_, T>(60.0).unwrap())).scalar().abs() /
Deg(num::cast::<_, T>(180.0).unwrap()).scalar();
self.intensity() <= i_limit
}
}
impl<T, A> PolarColor for Hsi<T, A>
where T: PosNormalChannelScalar,
A: AngularChannelScalar
{
type Angular = A;
type Cartesian = T;
}
impl<T, A> Color for Hsi<T, A>
where T: PosNormalChannelScalar,
A: AngularChannelScalar
{
type Tag = HsiTag;
type ChannelsTuple = (A, T, T);
fn num_channels() -> u32 {
3
}
fn to_tuple(self) -> Self::ChannelsTuple {
(self.hue.0, self.saturation.0, self.intensity.0)
}
}
impl<T, A> FromTuple for Hsi<T, A>
where T: PosNormalChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T>
{
fn from_tuple(values: Self::ChannelsTuple) -> Self {
Hsi::from_channels(values.0, values.1, values.2)
}
}
impl<T, A> Invert for Hsi<T, A>
where T: PosNormalChannelScalar,
A: AngularChannelScalar
{
impl_color_invert!(Hsi {hue, saturation, intensity});
}
impl<T, A> Lerp for Hsi<T, A>
where T: PosNormalChannelScalar + color::Lerp,
A: AngularChannelScalar + color::Lerp
{
type Position = A::Position;
impl_color_lerp_angular!(Hsi<T> {hue, saturation, intensity});
}
impl<T, A> Bounded for Hsi<T, A>
where T: PosNormalChannelScalar,
A: AngularChannelScalar
{
impl_color_bounded!(Hsi {hue, saturation, intensity});
}
impl<T, A> color::Flatten for Hsi<T, A>
where T: PosNormalChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T> + FromAngle<Turns<T>>
{
type ScalarFormat = T;
impl_color_as_slice!(T);
impl_color_from_slice_angular!(Hsi<T, A> {hue:AngularChannel - 0,
saturation:PosNormalBoundedChannel - 1, intensity:PosNormalBoundedChannel - 2});
}
impl<T, A> approx::ApproxEq for Hsi<T, A>
where T: PosNormalChannelScalar + approx::ApproxEq<Epsilon = A::Epsilon>,
A: AngularChannelScalar + approx::ApproxEq,
A::Epsilon: Clone + num::Float
{
impl_approx_eq!({hue, saturation, intensity});
}
impl<T, A> Default for Hsi<T, A>
where T: PosNormalChannelScalar + num::Zero,
A: AngularChannelScalar + num::Zero
{
impl_color_default!(Hsi {hue: AngularChannel,
saturation: PosNormalBoundedChannel, intensity: PosNormalBoundedChannel});
}
impl<T, A> fmt::Display for Hsi<T, A>
where T: PosNormalChannelScalar + fmt::Display,
A: AngularChannelScalar + fmt::Display
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Hsi({}, {}, {})", self.hue, self.saturation, self.intensity)
}
}
impl<T, A> GetHue for Hsi<T, A>
where T: PosNormalChannelScalar,
A: AngularChannelScalar
{
impl_color_get_hue_angular!(Hsi);
}
impl<T, A> FromColor<Rgb<T>> for Hsi<T, A>
where T: PosNormalChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T> + FromAngle<Rad<T>> + fmt::Display
{
fn from_color(from: &Rgb<T>) -> Self {
let coords = from.get_chromaticity_coordinates();
let hue_unnormal: A = coords.get_hue::<A>();
let hue = Angle::normalize(hue_unnormal);
let min = from.red().min(from.green().min(from.blue()));
let intensity = num::cast::<_, T>(1.0 / 3.0).unwrap() *
(from.red() + from.green() + from.blue());
let saturation: T = if intensity != num::cast::<_, T>(0.0).unwrap() {
num::cast::<_, T>(1.0).unwrap() - min / intensity
} else {
num::cast(0.0).unwrap()
};
Hsi::from_channels(hue, saturation, intensity)
}
}
impl<T, A> TryFromColor<Hsi<T, A>> for Rgb<T>
where T: PosNormalChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T>
{
fn try_from_color(from: &Hsi<T, A>) -> Option<Self> {
let c = from.to_rgb(OutOfGamutMode::Preserve);
let max = PosNormalBoundedChannel::<T>::max_bound();
if c.red() > max || c.green() > max || c.blue() > max {
None
} else {
Some(c)
}
}
}
impl<T, A> Hsi<T, A>
where T: PosNormalChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T> + IntoAngle<Rad<T>, OutputScalar = T>
{
pub fn to_rgb(&self, mode: OutOfGamutMode) -> Rgb<T> {
let pi_over_3: T = num::cast(consts::PI / 3.0).unwrap();
let hue_frac = Rad::from_angle(self.hue()) %
Rad(num::cast::<_, T>(2.0).unwrap() * pi_over_3);
let one = num::cast::<_, T>(1.0).unwrap();
let mut c1 = self.intensity() * (one - self.saturation());
let mut c2 =
self.intensity() *
(one + (self.saturation() * hue_frac.cos()) / (Angle::cos(Rad(pi_over_3) - hue_frac)));
let mut c3 = num::cast::<_, T>(3.0).unwrap() * self.intensity() - (c1 + c2);
to_rgb_out_of_gamut(self, &hue_frac, mode, &mut c1, &mut c2, &mut c3);
let turns_hue = Turns::from_angle(self.hue());
if turns_hue < Turns(num::cast(1.0 / 3.0).unwrap()) {
Rgb::from_channels(c2, c3, c1)
} else if turns_hue < Turns(num::cast(2.0 / 3.0).unwrap()) {
Rgb::from_channels(c1, c2, c3)
} else {
Rgb::from_channels(c3, c1, c2)
}
}
}
fn to_rgb_out_of_gamut<T, A>(color: &Hsi<T, A>,
hue_frac: &Rad<T>,
mode: OutOfGamutMode,
c1: &mut T,
c2: &mut T,
c3: &mut T)
where T: PosNormalChannelScalar + num::Float,
A: AngularChannelScalar + Angle<Scalar = T>
{
let one = num::cast(1.0).unwrap();
match mode {
// Do nothing.
OutOfGamutMode::Preserve => {}
OutOfGamutMode::Clip => {
*c1 = c1.min(one);
*c2 = c2.min(one);
*c3 = c3.min(one);
}
OutOfGamutMode::SimpleRescale => {
let max = c1.max(c2.max(*c3));
if max > one {
*c1 = *c1 / max;
*c2 = *c2 / max;
*c3 = *c3 / max;
}
}
// Algorithm adapted from:
// K. Yoshinari, Y. Hoshi and A. Taguchi, "Color image enhancement in HSI color space
// without gamut problem," 2014 6th International Symposium on Communications,
// Control and Signal Processing (ISCCSP), Athens, 2014, pp. 578-581.
OutOfGamutMode::SaturationRescale => {
let pi_over_3 = num::cast(consts::PI / 3.0).unwrap();
let cos_pi3_sub_hue = Rad::cos(Rad(pi_over_3) - *hue_frac);
let cos_hue = hue_frac.cos();
if *hue_frac < Rad(pi_over_3) {
if *c2 > one {
let rescaled_sat = ((one - color.intensity()) * cos_pi3_sub_hue) /
(color.intensity() * cos_hue);
*c1 = color.intensity() * (one - rescaled_sat);
*c2 = one;
*c3 = color.intensity() *
(one + (rescaled_sat * (cos_pi3_sub_hue - cos_hue) / cos_pi3_sub_hue));
}
} else {
if *c3 > one {
let rescaled_sat = ((one - color.intensity()) * cos_pi3_sub_hue) /
(color.intensity() * (cos_pi3_sub_hue - cos_hue));
*c1 = color.intensity() * (one - rescaled_sat);
*c2 = color.intensity() * (one + (rescaled_sat * cos_hue) / (cos_pi3_sub_hue));
*c3 = one;
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use test;
use convert::*;
use angle::*;
use rgb::Rgb;
use color::*;
#[test]
fn test_construct() {
let c1 = Hsi::from_channels(Deg(225.0), 0.8, 0.284);
assert_eq!(c1.hue(), Deg(225.0));
assert_eq!(c1.saturation(), 0.8);
assert_eq!(c1.intensity(), 0.284);
assert_eq!(c1.to_tuple(), (Deg(225.0), 0.8, 0.284));
assert_eq!(Hsi::from_tuple(c1.to_tuple()), c1);
let c2 = Hsi::from_channels(Turns(0.33), 0.62, 0.98);
assert_eq!(c2.hue(), Turns(0.33));
assert_eq!(c2.saturation(), 0.62);
assert_eq!(c2.intensity(), 0.98);
assert_eq!(c2.as_slice(), &[0.33, 0.62, 0.98]);
}
#[test]
fn test_invert() {
let c1 = Hsi::from_channels(Deg(222.0), 0.65, 0.23);
assert_relative_eq!(c1.clone().invert().invert(), c1);
assert_relative_eq!(c1.invert(), Hsi::from_channels(Deg(42.0), 0.35, 0.77));
let c2 = Hsi::from_channels(Turns(0.40), 0.25, 0.8);
assert_relative_eq!(c2.clone().invert().invert(), c2);
assert_relative_eq!(c2.invert(), Hsi::from_channels(Turns(0.90), 0.75, 0.2));
}
#[test]
fn test_lerp() {
let c1 = Hsi::from_channels(Deg(80.0), 0.20, 0.60);
let c2 = Hsi::from_channels(Deg(120.0), 0.80, 0.90);
assert_relative_eq!(c1.lerp(&c2, 0.0), c1);
assert_relative_eq!(c1.lerp(&c2, 1.0), c2);
assert_relative_eq!(c1.lerp(&c2, 0.5), Hsi::from_channels(Deg(100.0), 0.50, 0.75));
assert_relative_eq!(c1.lerp(&c2, 0.25), Hsi::from_channels(Deg(90.0), 0.35, 0.675));
}
#[test]
fn test_from_rgb() {
let test_data = test::build_hs_test_data();
for item in test_data {
let hsi = Hsi::from_color(&item.rgb);
assert_relative_eq!(hsi, item.hsi, epsilon=1e-3);
}
}
#[test]
fn test_to_rgb() {
let test_data = test::build_hs_test_data();
for item in test_data {
let rgb = item.hsi.to_rgb(OutOfGamutMode::Preserve);
assert_relative_eq!(rgb, item.rgb, epsilon=2e-3);
let hsi = Hsi::from_color(&rgb);
assert_relative_eq!(hsi, item.hsi, epsilon=2e-3);
}
let c1 = Hsi::from_channels(Deg(150.0), 1.0, 1.0);
let rgb1_1 = c1.to_rgb(OutOfGamutMode::Preserve);
let rgb1_2 = c1.to_rgb(OutOfGamutMode::Clip);
let rgb1_3 = c1.to_rgb(OutOfGamutMode::SimpleRescale);
let rgb1_4 = c1.to_rgb(OutOfGamutMode::SaturationRescale);
assert_relative_eq!(rgb1_1, Rgb::from_channels(0.0, 2.0, 1.0), epsilon=1e-6);
assert_relative_eq!(rgb1_2, Rgb::from_channels(0.0, 1.0, 1.0), epsilon=1e-6);
assert_relative_eq!(rgb1_3, Rgb::from_channels(0.0, 1.0, 0.5), epsilon=1e-6);
assert_relative_eq!(rgb1_4, Rgb::from_channels(1.0, 1.0, 1.0), epsilon=1e-6);
let c2 = Hsi::from_channels(Deg(180.0), 1.0, 0.7);
let rgb2_1 = c2.to_rgb(OutOfGamutMode::Preserve);
let rgb2_2 = c2.to_rgb(OutOfGamutMode::Clip);
let rgb2_3 = c2.to_rgb(OutOfGamutMode::SimpleRescale);
let rgb2_4 = c2.to_rgb(OutOfGamutMode::SaturationRescale);
assert_relative_eq!(rgb2_1, Rgb::from_channels(0.0, 1.05, 1.05), epsilon=1e-6);
assert_relative_eq!(rgb2_2, Rgb::from_channels(0.0, 1.00, 1.00), epsilon=1e-6);
assert_relative_eq!(rgb2_3, Rgb::from_channels(0.0, 1.00, 1.00), epsilon=1e-6);
assert_relative_eq!(rgb2_4, Rgb::from_channels(0.1, 1.00, 1.00), epsilon=1e-6);
let c3 = Hsi::from_channels(Deg(240.0), 1.0, 0.3);
let rgb3_1 = c3.to_rgb(OutOfGamutMode::Preserve);
let rgb3_2 = c3.to_rgb(OutOfGamutMode::Clip);
let rgb3_3 = c3.to_rgb(OutOfGamutMode::SimpleRescale);
let rgb3_4 = c3.to_rgb(OutOfGamutMode::SaturationRescale);
assert_relative_eq!(rgb3_1, Rgb::from_channels(0.0, 0.0, 0.9), epsilon=1e-6);
assert_relative_eq!(rgb3_2, Rgb::from_channels(0.0, 0.0, 0.9), epsilon=1e-6);
assert_relative_eq!(rgb3_3, Rgb::from_channels(0.0, 0.0, 0.9), epsilon=1e-6);
assert_relative_eq!(rgb3_4, Rgb::from_channels(0.0, 0.0, 0.9), epsilon=1e-6);
}
#[test]
fn test_color_cast() {
let c1 = Hsi::from_channels(Deg(120.0), 0.53, 0.94);
assert_relative_eq!(c1.color_cast(),
Hsi::from_channels(Turns(0.33333333333f32), 0.53f32, 0.94), epsilon=1e-6);
assert_relative_eq!(c1.color_cast::<f32, Rad<f32>>().color_cast(), c1, epsilon=1e-6);
assert_relative_eq!(c1.color_cast(), c1, epsilon=1e-6);
}
}
|
extern crate rand;
extern crate sfml;
mod fireworks;
mod snow;
use sfml::graphics::*;
use sfml::system::*;
use sfml::window::*;
pub static WINDOW_WIDTH: u32 = 800;
pub static WINDOW_HEIGHT: u32 = 600;
fn load_font() -> SfBox<Font> {
let font = Font::from_file("res/LiberationMono-Regular.ttf");
if font.is_none() {
println!("Error: Could not find font in \"../res/\" folder.");
}
font.unwrap()
}
fn rainbow_text(text: &mut Text, t: f32) {
let r = f32::sin(t + 1.5) * 127. + 127.;
let g = f32::sin(t - 0.5) * 127. + 127.;
let b = f32::sin(t + 3.5) * 127. + 127.;
text.set_fill_color(Color::rgb(r as u8, g as u8, b as u8));
}
fn create_text<'a>(string: &str, font: &'a Font) -> Text<'a> {
let mut text = Text::new(string, font, 56);
// Set text to center of screen
let bounds = text.local_bounds();
text.set_position((WINDOW_WIDTH as f32 / 2., WINDOW_HEIGHT as f32 / 2.));
text.move_((-bounds.width / 2., -bounds.height / 2.));
// Set appearance
text.set_fill_color(Color::rgb(0x23, 0x4a, 0x1e));
text.set_outline_color(Color::WHITE);
text.set_outline_thickness(1.);
text
}
pub fn run_app() {
// Create the window of the application
let mut window = RenderWindow::new(
VideoMode::new(WINDOW_WIDTH, WINDOW_HEIGHT, 32),
"Happy New Years!",
Style::CLOSE,
&ContextSettings::default(),
);
window.set_framerate_limit(120);
let font = load_font();
let mut text = create_text("Happy New Years 2019", &*font);
let mut snow_ctx = snow::SnowCtx::new();
let mut fireworks_ctx = fireworks::FireworksCtx::new();
let mut clock = Clock::start();
let mut t: f32 = 0.;
loop {
let delta = clock.restart().as_milliseconds() as f32 / 1000.;
t += delta;
// Handle events
while let Some(event) = window.poll_event() {
if let Event::Closed = event {
return;
}
}
rainbow_text(&mut text, t as f32);
// Update objects
snow::update_snow(&mut snow_ctx, delta);
fireworks::update_fireworks(&mut fireworks_ctx, delta);
// Clear the window
window.clear(Color::rgb(0, 10, 20));
// Draw objects
snow::draw_snow(&mut snow_ctx, &mut window);
fireworks::draw_fireworks(&mut fireworks_ctx, &mut window);
// Draw text
window.draw(&text);
// Display things on screen
window.display()
}
}
|
use cgmath::{EuclideanSpace, InnerSpace, MetricSpace, Point3, Vector3};
use crate::{config, P3, V3};
use std::f64::EPSILON;
use std::ops::Neg;
#[derive(Copy, Clone, Debug)]
pub struct Positioned<T> {
pos: P3,
value: T,
}
impl<T: Default> Default for Positioned<T> {
fn default() -> Self {
Self {
pos: Point3::origin(),
value: T::default(),
}
}
}
impl<T> From<config::Positioned<T>> for Positioned<T> {
fn from(p: config::Positioned<T>) -> Self {
Self {
pos: p.pos.into(),
value: p.value,
}
}
}
impl<T> From<Positioned<T>> for config::Positioned<T> {
fn from(p: Positioned<T>) -> Self {
Self {
pos: p.pos.into(),
value: p.value,
}
}
}
impl<T> Positioned<T> {
pub fn map<U, F: FnOnce(T) -> U>(self, mapper: F) -> Positioned<U> {
Positioned {
pos: self.pos,
value: mapper(self.value),
}
}
pub fn map_copy<U, F: FnOnce(&T) -> U>(&self, mapper: F) -> Positioned<U> {
Positioned {
pos: self.pos,
value: mapper(&self.value),
}
}
}
impl Positioned<SDF> {
pub fn sdf(&self, pos: P3) -> f64 {
let pos = pos - self.pos;
self.value.sdf(from_vec3(pos))
}
pub fn sdf_d(&self, pos: P3) -> V3 {
let pos = pos - self.pos;
self.value.sdf_d(from_vec3(pos))
}
}
fn from_vec3<T>(vec: Vector3<T>) -> Point3<T> {
Point3::new(vec.x, vec.y, vec.z)
}
#[derive(Debug)]
pub enum SDF {
Sphere {
radius: f64,
},
Plane {
normal: V3,
},
Box {
size: V3,
},
Rounding {
sdf: Box<SDF>,
amount: f64,
},
Union {
left: Box<Positioned<SDF>>,
right: Box<Positioned<SDF>>,
smooth: f64,
},
Intersection {
left: Box<Positioned<SDF>>,
right: Box<Positioned<SDF>>,
smooth: f64,
},
}
impl From<config::SDF> for SDF {
fn from(c: config::SDF) -> Self {
match c {
config::SDF::Sphere { radius } => Self::Sphere { radius },
config::SDF::Plane { normal } => Self::Plane {
normal: normal.into(),
},
config::SDF::Box { size } => Self::Box { size: size.into() },
config::SDF::Rounding { sdf, amount } => Self::Rounding {
sdf: Box::new((*sdf).into()),
amount,
},
config::SDF::Union {
left,
right,
smooth,
} => Self::Union {
left: Box::new(Positioned::from(left).map(|s| (*s).into())),
right: Box::new(Positioned::from(right).map(|s| (*s).into())),
smooth,
},
config::SDF::Intersection {
left,
right,
smooth,
} => Self::Intersection {
left: Box::new(Positioned::from(left).map(|s| (*s).into())),
right: Box::new(Positioned::from(right).map(|s| (*s).into())),
smooth,
},
}
}
}
impl From<SDF> for config::SDF {
fn from(s: SDF) -> Self {
match s {
SDF::Sphere { radius } => config::SDF::Sphere { radius },
SDF::Plane { normal } => config::SDF::Plane {
normal: normal.into(),
},
SDF::Box { size } => config::SDF::Box { size: size.into() },
SDF::Rounding { sdf, amount } => config::SDF::Rounding {
sdf: Box::new((*sdf).into()),
amount,
},
SDF::Union {
left,
right,
smooth,
} => config::SDF::Union {
left: config::Positioned::from(left.map(|v| Box::new(v.into()))),
right: config::Positioned::from(right.map(|v| Box::new(v.into()))),
smooth,
},
SDF::Intersection {
left,
right,
smooth,
} => config::SDF::Intersection {
left: config::Positioned::from(left.map(|v| Box::new(v.into()))),
right: config::Positioned::from(right.map(|v| Box::new(v.into()))),
smooth,
},
}
}
}
impl SDF {
pub fn sdf(&self, pos: P3) -> f64 {
match self {
Self::Sphere { radius } => pos.to_vec().magnitude() - radius,
Self::Plane { normal } => pos.dot(*normal),
Self::Box { size } => {
let q: P3 = pos.map(f64::abs) - size;
q.map(|v| v.max(0.0)).to_vec().magnitude() + q.y.max(q.z).max(q.x).min(0.0)
}
Self::Rounding { sdf, amount } => sdf.sdf(pos) - amount,
Self::Union {
left,
right,
smooth,
} => {
let d1 = left.sdf(pos);
let d2 = right.sdf(pos);
let h = (0.5 + 0.5 * (d2 - d1) / smooth).max(0.0).min(1.0);
lerp(d2, d1, h) - smooth * h * (1.0 - h)
}
Self::Intersection {
left,
right,
smooth,
} => {
let d1 = left.sdf(pos);
let d2 = right.sdf(pos);
let h = (0.5 - 0.5 * (d2 - d1) / smooth).max(0.0).min(1.0);
lerp(d2, d1, h) + smooth * h * (1.0 - h)
}
}
}
pub fn sdf_d(&self, pos: P3) -> V3 {
match self {
Self::Sphere { .. } => pos.to_vec().normalize().neg(),
Self::Plane { normal } => *normal,
_ => V3::new(
self.sdf(pos + V3::unit_x() * EPSILON) - self.sdf(pos - V3::unit_x() * EPSILON),
self.sdf(pos + V3::unit_y() * EPSILON) - self.sdf(pos - V3::unit_y() * EPSILON),
self.sdf(pos + V3::unit_z() * EPSILON) - self.sdf(pos - V3::unit_z() * EPSILON),
)
.normalize(),
}
}
}
fn lerp(a: f64, b: f64, x: f64) -> f64 {
(1.0 - x) * a + x * b
}
|
use std::fs::File;
use std::io::{self, Read, Write};
pub fn update_values_in_files(word_to_replace: &str, new_word: &str, path: &String) -> Result<(), io::Error> {
let mut src = File::open(&path)?;
let mut data = String::new();
src.read_to_string(&mut data)?;
drop(src); // Close the file early
let new_data = data.replace(word_to_replace, new_word);
let mut dst = File::create(&path)?;
dst.write(new_data.as_bytes())?;
Ok(())
} |
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtCore/qobjectdefs.h
// dst-file: /src/core/qobjectdefs.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::qobjectdefs::QGenericArgument; // 773
use super::qbytearray::*; // 773
use super::qobject::*; // 773
use super::qmetaobject::*; // 773
// use super::qobjectdefs::QGenericReturnArgument; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QMetaObject__Connection_Class_Size() -> c_int;
// proto: void QMetaObject::Connection::Connection();
fn C_ZN11QMetaObject10ConnectionC2Ev() -> u64;
// proto: void QMetaObject::Connection::~Connection();
fn C_ZN11QMetaObject10ConnectionD2Ev(qthis: u64 /* *mut c_void*/);
fn QGenericReturnArgument_Class_Size() -> c_int;
// proto: void QGenericReturnArgument::QGenericReturnArgument(const char * aName, void * aData);
fn C_ZN22QGenericReturnArgumentC2EPKcPv(arg0: *mut c_char, arg1: *mut c_void) -> u64;
fn QMetaObject_Class_Size() -> c_int;
// proto: static QByteArray QMetaObject::normalizedSignature(const char * method);
fn C_ZN11QMetaObject19normalizedSignatureEPKc(arg0: *mut c_char) -> *mut c_void;
// proto: static bool QMetaObject::disconnectOne(const QObject * sender, int signal_index, const QObject * receiver, int method_index);
fn C_ZN11QMetaObject13disconnectOneEPK7QObjectiS2_i(arg0: *mut c_void, arg1: c_int, arg2: *mut c_void, arg3: c_int) -> c_char;
// proto: int QMetaObject::indexOfSlot(const char * slot);
fn C_ZNK11QMetaObject11indexOfSlotEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_int;
// proto: int QMetaObject::indexOfConstructor(const char * constructor);
fn C_ZNK11QMetaObject18indexOfConstructorEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_int;
// proto: QMetaEnum QMetaObject::enumerator(int index);
fn C_ZNK11QMetaObject10enumeratorEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: int QMetaObject::indexOfMethod(const char * method);
fn C_ZNK11QMetaObject13indexOfMethodEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_int;
// proto: QMetaMethod QMetaObject::constructor(int index);
fn C_ZNK11QMetaObject11constructorEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: static bool QMetaObject::checkConnectArgs(const char * signal, const char * method);
fn C_ZN11QMetaObject16checkConnectArgsEPKcS1_(arg0: *mut c_char, arg1: *mut c_char) -> c_char;
// proto: int QMetaObject::enumeratorOffset();
fn C_ZNK11QMetaObject16enumeratorOffsetEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QMetaProperty QMetaObject::property(int index);
fn C_ZNK11QMetaObject8propertyEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: static void QMetaObject::connectSlotsByName(QObject * o);
fn C_ZN11QMetaObject18connectSlotsByNameEP7QObject(arg0: *mut c_void);
// proto: QMetaProperty QMetaObject::userProperty();
fn C_ZNK11QMetaObject12userPropertyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QMetaObject::indexOfProperty(const char * name);
fn C_ZNK11QMetaObject15indexOfPropertyEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_int;
// proto: int QMetaObject::indexOfClassInfo(const char * name);
fn C_ZNK11QMetaObject16indexOfClassInfoEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_int;
// proto: static void QMetaObject::activate(QObject * sender, const QMetaObject * , int local_signal_index, void ** argv);
fn C_ZN11QMetaObject8activateEP7QObjectPKS_iPPv(arg0: *mut c_void, arg1: *mut c_void, arg2: c_int, arg3: *mut c_void);
// proto: const QObject * QMetaObject::cast(const QObject * obj);
fn C_ZNK11QMetaObject4castEPK7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QMetaMethod QMetaObject::method(int index);
fn C_ZNK11QMetaObject6methodEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: const QMetaObject * QMetaObject::superClass();
fn C_ZNK11QMetaObject10superClassEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QObject * QMetaObject::cast(QObject * obj);
fn C_ZNK11QMetaObject4castEP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: static void QMetaObject::activate(QObject * sender, int signal_offset, int local_signal_index, void ** argv);
fn C_ZN11QMetaObject8activateEP7QObjectiiPPv(arg0: *mut c_void, arg1: c_int, arg2: c_int, arg3: *mut c_void);
// proto: int QMetaObject::propertyCount();
fn C_ZNK11QMetaObject13propertyCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QMetaClassInfo QMetaObject::classInfo(int index);
fn C_ZNK11QMetaObject9classInfoEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: static bool QMetaObject::checkConnectArgs(const QMetaMethod & signal, const QMetaMethod & method);
fn C_ZN11QMetaObject16checkConnectArgsERK11QMetaMethodS2_(arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: const char * QMetaObject::className();
fn C_ZNK11QMetaObject9classNameEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: int QMetaObject::indexOfSignal(const char * signal);
fn C_ZNK11QMetaObject13indexOfSignalEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_int;
// proto: static QByteArray QMetaObject::normalizedType(const char * type);
fn C_ZN11QMetaObject14normalizedTypeEPKc(arg0: *mut c_char) -> *mut c_void;
// proto: int QMetaObject::constructorCount();
fn C_ZNK11QMetaObject16constructorCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMetaObject::propertyOffset();
fn C_ZNK11QMetaObject14propertyOffsetEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: static bool QMetaObject::disconnect(const QObject * sender, int signal_index, const QObject * receiver, int method_index);
fn C_ZN11QMetaObject10disconnectEPK7QObjectiS2_i(arg0: *mut c_void, arg1: c_int, arg2: *mut c_void, arg3: c_int) -> c_char;
// proto: static void QMetaObject::activate(QObject * sender, int signal_index, void ** argv);
fn C_ZN11QMetaObject8activateEP7QObjectiPPv(arg0: *mut c_void, arg1: c_int, arg2: *mut c_void);
// proto: int QMetaObject::enumeratorCount();
fn C_ZNK11QMetaObject15enumeratorCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMetaObject::classInfoOffset();
fn C_ZNK11QMetaObject15classInfoOffsetEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMetaObject::methodOffset();
fn C_ZNK11QMetaObject12methodOffsetEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMetaObject::indexOfEnumerator(const char * name);
fn C_ZNK11QMetaObject17indexOfEnumeratorEPKc(qthis: u64 /* *mut c_void*/, arg0: *mut c_char) -> c_int;
// proto: int QMetaObject::methodCount();
fn C_ZNK11QMetaObject11methodCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QMetaObject::classInfoCount();
fn C_ZNK11QMetaObject14classInfoCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
fn QGenericArgument_Class_Size() -> c_int;
// proto: const char * QGenericArgument::name();
fn C_ZNK16QGenericArgument4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_char;
// proto: void * QGenericArgument::data();
fn C_ZNK16QGenericArgument4dataEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGenericArgument::QGenericArgument(const char * aName, const void * aData);
fn C_ZN16QGenericArgumentC2EPKcPKv(arg0: *mut c_char, arg1: *mut c_void) -> u64;
} // <= ext block end
// body block begin =>
// class sizeof(QMetaObject__Connection)=8
#[derive(Default)]
pub struct QMetaObject__Connection {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QGenericReturnArgument)=16
#[derive(Default)]
pub struct QGenericReturnArgument {
qbase: QGenericArgument,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QMetaObject)=48
#[derive(Default)]
pub struct QMetaObject {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QGenericArgument)=16
#[derive(Default)]
pub struct QGenericArgument {
// qbase: None,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QMetaObject__Connection {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMetaObject__Connection {
return QMetaObject__Connection{qclsinst: qthis, ..Default::default()};
}
}
// proto: void QMetaObject::Connection::Connection();
impl /*struct*/ QMetaObject__Connection {
pub fn new<T: QMetaObject__Connection_new>(value: T) -> QMetaObject__Connection {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QMetaObject__Connection_new {
fn new(self) -> QMetaObject__Connection;
}
// proto: void QMetaObject::Connection::Connection();
impl<'a> /*trait*/ QMetaObject__Connection_new for () {
fn new(self) -> QMetaObject__Connection {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QMetaObject10ConnectionC2Ev()};
let ctysz: c_int = unsafe{QMetaObject__Connection_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let qthis: u64 = unsafe {C_ZN11QMetaObject10ConnectionC2Ev()};
let rsthis = QMetaObject__Connection{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QMetaObject::Connection::~Connection();
impl /*struct*/ QMetaObject__Connection {
pub fn free<RetType, T: QMetaObject__Connection_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QMetaObject__Connection_free<RetType> {
fn free(self , rsthis: & QMetaObject__Connection) -> RetType;
}
// proto: void QMetaObject::Connection::~Connection();
impl<'a> /*trait*/ QMetaObject__Connection_free<()> for () {
fn free(self , rsthis: & QMetaObject__Connection) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN11QMetaObject10ConnectionD2Ev()};
unsafe {C_ZN11QMetaObject10ConnectionD2Ev(rsthis.qclsinst)};
// return 1;
}
}
impl /*struct*/ QGenericReturnArgument {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGenericReturnArgument {
return QGenericReturnArgument{qbase: QGenericArgument::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGenericReturnArgument {
type Target = QGenericArgument;
fn deref(&self) -> &QGenericArgument {
return & self.qbase;
}
}
impl AsRef<QGenericArgument> for QGenericReturnArgument {
fn as_ref(& self) -> & QGenericArgument {
return & self.qbase;
}
}
// proto: void QGenericReturnArgument::QGenericReturnArgument(const char * aName, void * aData);
impl /*struct*/ QGenericReturnArgument {
pub fn new<T: QGenericReturnArgument_new>(value: T) -> QGenericReturnArgument {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGenericReturnArgument_new {
fn new(self) -> QGenericReturnArgument;
}
// proto: void QGenericReturnArgument::QGenericReturnArgument(const char * aName, void * aData);
impl<'a> /*trait*/ QGenericReturnArgument_new for (Option<&'a String>, Option<*mut c_void>) {
fn new(self) -> QGenericReturnArgument {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN22QGenericReturnArgumentC2EPKcPv()};
let ctysz: c_int = unsafe{QGenericReturnArgument_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.0.is_none() {0 as *const u8} else {self.0.unwrap().as_ptr()}) as *mut c_char;
let arg1 = (if self.1.is_none() {0 as *mut c_void} else {self.1.unwrap()}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN22QGenericReturnArgumentC2EPKcPv(arg0, arg1)};
let rsthis = QGenericReturnArgument{qbase: QGenericArgument::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
impl /*struct*/ QMetaObject {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QMetaObject {
return QMetaObject{qclsinst: qthis, ..Default::default()};
}
}
// proto: static QByteArray QMetaObject::normalizedSignature(const char * method);
impl /*struct*/ QMetaObject {
pub fn normalizedSignature_s<RetType, T: QMetaObject_normalizedSignature_s<RetType>>( overload_args: T) -> RetType {
return overload_args.normalizedSignature_s();
// return 1;
}
}
pub trait QMetaObject_normalizedSignature_s<RetType> {
fn normalizedSignature_s(self ) -> RetType;
}
// proto: static QByteArray QMetaObject::normalizedSignature(const char * method);
impl<'a> /*trait*/ QMetaObject_normalizedSignature_s<QByteArray> for (&'a String) {
fn normalizedSignature_s(self ) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject19normalizedSignatureEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZN11QMetaObject19normalizedSignatureEPKc(arg0)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static bool QMetaObject::disconnectOne(const QObject * sender, int signal_index, const QObject * receiver, int method_index);
impl /*struct*/ QMetaObject {
pub fn disconnectOne_s<RetType, T: QMetaObject_disconnectOne_s<RetType>>( overload_args: T) -> RetType {
return overload_args.disconnectOne_s();
// return 1;
}
}
pub trait QMetaObject_disconnectOne_s<RetType> {
fn disconnectOne_s(self ) -> RetType;
}
// proto: static bool QMetaObject::disconnectOne(const QObject * sender, int signal_index, const QObject * receiver, int method_index);
impl<'a> /*trait*/ QMetaObject_disconnectOne_s<i8> for (&'a QObject, i32, &'a QObject, i32) {
fn disconnectOne_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject13disconnectOneEPK7QObjectiS2_i()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
let arg3 = self.3 as c_int;
let mut ret = unsafe {C_ZN11QMetaObject13disconnectOneEPK7QObjectiS2_i(arg0, arg1, arg2, arg3)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QMetaObject::indexOfSlot(const char * slot);
impl /*struct*/ QMetaObject {
pub fn indexOfSlot<RetType, T: QMetaObject_indexOfSlot<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfSlot(self);
// return 1;
}
}
pub trait QMetaObject_indexOfSlot<RetType> {
fn indexOfSlot(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::indexOfSlot(const char * slot);
impl<'a> /*trait*/ QMetaObject_indexOfSlot<i32> for (&'a String) {
fn indexOfSlot(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject11indexOfSlotEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZNK11QMetaObject11indexOfSlotEPKc(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::indexOfConstructor(const char * constructor);
impl /*struct*/ QMetaObject {
pub fn indexOfConstructor<RetType, T: QMetaObject_indexOfConstructor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfConstructor(self);
// return 1;
}
}
pub trait QMetaObject_indexOfConstructor<RetType> {
fn indexOfConstructor(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::indexOfConstructor(const char * constructor);
impl<'a> /*trait*/ QMetaObject_indexOfConstructor<i32> for (&'a String) {
fn indexOfConstructor(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject18indexOfConstructorEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZNK11QMetaObject18indexOfConstructorEPKc(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: QMetaEnum QMetaObject::enumerator(int index);
impl /*struct*/ QMetaObject {
pub fn enumerator<RetType, T: QMetaObject_enumerator<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enumerator(self);
// return 1;
}
}
pub trait QMetaObject_enumerator<RetType> {
fn enumerator(self , rsthis: & QMetaObject) -> RetType;
}
// proto: QMetaEnum QMetaObject::enumerator(int index);
impl<'a> /*trait*/ QMetaObject_enumerator<QMetaEnum> for (i32) {
fn enumerator(self , rsthis: & QMetaObject) -> QMetaEnum {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject10enumeratorEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QMetaObject10enumeratorEi(rsthis.qclsinst, arg0)};
let mut ret1 = QMetaEnum::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QMetaObject::indexOfMethod(const char * method);
impl /*struct*/ QMetaObject {
pub fn indexOfMethod<RetType, T: QMetaObject_indexOfMethod<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfMethod(self);
// return 1;
}
}
pub trait QMetaObject_indexOfMethod<RetType> {
fn indexOfMethod(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::indexOfMethod(const char * method);
impl<'a> /*trait*/ QMetaObject_indexOfMethod<i32> for (&'a String) {
fn indexOfMethod(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject13indexOfMethodEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZNK11QMetaObject13indexOfMethodEPKc(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: QMetaMethod QMetaObject::constructor(int index);
impl /*struct*/ QMetaObject {
pub fn constructor<RetType, T: QMetaObject_constructor<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.constructor(self);
// return 1;
}
}
pub trait QMetaObject_constructor<RetType> {
fn constructor(self , rsthis: & QMetaObject) -> RetType;
}
// proto: QMetaMethod QMetaObject::constructor(int index);
impl<'a> /*trait*/ QMetaObject_constructor<QMetaMethod> for (i32) {
fn constructor(self , rsthis: & QMetaObject) -> QMetaMethod {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject11constructorEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QMetaObject11constructorEi(rsthis.qclsinst, arg0)};
let mut ret1 = QMetaMethod::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static bool QMetaObject::checkConnectArgs(const char * signal, const char * method);
impl /*struct*/ QMetaObject {
pub fn checkConnectArgs_s<RetType, T: QMetaObject_checkConnectArgs_s<RetType>>( overload_args: T) -> RetType {
return overload_args.checkConnectArgs_s();
// return 1;
}
}
pub trait QMetaObject_checkConnectArgs_s<RetType> {
fn checkConnectArgs_s(self ) -> RetType;
}
// proto: static bool QMetaObject::checkConnectArgs(const char * signal, const char * method);
impl<'a> /*trait*/ QMetaObject_checkConnectArgs_s<i8> for (&'a String, &'a String) {
fn checkConnectArgs_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject16checkConnectArgsEPKcS1_()};
let arg0 = self.0.as_ptr() as *mut c_char;
let arg1 = self.1.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZN11QMetaObject16checkConnectArgsEPKcS1_(arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QMetaObject::enumeratorOffset();
impl /*struct*/ QMetaObject {
pub fn enumeratorOffset<RetType, T: QMetaObject_enumeratorOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enumeratorOffset(self);
// return 1;
}
}
pub trait QMetaObject_enumeratorOffset<RetType> {
fn enumeratorOffset(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::enumeratorOffset();
impl<'a> /*trait*/ QMetaObject_enumeratorOffset<i32> for () {
fn enumeratorOffset(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject16enumeratorOffsetEv()};
let mut ret = unsafe {C_ZNK11QMetaObject16enumeratorOffsetEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: QMetaProperty QMetaObject::property(int index);
impl /*struct*/ QMetaObject {
pub fn property<RetType, T: QMetaObject_property<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.property(self);
// return 1;
}
}
pub trait QMetaObject_property<RetType> {
fn property(self , rsthis: & QMetaObject) -> RetType;
}
// proto: QMetaProperty QMetaObject::property(int index);
impl<'a> /*trait*/ QMetaObject_property<QMetaProperty> for (i32) {
fn property(self , rsthis: & QMetaObject) -> QMetaProperty {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject8propertyEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QMetaObject8propertyEi(rsthis.qclsinst, arg0)};
let mut ret1 = QMetaProperty::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QMetaObject::connectSlotsByName(QObject * o);
impl /*struct*/ QMetaObject {
pub fn connectSlotsByName_s<RetType, T: QMetaObject_connectSlotsByName_s<RetType>>( overload_args: T) -> RetType {
return overload_args.connectSlotsByName_s();
// return 1;
}
}
pub trait QMetaObject_connectSlotsByName_s<RetType> {
fn connectSlotsByName_s(self ) -> RetType;
}
// proto: static void QMetaObject::connectSlotsByName(QObject * o);
impl<'a> /*trait*/ QMetaObject_connectSlotsByName_s<()> for (&'a QObject) {
fn connectSlotsByName_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject18connectSlotsByNameEP7QObject()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN11QMetaObject18connectSlotsByNameEP7QObject(arg0)};
// return 1;
}
}
// proto: QMetaProperty QMetaObject::userProperty();
impl /*struct*/ QMetaObject {
pub fn userProperty<RetType, T: QMetaObject_userProperty<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.userProperty(self);
// return 1;
}
}
pub trait QMetaObject_userProperty<RetType> {
fn userProperty(self , rsthis: & QMetaObject) -> RetType;
}
// proto: QMetaProperty QMetaObject::userProperty();
impl<'a> /*trait*/ QMetaObject_userProperty<QMetaProperty> for () {
fn userProperty(self , rsthis: & QMetaObject) -> QMetaProperty {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject12userPropertyEv()};
let mut ret = unsafe {C_ZNK11QMetaObject12userPropertyEv(rsthis.qclsinst)};
let mut ret1 = QMetaProperty::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QMetaObject::indexOfProperty(const char * name);
impl /*struct*/ QMetaObject {
pub fn indexOfProperty<RetType, T: QMetaObject_indexOfProperty<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfProperty(self);
// return 1;
}
}
pub trait QMetaObject_indexOfProperty<RetType> {
fn indexOfProperty(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::indexOfProperty(const char * name);
impl<'a> /*trait*/ QMetaObject_indexOfProperty<i32> for (&'a String) {
fn indexOfProperty(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject15indexOfPropertyEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZNK11QMetaObject15indexOfPropertyEPKc(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::indexOfClassInfo(const char * name);
impl /*struct*/ QMetaObject {
pub fn indexOfClassInfo<RetType, T: QMetaObject_indexOfClassInfo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfClassInfo(self);
// return 1;
}
}
pub trait QMetaObject_indexOfClassInfo<RetType> {
fn indexOfClassInfo(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::indexOfClassInfo(const char * name);
impl<'a> /*trait*/ QMetaObject_indexOfClassInfo<i32> for (&'a String) {
fn indexOfClassInfo(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject16indexOfClassInfoEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZNK11QMetaObject16indexOfClassInfoEPKc(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: static void QMetaObject::activate(QObject * sender, const QMetaObject * , int local_signal_index, void ** argv);
impl /*struct*/ QMetaObject {
pub fn activate_s<RetType, T: QMetaObject_activate_s<RetType>>( overload_args: T) -> RetType {
return overload_args.activate_s();
// return 1;
}
}
pub trait QMetaObject_activate_s<RetType> {
fn activate_s(self ) -> RetType;
}
// proto: static void QMetaObject::activate(QObject * sender, const QMetaObject * , int local_signal_index, void ** argv);
impl<'a> /*trait*/ QMetaObject_activate_s<()> for (&'a QObject, &'a QMetaObject, i32, *mut c_void) {
fn activate_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject8activateEP7QObjectPKS_iPPv()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2 as c_int;
let arg3 = self.3 as *mut c_void;
unsafe {C_ZN11QMetaObject8activateEP7QObjectPKS_iPPv(arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: const QObject * QMetaObject::cast(const QObject * obj);
impl /*struct*/ QMetaObject {
pub fn cast<RetType, T: QMetaObject_cast<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.cast(self);
// return 1;
}
}
pub trait QMetaObject_cast<RetType> {
fn cast(self , rsthis: & QMetaObject) -> RetType;
}
// proto: const QObject * QMetaObject::cast(const QObject * obj);
impl<'a> /*trait*/ QMetaObject_cast<QObject> for (&'a QObject) {
fn cast(self , rsthis: & QMetaObject) -> QObject {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject4castEPK7QObject()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK11QMetaObject4castEPK7QObject(rsthis.qclsinst, arg0)};
let mut ret1 = QObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QMetaMethod QMetaObject::method(int index);
impl /*struct*/ QMetaObject {
pub fn method<RetType, T: QMetaObject_method<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.method(self);
// return 1;
}
}
pub trait QMetaObject_method<RetType> {
fn method(self , rsthis: & QMetaObject) -> RetType;
}
// proto: QMetaMethod QMetaObject::method(int index);
impl<'a> /*trait*/ QMetaObject_method<QMetaMethod> for (i32) {
fn method(self , rsthis: & QMetaObject) -> QMetaMethod {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject6methodEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QMetaObject6methodEi(rsthis.qclsinst, arg0)};
let mut ret1 = QMetaMethod::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QMetaObject::superClass();
impl /*struct*/ QMetaObject {
pub fn superClass<RetType, T: QMetaObject_superClass<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.superClass(self);
// return 1;
}
}
pub trait QMetaObject_superClass<RetType> {
fn superClass(self , rsthis: & QMetaObject) -> RetType;
}
// proto: const QMetaObject * QMetaObject::superClass();
impl<'a> /*trait*/ QMetaObject_superClass<QMetaObject> for () {
fn superClass(self , rsthis: & QMetaObject) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject10superClassEv()};
let mut ret = unsafe {C_ZNK11QMetaObject10superClassEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static void QMetaObject::activate(QObject * sender, int signal_offset, int local_signal_index, void ** argv);
impl<'a> /*trait*/ QMetaObject_activate_s<()> for (&'a QObject, i32, i32, *mut c_void) {
fn activate_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject8activateEP7QObjectiiPPv()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as c_int;
let arg3 = self.3 as *mut c_void;
unsafe {C_ZN11QMetaObject8activateEP7QObjectiiPPv(arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: int QMetaObject::propertyCount();
impl /*struct*/ QMetaObject {
pub fn propertyCount<RetType, T: QMetaObject_propertyCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.propertyCount(self);
// return 1;
}
}
pub trait QMetaObject_propertyCount<RetType> {
fn propertyCount(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::propertyCount();
impl<'a> /*trait*/ QMetaObject_propertyCount<i32> for () {
fn propertyCount(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject13propertyCountEv()};
let mut ret = unsafe {C_ZNK11QMetaObject13propertyCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: QMetaClassInfo QMetaObject::classInfo(int index);
impl /*struct*/ QMetaObject {
pub fn classInfo<RetType, T: QMetaObject_classInfo<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.classInfo(self);
// return 1;
}
}
pub trait QMetaObject_classInfo<RetType> {
fn classInfo(self , rsthis: & QMetaObject) -> RetType;
}
// proto: QMetaClassInfo QMetaObject::classInfo(int index);
impl<'a> /*trait*/ QMetaObject_classInfo<QMetaClassInfo> for (i32) {
fn classInfo(self , rsthis: & QMetaObject) -> QMetaClassInfo {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject9classInfoEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK11QMetaObject9classInfoEi(rsthis.qclsinst, arg0)};
let mut ret1 = QMetaClassInfo::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: static bool QMetaObject::checkConnectArgs(const QMetaMethod & signal, const QMetaMethod & method);
impl<'a> /*trait*/ QMetaObject_checkConnectArgs_s<i8> for (&'a QMetaMethod, &'a QMetaMethod) {
fn checkConnectArgs_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject16checkConnectArgsERK11QMetaMethodS2_()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN11QMetaObject16checkConnectArgsERK11QMetaMethodS2_(arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: const char * QMetaObject::className();
impl /*struct*/ QMetaObject {
pub fn className<RetType, T: QMetaObject_className<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.className(self);
// return 1;
}
}
pub trait QMetaObject_className<RetType> {
fn className(self , rsthis: & QMetaObject) -> RetType;
}
// proto: const char * QMetaObject::className();
impl<'a> /*trait*/ QMetaObject_className<String> for () {
fn className(self , rsthis: & QMetaObject) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject9classNameEv()};
let mut ret = unsafe {C_ZNK11QMetaObject9classNameEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: int QMetaObject::indexOfSignal(const char * signal);
impl /*struct*/ QMetaObject {
pub fn indexOfSignal<RetType, T: QMetaObject_indexOfSignal<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfSignal(self);
// return 1;
}
}
pub trait QMetaObject_indexOfSignal<RetType> {
fn indexOfSignal(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::indexOfSignal(const char * signal);
impl<'a> /*trait*/ QMetaObject_indexOfSignal<i32> for (&'a String) {
fn indexOfSignal(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject13indexOfSignalEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZNK11QMetaObject13indexOfSignalEPKc(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: static QByteArray QMetaObject::normalizedType(const char * type);
impl /*struct*/ QMetaObject {
pub fn normalizedType_s<RetType, T: QMetaObject_normalizedType_s<RetType>>( overload_args: T) -> RetType {
return overload_args.normalizedType_s();
// return 1;
}
}
pub trait QMetaObject_normalizedType_s<RetType> {
fn normalizedType_s(self ) -> RetType;
}
// proto: static QByteArray QMetaObject::normalizedType(const char * type);
impl<'a> /*trait*/ QMetaObject_normalizedType_s<QByteArray> for (&'a String) {
fn normalizedType_s(self ) -> QByteArray {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject14normalizedTypeEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZN11QMetaObject14normalizedTypeEPKc(arg0)};
let mut ret1 = QByteArray::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QMetaObject::constructorCount();
impl /*struct*/ QMetaObject {
pub fn constructorCount<RetType, T: QMetaObject_constructorCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.constructorCount(self);
// return 1;
}
}
pub trait QMetaObject_constructorCount<RetType> {
fn constructorCount(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::constructorCount();
impl<'a> /*trait*/ QMetaObject_constructorCount<i32> for () {
fn constructorCount(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject16constructorCountEv()};
let mut ret = unsafe {C_ZNK11QMetaObject16constructorCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::propertyOffset();
impl /*struct*/ QMetaObject {
pub fn propertyOffset<RetType, T: QMetaObject_propertyOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.propertyOffset(self);
// return 1;
}
}
pub trait QMetaObject_propertyOffset<RetType> {
fn propertyOffset(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::propertyOffset();
impl<'a> /*trait*/ QMetaObject_propertyOffset<i32> for () {
fn propertyOffset(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject14propertyOffsetEv()};
let mut ret = unsafe {C_ZNK11QMetaObject14propertyOffsetEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: static bool QMetaObject::disconnect(const QObject * sender, int signal_index, const QObject * receiver, int method_index);
impl /*struct*/ QMetaObject {
pub fn disconnect_s<RetType, T: QMetaObject_disconnect_s<RetType>>( overload_args: T) -> RetType {
return overload_args.disconnect_s();
// return 1;
}
}
pub trait QMetaObject_disconnect_s<RetType> {
fn disconnect_s(self ) -> RetType;
}
// proto: static bool QMetaObject::disconnect(const QObject * sender, int signal_index, const QObject * receiver, int method_index);
impl<'a> /*trait*/ QMetaObject_disconnect_s<i8> for (&'a QObject, i32, &'a QObject, i32) {
fn disconnect_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject10disconnectEPK7QObjectiS2_i()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2.qclsinst as *mut c_void;
let arg3 = self.3 as c_int;
let mut ret = unsafe {C_ZN11QMetaObject10disconnectEPK7QObjectiS2_i(arg0, arg1, arg2, arg3)};
return ret as i8; // 1
// return 1;
}
}
// proto: static void QMetaObject::activate(QObject * sender, int signal_index, void ** argv);
impl<'a> /*trait*/ QMetaObject_activate_s<()> for (&'a QObject, i32, *mut c_void) {
fn activate_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZN11QMetaObject8activateEP7QObjectiPPv()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_int;
let arg2 = self.2 as *mut c_void;
unsafe {C_ZN11QMetaObject8activateEP7QObjectiPPv(arg0, arg1, arg2)};
// return 1;
}
}
// proto: int QMetaObject::enumeratorCount();
impl /*struct*/ QMetaObject {
pub fn enumeratorCount<RetType, T: QMetaObject_enumeratorCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.enumeratorCount(self);
// return 1;
}
}
pub trait QMetaObject_enumeratorCount<RetType> {
fn enumeratorCount(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::enumeratorCount();
impl<'a> /*trait*/ QMetaObject_enumeratorCount<i32> for () {
fn enumeratorCount(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject15enumeratorCountEv()};
let mut ret = unsafe {C_ZNK11QMetaObject15enumeratorCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::classInfoOffset();
impl /*struct*/ QMetaObject {
pub fn classInfoOffset<RetType, T: QMetaObject_classInfoOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.classInfoOffset(self);
// return 1;
}
}
pub trait QMetaObject_classInfoOffset<RetType> {
fn classInfoOffset(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::classInfoOffset();
impl<'a> /*trait*/ QMetaObject_classInfoOffset<i32> for () {
fn classInfoOffset(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject15classInfoOffsetEv()};
let mut ret = unsafe {C_ZNK11QMetaObject15classInfoOffsetEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::methodOffset();
impl /*struct*/ QMetaObject {
pub fn methodOffset<RetType, T: QMetaObject_methodOffset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.methodOffset(self);
// return 1;
}
}
pub trait QMetaObject_methodOffset<RetType> {
fn methodOffset(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::methodOffset();
impl<'a> /*trait*/ QMetaObject_methodOffset<i32> for () {
fn methodOffset(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject12methodOffsetEv()};
let mut ret = unsafe {C_ZNK11QMetaObject12methodOffsetEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::indexOfEnumerator(const char * name);
impl /*struct*/ QMetaObject {
pub fn indexOfEnumerator<RetType, T: QMetaObject_indexOfEnumerator<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.indexOfEnumerator(self);
// return 1;
}
}
pub trait QMetaObject_indexOfEnumerator<RetType> {
fn indexOfEnumerator(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::indexOfEnumerator(const char * name);
impl<'a> /*trait*/ QMetaObject_indexOfEnumerator<i32> for (&'a String) {
fn indexOfEnumerator(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject17indexOfEnumeratorEPKc()};
let arg0 = self.as_ptr() as *mut c_char;
let mut ret = unsafe {C_ZNK11QMetaObject17indexOfEnumeratorEPKc(rsthis.qclsinst, arg0)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::methodCount();
impl /*struct*/ QMetaObject {
pub fn methodCount<RetType, T: QMetaObject_methodCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.methodCount(self);
// return 1;
}
}
pub trait QMetaObject_methodCount<RetType> {
fn methodCount(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::methodCount();
impl<'a> /*trait*/ QMetaObject_methodCount<i32> for () {
fn methodCount(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject11methodCountEv()};
let mut ret = unsafe {C_ZNK11QMetaObject11methodCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QMetaObject::classInfoCount();
impl /*struct*/ QMetaObject {
pub fn classInfoCount<RetType, T: QMetaObject_classInfoCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.classInfoCount(self);
// return 1;
}
}
pub trait QMetaObject_classInfoCount<RetType> {
fn classInfoCount(self , rsthis: & QMetaObject) -> RetType;
}
// proto: int QMetaObject::classInfoCount();
impl<'a> /*trait*/ QMetaObject_classInfoCount<i32> for () {
fn classInfoCount(self , rsthis: & QMetaObject) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 48)};
// unsafe{_ZNK11QMetaObject14classInfoCountEv()};
let mut ret = unsafe {C_ZNK11QMetaObject14classInfoCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
impl /*struct*/ QGenericArgument {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGenericArgument {
return QGenericArgument{qclsinst: qthis, ..Default::default()};
}
}
// proto: const char * QGenericArgument::name();
impl /*struct*/ QGenericArgument {
pub fn name<RetType, T: QGenericArgument_name<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.name(self);
// return 1;
}
}
pub trait QGenericArgument_name<RetType> {
fn name(self , rsthis: & QGenericArgument) -> RetType;
}
// proto: const char * QGenericArgument::name();
impl<'a> /*trait*/ QGenericArgument_name<String> for () {
fn name(self , rsthis: & QGenericArgument) -> String {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QGenericArgument4nameEv()};
let mut ret = unsafe {C_ZNK16QGenericArgument4nameEv(rsthis.qclsinst)};
let slen = unsafe {strlen(ret as *const i8)} as usize;
return unsafe{String::from_raw_parts(ret as *mut u8, slen, slen+1)};
// return 1;
}
}
// proto: void * QGenericArgument::data();
impl /*struct*/ QGenericArgument {
pub fn data<RetType, T: QGenericArgument_data<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.data(self);
// return 1;
}
}
pub trait QGenericArgument_data<RetType> {
fn data(self , rsthis: & QGenericArgument) -> RetType;
}
// proto: void * QGenericArgument::data();
impl<'a> /*trait*/ QGenericArgument_data<*mut c_void> for () {
fn data(self , rsthis: & QGenericArgument) -> *mut c_void {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK16QGenericArgument4dataEv()};
let mut ret = unsafe {C_ZNK16QGenericArgument4dataEv(rsthis.qclsinst)};
return ret as *mut c_void; // 1
// return 1;
}
}
// proto: void QGenericArgument::QGenericArgument(const char * aName, const void * aData);
impl /*struct*/ QGenericArgument {
pub fn new<T: QGenericArgument_new>(value: T) -> QGenericArgument {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGenericArgument_new {
fn new(self) -> QGenericArgument;
}
// proto: void QGenericArgument::QGenericArgument(const char * aName, const void * aData);
impl<'a> /*trait*/ QGenericArgument_new for (Option<&'a String>, Option<*mut c_void>) {
fn new(self) -> QGenericArgument {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN16QGenericArgumentC2EPKcPKv()};
let ctysz: c_int = unsafe{QGenericArgument_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.0.is_none() {0 as *const u8} else {self.0.unwrap().as_ptr()}) as *mut c_char;
let arg1 = (if self.1.is_none() {0 as *mut c_void} else {self.1.unwrap()}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN16QGenericArgumentC2EPKcPKv(arg0, arg1)};
let rsthis = QGenericArgument{qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// <= body block end
|
//! https://github.com/lumen/otp/tree/lumen/lib/ssh/src
use super::*;
test_compiles_lumen_otp!(ssh);
test_compiles_lumen_otp!(ssh_acceptor);
test_compiles_lumen_otp!(ssh_acceptor_sup);
test_compiles_lumen_otp!(ssh_agent);
test_compiles_lumen_otp!(ssh_app imports "lib/stdlib/src/supervisor");
test_compiles_lumen_otp!(ssh_auth);
test_compiles_lumen_otp!(ssh_bits imports "lib/crypto/src/crypto", "lib/stdlib/src/lists");
test_compiles_lumen_otp!(ssh_channel imports "lib/ssh/src/ssh_client_channel");
test_compiles_lumen_otp!(ssh_channel_sup);
test_compiles_lumen_otp!(ssh_cli);
test_compiles_lumen_otp!(ssh_client_channel);
test_compiles_lumen_otp!(ssh_client_key_api);
test_compiles_lumen_otp!(ssh_connection);
test_compiles_lumen_otp!(ssh_connection_handler);
test_compiles_lumen_otp!(ssh_connection_sup imports "lib/stdlib/src/supervisor");
test_compiles_lumen_otp!(ssh_daemon_channel imports "lib/ssh/ssh_server_channel");
test_compiles_lumen_otp!(ssh_dbg);
test_compiles_lumen_otp!(ssh_file);
test_compiles_lumen_otp!(ssh_info);
test_compiles_lumen_otp!(ssh_io);
test_compiles_lumen_otp!(ssh_message);
test_compiles_lumen_otp!(ssh_no_io);
test_compiles_lumen_otp!(ssh_options);
test_compiles_lumen_otp!(ssh_server_channel imports "lib/ssh/ssh_client_channel");
test_compiles_lumen_otp!(ssh_server_key_api);
test_compiles_lumen_otp!(ssh_sftp);
test_compiles_lumen_otp!(ssh_sftpd);
test_compiles_lumen_otp!(ssh_sftpd_file imports "lib/kernel/src/file", "lib/stdlib/src/filelib");
test_compiles_lumen_otp!(ssh_sftpd_file_api);
test_compiles_lumen_otp!(ssh_shell);
test_compiles_lumen_otp!(ssh_subsystem_sup);
test_compiles_lumen_otp!(ssh_sup);
test_compiles_lumen_otp!(ssh_system_sup);
test_compiles_lumen_otp!(ssh_tcpip_forward_acceptor);
test_compiles_lumen_otp!(ssh_tcpip_forward_acceptor_sup imports "lib/stdlib/src/supervisor");
test_compiles_lumen_otp!(ssh_tcpip_forward_client);
test_compiles_lumen_otp!(ssh_tcpip_forward_srv);
test_compiles_lumen_otp!(ssh_transport);
test_compiles_lumen_otp!(ssh_xfer);
test_compiles_lumen_otp!(sshc_sup);
test_compiles_lumen_otp!(sshd_sup);
fn includes() -> Vec<&'static str> {
let mut includes = super::includes();
includes.extend(vec![
"lib/kernel/include",
"lib/kernel/src",
"lib/public_key/include",
"lib/ssh/src",
]);
includes
}
fn relative_directory_path() -> PathBuf {
super::relative_directory_path().join("ssh/src")
}
fn setup() {
public_key::setup();
}
|
extern crate regex;
use super::Graph;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::io::Result;
use self::regex::Regex;
use std::str::FromStr;
use std::fmt::Display;
pub fn unconnected<T : Eq + Clone + Hash>(nodes : Vec<T>, directed : bool) -> Graph<T> {
let hash_map : HashMap<T, usize> =
nodes.iter()
.cloned()
.enumerate()
.map(|(i, x)| { (x, i) })
.collect();
let adjacency_list = vec![Vec::new(); nodes.len()];
Graph { nodes : nodes.clone(), directed : directed, node_indices : hash_map, adjacency_list : adjacency_list }
}
pub fn from_file(filename : &str) -> Result<Graph<usize>> {
let (number_of_vertices, directed, edges, _) = parse_file::<usize>(filename);
let mut g = unconnected((0..number_of_vertices).collect(), directed);
for (source, dest) in edges {
if directed { g.add_directed_edge(source, dest) }
else { g.add_undirected_edge(source, dest) }
}
Ok(g)
}
pub fn from_file_with_nodes<T : Clone + Eq + Hash + FromStr>(filename : &str) -> Result<Graph<T>> {
let (number_of_vertices, directed, edges, nodes) = parse_file::<T>(filename);
// Test that I have the correct number of nodes
if number_of_vertices != nodes.len() {
panic!("Graph file specified {} vertices, but listed {}.", number_of_vertices, nodes.len())
}
{
// Test that the nodes are unique
let mut hasher = DefaultHasher::new();
let mut node_clones : Vec<(u64, &T)> =
nodes.iter().map(|n| {
n.hash(&mut hasher);
(hasher.finish(), n)
}).collect();
node_clones.sort_by(|&(h1, _), &(h2, _)| h1.cmp(&h2));
let mut prev_element = None;
for (h2, n2) in node_clones {
if let Some((h1, n1)) = prev_element {
if h1 == h2 && n1 == n2 { panic!("Nodes are not unique!") }
}
prev_element = Some((h2, n2));
}
}
let mut g = unconnected(nodes, directed);
for (source, dest) in edges {
if directed { g.add_directed_edge(source, dest) }
else { g.add_undirected_edge(source, dest) }
}
Ok(g)
}
// A helper function that returns the parsed data read from the graph file.
// We want to do slightly different things with it depending on whether or not
// we're expecting node names.
fn parse_file<T>(filename : &str) -> (usize, bool, Vec<(usize, usize)>, Vec<T>)
where T : FromStr
{
let file = File::open(filename).unwrap();
let buf_reader = BufReader::new(file);
// Strip out comments and blank lines
let lines =
buf_reader.lines()
.map(|l| l.unwrap()) // FIXME - maybe better error handling than this?
.map(|l| l.split("//").next().map(|x| String::from(x.trim())))
.filter(|l| match l {
&None => false,
&Some(ref l) => l.len() > 0,
})
.map(|x| x.unwrap());
let variable_regex = Regex::new(r"^\s*([a-z_]+)\s*:\s*([a-zA-Z0-9]*)\s*$").unwrap();
let edges_regex = Regex::new(r"^\s*(\d+)\s*(\d+)\s*$").unwrap();
let nodes_regex = Regex::new(r"^\s*([a-zA-Z0-9_(::)]*[a-zA-Z0-9_]+)\s*$").unwrap();
let mut number_of_vertices = None;
let mut directed = None;
let mut edges_mode = false;
let mut nodes_mode = false;
let mut parsed_line : bool;
let mut edges = Vec::new();
let mut nodes : Vec<T> = Vec::new();
for line in lines {
parsed_line = false;
variable_regex.captures(&line).map(|cap| {
match &cap[1] {
"edges" => {
if &cap[2] != "" { panic!("Spurious text {} after edges keyword", &cap[1]) }
edges_mode = true;
parsed_line = true;
},
"nodes" => {
if &cap[2] != "" { panic!("Spurious text {} after nodes keyword", &cap[1]) }
nodes_mode = true;
parsed_line = true;
},
"number_of_vertices" => {
if number_of_vertices.is_some() { panic!("File specifies number_of_vertices multiple times.") }
number_of_vertices = Some((&cap[2]).parse::<usize>().unwrap());
parsed_line = true;
},
"directed" => {
if directed.is_some() { panic!("File specifies directed multiple times.") }
directed = Some((&cap[2]).parse::<bool>().unwrap());
parsed_line = true;
},
s => panic!("Unrecognised variable name: {}", s),
}
});
nodes_regex.captures(&line).map(|cap| {
if nodes_mode {
let node = (&cap[1]).parse::<T>()
.or_else(|_| -> ::std::result::Result<T, ()> {
panic!("Failed to parse node: {}", &cap[1])
})
.unwrap();
nodes.push(node);
parsed_line = true;
}
});
edges_regex.captures(&line).map(|cap| {
if edges_mode {
let source = (&cap[1]).parse::<usize>().unwrap();
let dest = (&cap[2]).parse::<usize>().unwrap();
edges.push((source, dest));
parsed_line = true;
}
});
if !parsed_line { panic!("Failed to parse line: {}", line) };
}
let number_of_vertices = match number_of_vertices {
None => panic!("number_of_vertices not specified"),
Some(n) => n,
};
let directed = match directed {
None => true,
Some(d) => d,
};
(number_of_vertices, directed, edges, nodes)
}
pub fn make_serialization_string<T>(graph : &Graph<T>) -> String
where T : Clone + Eq + Hash
{
let mut ser = String::new();
ser.push_str("// Graph\n");
ser.push_str(&*format!("number_of_vertices: {}\n", graph.number_of_vertices()));
ser.push_str(&*format!("directed: {}\n", graph.is_directed()));
ser.push_str("edges:\n");
for source in 0..(graph.number_of_vertices()) {
for dest in &graph.adjacency_list[source] {
if graph.is_directed() || *dest > source {
ser.push_str(&*format!("{} {}\n", source, *dest));
}
}
}
ser
}
pub fn make_serialization_string_with_nodes<T>(graph : &Graph<T>) -> String
where T : Clone + Eq + Hash + Display
{
let mut ser = make_serialization_string(graph); // Re-use the above code to serialize the structure
ser.push_str("nodes:\n");
for node in &graph.nodes {
ser.push_str(&format!("{}\n", node));
}
ser
}
|
use std::collections::HashSet;
use std::env;
use actix_web::{web, App, HttpRequest, HttpServer, Responder, HttpResponse};
use std::time::{SystemTime, UNIX_EPOCH};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let redis_url = env::var("FLY_REDIS_CACHE_URL").unwrap();
println!("Using {}", redis_url);
let redis_client = redis::Client::open(redis_url).unwrap();
let client = Client::new(redis_client);
for (id, state) in client.find_all_states() {
println!("{}: {}", id, state);
}
HttpServer::new(move || {
App::new()
.data(client.clone())
.route("/", web::get().to(list))
.route("/update", web::post().to(update))
})
.bind(("0.0.0.0", 8080))?
.run()
.await
}
async fn list(client: web::Data<Client>) -> impl Responder {
client.find_all_states()
.iter()
.map(|(id, state)| format!("{}: {}", id, state))
.collect::<Vec<String>>()
.join("\n")
}
async fn update(client: web::Data<Client>) -> impl Responder {
let system_time = SystemTime::now();
let since_the_epoch = system_time
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let current_time_millis = since_the_epoch.as_millis();
let arbitrary_id = format!("id{}", current_time_millis % 1000);
let arbitrary_state = format!("state{}", current_time_millis % 7);
client.set_state(&arbitrary_id, &arbitrary_state);
HttpResponse::Ok().body(format!("{}: {}", arbitrary_id, arbitrary_state))
}
#[derive(Clone)]
struct Client {
redis_client: redis::Client
}
impl Client {
fn new(redis_client: redis::Client) -> Self {
Client { redis_client }
}
fn set_state(&self, id: &str, state: &str) {
use redis::Commands;
let mut con = self.redis_client.get_connection().unwrap();
con.hset::<&str, &str, &str, u8>("states", id, state).unwrap();
}
fn find_state(&self, id: &str) -> Option<String> {
use redis::Commands;
let mut con = self.redis_client.get_connection().unwrap();
match con.hget("states", id) {
Ok(state) => Some(state),
Err(_) => None
}
}
fn find_all_states(&self) -> HashSet<(String, String)> {
use redis::{Commands, Iter};
let mut con = self.redis_client.get_connection().unwrap();
let states_iter: Iter<'_, (String, String)>= con.hscan("states").unwrap();
states_iter.collect()
}
}
#[cfg(test)]
mod tests {
use testcontainers::{clients, images, Docker};
use std::collections::HashSet;
use crate::Client;
#[tokio::test]
async fn no_states_by_default() {
let _ = pretty_env_logger::try_init();
let docker = clients::Cli::default();
let node = docker.run(images::redis::Redis::default());
let host_port = node.get_host_port(6379).unwrap();
let url = format!("redis://localhost:{}", host_port);
let redis_client = redis::Client::open(url.as_ref()).unwrap();
let client = Client::new(redis_client);
let states = client.find_all_states();
assert_eq!(0, states.len());
}
#[tokio::test]
async fn can_set_state() {
let _ = pretty_env_logger::try_init();
let docker = clients::Cli::default();
let node = docker.run(images::redis::Redis::default());
let host_port = node.get_host_port(6379).unwrap();
let url = format!("redis://localhost:{}", host_port);
let redis_client = redis::Client::open(url.as_ref()).unwrap();
let client = Client::new(redis_client);
let initial_state = client.find_state(&"some_id".to_string());
assert_eq!(None, initial_state);
let expected_state = "some_state".to_string();
client.set_state(&"some_id".to_string(), &expected_state);
let current_state = client.find_state(&"some_id".to_string());
assert_eq!(Some(expected_state), current_state);
}
#[tokio::test]
async fn can_update_state() {
let _ = pretty_env_logger::try_init();
let docker = clients::Cli::default();
let node = docker.run(images::redis::Redis::default());
let host_port = node.get_host_port(6379).unwrap();
let url = format!("redis://localhost:{}", host_port);
let redis_client = redis::Client::open(url.as_ref()).unwrap();
let client = Client::new(redis_client);
let initial_state = client.find_state(&"some_id".to_string());
assert_eq!(None, initial_state);
let intermediate_state = "some_other_state".to_string();
client.set_state(&"some_id".to_string(), &intermediate_state);
let mut current_state = client.find_state(&"some_id".to_string()).unwrap();
assert_eq!(intermediate_state, current_state);
let expected_state = "some_state".to_string();
client.set_state(&"some_id".to_string(), &expected_state);
current_state = client.find_state(&"some_id".to_string()).unwrap();
assert_eq!(expected_state, current_state);
}
#[tokio::test]
async fn can_find_all_states() {
let _ = pretty_env_logger::try_init();
let docker = clients::Cli::default();
let node = docker.run(images::redis::Redis::default());
let host_port = node.get_host_port(6379).unwrap();
let url = format!("redis://localhost:{}", host_port);
let redis_client = redis::Client::open(url.as_ref()).unwrap();
let client = Client::new(redis_client);
client.set_state(&"id1".to_string(), &"state1".to_string());
client.set_state(&"id2".to_string(), &"state2".to_string());
let expected_states : HashSet<(String, String)>
= vec![
("id1".to_string(), "state1".to_string()),
("id2".to_string(), "state2".to_string())]
.into_iter().collect();
let states = client.find_all_states();
assert_eq!(expected_states, states);
}
} |
use {
derive_new::new,
rough::{
amethyst::{
controls::{HideCursor, WindowFocus},
core::{bundle::SystemBundle, ecs::prelude::*},
derive::SystemDesc,
prelude::*,
shrev::{EventChannel, ReaderId},
winit::{Event, Window, WindowEvent},
},
log,
},
};
pub const WINDOW_FOCUS_SYSTEM: &str = "window_focus_system";
pub const CURSOR_GRAB_SYSTEM: &str = "cursor_grab_system";
#[derive(new)]
pub struct CursorGrabBundle;
impl<'a, 'b> SystemBundle<'a, 'b> for CursorGrabBundle {
fn build(
self,
world: &mut World,
builder: &mut DispatcherBuilder<'a, 'b>,
) -> amethyst::Result<()> {
builder.add(
WindowFocusUpdateSystemDesc::default().build(world),
WINDOW_FOCUS_SYSTEM,
&["input_system"],
);
builder.add(
CursorGrabSystemDesc::default().build(world),
CURSOR_GRAB_SYSTEM,
&[WINDOW_FOCUS_SYSTEM],
);
Ok(())
}
}
/// A system which reads Events and saves if a window has lost focus in a WindowFocus resource
#[derive(Debug, SystemDesc, new)]
#[system_desc(name(WindowFocusUpdateSystemDesc))]
pub struct WindowFocusUpdateSystem {
#[system_desc(event_channel_reader)]
event_reader: ReaderId<Event>,
}
impl<'a> System<'a> for WindowFocusUpdateSystem {
type SystemData = (Read<'a, EventChannel<Event>>, Write<'a, WindowFocus>);
fn run(&mut self, (events, mut focus): Self::SystemData) {
for event in events.read(&mut self.event_reader) {
if let Event::WindowEvent { ref event, .. } = *event {
if let WindowEvent::Focused(focused) = *event {
focus.is_focused = focused;
break;
}
}
}
}
}
/// System which hides the cursor when the window is focused.
/// Requires the usage WindowFocusUpdateSystem at the same time.
#[derive(Debug, SystemDesc, new)]
#[system_desc(name(CursorGrabSystemDesc))]
pub struct CursorGrabSystem {
#[new(value = "true")]
#[system_desc(skip)]
is_hidden: bool,
}
impl Default for CursorGrabSystem {
fn default() -> Self {
CursorGrabSystem::new()
}
}
impl<'a> System<'a> for CursorGrabSystem {
type SystemData = (
ReadExpect<'a, Window>,
Read<'a, HideCursor>,
Read<'a, WindowFocus>,
);
fn run(&mut self, (win, hide, focus): Self::SystemData) {
let should_be_hidden = focus.is_focused && hide.hide;
if !self.is_hidden && should_be_hidden {
if let Err(err) = win.grab_cursor(true) {
log::error!("Unable to grab the cursor. Error: {}", err);
}
win.hide_cursor(true);
self.is_hidden = true;
} else if self.is_hidden && !should_be_hidden {
if let Err(err) = win.grab_cursor(false) {
log::error!("Unable to release the cursor. Error: {}", err);
}
win.hide_cursor(false);
self.is_hidden = false;
}
}
}
|
#![no_main]
#![no_std]
#![feature(alloc_error_handler)]
#[macro_use(singleton)]
extern crate cortex_m;
use bluepill::clocks::*;
use bluepill::hal::delay::Delay;
use bluepill::hal::dma::{CircReadDma, Half, RxDma};
use bluepill::hal::gpio::gpioc::PC13;
use bluepill::hal::gpio::{Output, PushPull};
use bluepill::hal::{
pac::interrupt,
pac::Interrupt,
pac::USART1,
prelude::*,
serial::{Config, Rx, Serial, Tx},
};
use bluepill::led::*;
use core::borrow::Borrow;
use core::cell::RefCell;
use core::fmt::Write;
use cortex_m::asm;
use stm32f1xx_hal::dma::dma1::C5;
use cortex_m::{asm::wfi, interrupt::Mutex};
use cortex_m_rt::entry;
use embedded_dma::ReadBuffer;
use heapless::spsc::{Consumer, Producer, Queue};
use heapless::Vec;
use panic_halt as _;
use alloc_cortex_m::CortexMHeap;
#[global_allocator]
static ALLOCATOR: CortexMHeap = CortexMHeap::empty();
/// 堆内存 8K
const HEAP_SIZE: usize = 8192;
fn init() {
unsafe {
ALLOCATOR.init(cortex_m_rt::heap_start() as usize, HEAP_SIZE);
}
}
#[entry]
fn main() -> ! {
init();
let p = bluepill::Peripherals::take().unwrap(); //核心设备、外围设备
let mut flash = p.device.FLASH.constrain(); //Flash
let mut rcc = p.device.RCC.constrain(); //RCC
let mut afio = p.device.AFIO.constrain(&mut rcc.apb2);
let clocks = rcc.cfgr.clocks_72mhz(&mut flash.acr); //配置全速时钟
let channels = p.device.DMA1.split(&mut rcc.ahb);
let mut gpioa = p.device.GPIOA.split(&mut rcc.apb2);
let mut gpioc = p.device.GPIOC.split(&mut rcc.apb2);
let mut delay = Delay::new(p.core.SYST, clocks); //配置延时器
let mut led = Led(gpioc.pc13).ppo(&mut gpioc.crh); //配置LED
let (mut stdout, mut stdin) = bluepill::serial::Serial::with_usart(p.device.USART1)
.pins(gpioa.pa9, gpioa.pa10) //映射到引脚
.cr(&mut gpioa.crh) //配置GPIO控制寄存器
.clocks(clocks) //时钟
.afio_mapr(&mut afio.mapr) //复用重映射即寄存器
.bus(&mut rcc.apb2) //配置内核总线
.build()
.split();
let mut rx = stdin.with_dma(channels.5);
read_dma1(&mut stdout, rx);
loop {}
}
fn read_dma_circ(stdout: &mut Tx<USART1>, rx: RxDma<Rx<USART1>, C5>) {
let mut rx = rx;
let buf = singleton!(: [[u8; 8]; 2] = [[0; 8]; 2]).unwrap();
let mut s: heapless::String<16384> = heapless::String::new();
read_dma(stdout, rx)
}
fn read_dma1(stdout: &mut Tx<USART1>, rx: RxDma<Rx<USART1>, C5>) -> ! {
let mut rx = rx;
let mut buf = singleton!(: [u8; 8] = [0; 8]).unwrap();
let mut s: heapless::String<4096> = heapless::String::new();
loop {
let t = rx.read(buf);
while !t.is_done() {}
let (out, _rx) = t.wait();
out.iter().for_each(|b| {
let c = *b as char;
if c == '\n' {
stdout.write_fmt(format_args!("{}", s));
s.clear();
} else {
if s.len() == 4096 {
stdout.write_fmt(format_args!("{}", s));
s.clear();
}
s.push(c).ok();
}
});
rx = _rx;
buf = out;
//led.toggle();
}
}
fn read_dma(stdout: &mut Tx<USART1>, rx: RxDma<Rx<USART1>, C5>) {
let mut rx = rx;
let mut buf = singleton!(: [u8; 1] = [0; 1]).unwrap();
let mut s: heapless::String<4096> = heapless::String::new();
loop {
let (out, _rx) = rx.read(buf).wait();
out.iter().for_each(|b| {
let c = *b as char;
if c == '\n' {
//s.push(c).ok();
stdout.write_fmt(format_args!("{}", s));
s.clear();
} else {
s.push(*b as char).ok();
}
});
if s.len() == 4096 {
stdout.write_fmt(format_args!("{}", s));
s.clear();
}
rx = _rx;
buf = out;
//led.toggle();
}
}
// 内存不足执行此处代码(调试用)
#[alloc_error_handler]
fn alloc_error(_layout: core::alloc::Layout) -> ! {
cortex_m::asm::bkpt();
loop {}
}
|
use std::{thread, time};
use test_deps::deps;
static mut BOOL_IGN_OK: bool = false;
#[deps(IGN_OK_000)]
#[test]
fn with_ignore_attribute_000() {
thread::sleep(time::Duration::from_millis(250));
unsafe {
assert!(!BOOL_IGN_OK);
BOOL_IGN_OK = true;
}
}
#[deps(IGN_OK_001: IGN_OK_000)]
#[ignore]
#[test]
fn with_ignore_attribute_001() {
unsafe {
BOOL_IGN_OK = false;
}
panic!("you should not come here");
}
#[deps(IGN_OK_002: IGN_OK_001)]
#[test]
fn with_ignore_attribute_002() {
unsafe {
assert!(BOOL_IGN_OK);
BOOL_IGN_OK = false;
}
}
static mut COUNTER_SHOULD_PANIC_OK: usize = 0;
#[deps(SHOULD_PANIC_OK_000)]
#[test]
fn with_should_panic_attribute_000() {
unsafe {
assert_eq!(0, COUNTER_SHOULD_PANIC_OK);
COUNTER_SHOULD_PANIC_OK = COUNTER_SHOULD_PANIC_OK + 1;
}
}
#[deps(SHOULD_PANIC_OK_001: SHOULD_PANIC_OK_000)]
#[should_panic]
#[test]
fn with_should_panic_attribute_001() {
thread::sleep(time::Duration::from_millis(250));
unsafe {
assert_eq!(1, COUNTER_SHOULD_PANIC_OK);
COUNTER_SHOULD_PANIC_OK = COUNTER_SHOULD_PANIC_OK + 1;
}
panic!("this is fine");
#[allow(unreachable_code)]
unsafe {
COUNTER_SHOULD_PANIC_OK = COUNTER_SHOULD_PANIC_OK + 1;
}
}
#[deps(SOULD_PANIC_OK_002: SHOULD_PANIC_OK_001)]
#[test]
fn with_should_panic_attribute_002() {
unsafe {
assert_eq!(2, COUNTER_SHOULD_PANIC_OK);
COUNTER_SHOULD_PANIC_OK = COUNTER_SHOULD_PANIC_OK + 1;
}
}
static mut BOOL_IGN_SHOULD_PANIC_OK: bool = false;
#[deps(IGN_SHOULD_PANIC_OK_000)]
#[test]
fn with_ignore_and_should_panic_attribute_000() {
thread::sleep(time::Duration::from_millis(250));
unsafe {
assert!(!BOOL_IGN_SHOULD_PANIC_OK);
BOOL_IGN_SHOULD_PANIC_OK = true;
}
}
#[deps(IGN_SHOULD_PANIC_OK_001: IGN_SHOULD_PANIC_OK_000)]
#[ignore]
#[should_panic]
#[test]
fn with_ignore_and_should_panic_attribute_001() {
unsafe {
BOOL_IGN_SHOULD_PANIC_OK = false;
}
}
#[deps(IGN_SHOULD_PANIC_OK_002: IGN_SHOULD_PANIC_OK_001)]
#[test]
fn with_ignore_and_should_panic_attribute_002() {
unsafe {
assert!(BOOL_IGN_SHOULD_PANIC_OK);
BOOL_IGN_SHOULD_PANIC_OK = false;
}
}
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::any::Any;
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::sync::Arc;
use common_exception::Result;
use common_expression::BlockMetaInfo;
use common_expression::BlockMetaInfoDowncast;
use common_expression::DataBlock;
use common_pipeline_core::processors::port::InputPort;
use common_pipeline_core::processors::port::OutputPort;
use common_pipeline_core::processors::processor::Event;
use common_pipeline_core::processors::Processor;
pub trait AccumulatingTransform: Send {
const NAME: &'static str;
fn transform(&mut self, data: DataBlock) -> Result<Vec<DataBlock>>;
fn on_finish(&mut self, _output: bool) -> Result<Vec<DataBlock>> {
Ok(vec![])
}
}
pub struct AccumulatingTransformer<T: AccumulatingTransform + 'static> {
inner: T,
input: Arc<InputPort>,
output: Arc<OutputPort>,
called_on_finish: bool,
input_data: Option<DataBlock>,
output_data: VecDeque<DataBlock>,
}
impl<T: AccumulatingTransform + 'static> AccumulatingTransformer<T> {
pub fn create(input: Arc<InputPort>, output: Arc<OutputPort>, inner: T) -> Box<dyn Processor> {
Box::new(Self {
inner,
input,
output,
input_data: None,
output_data: VecDeque::with_capacity(1),
called_on_finish: false,
})
}
}
impl<T: AccumulatingTransform + 'static> Drop for AccumulatingTransformer<T> {
fn drop(&mut self) {
if !self.called_on_finish {
self.inner.on_finish(false).unwrap();
}
}
}
#[async_trait::async_trait]
impl<T: AccumulatingTransform + 'static> Processor for AccumulatingTransformer<T> {
fn name(&self) -> String {
String::from(T::NAME)
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn event(&mut self) -> Result<Event> {
if self.output.is_finished() {
if !self.called_on_finish {
return Ok(Event::Sync);
}
self.input.finish();
return Ok(Event::Finished);
}
if !self.output.can_push() {
self.input.set_not_need_data();
return Ok(Event::NeedConsume);
}
if let Some(data_block) = self.output_data.pop_front() {
self.output.push_data(Ok(data_block));
return Ok(Event::NeedConsume);
}
if self.input_data.is_some() {
return Ok(Event::Sync);
}
if self.input.has_data() {
self.input_data = Some(self.input.pull_data().unwrap()?);
return Ok(Event::Sync);
}
if self.input.is_finished() {
return match !self.called_on_finish {
true => Ok(Event::Sync),
false => {
self.output.finish();
Ok(Event::Finished)
}
};
}
self.input.set_need_data();
Ok(Event::NeedData)
}
fn process(&mut self) -> Result<()> {
if let Some(data_block) = self.input_data.take() {
self.output_data.extend(self.inner.transform(data_block)?);
return Ok(());
}
if !self.called_on_finish {
self.called_on_finish = true;
self.output_data.extend(self.inner.on_finish(true)?);
}
Ok(())
}
}
pub trait BlockMetaAccumulatingTransform<B: BlockMetaInfo>: Send + 'static {
const NAME: &'static str;
fn transform(&mut self, data: B) -> Result<Option<DataBlock>>;
fn on_finish(&mut self, _output: bool) -> Result<Option<DataBlock>> {
Ok(None)
}
}
pub struct BlockMetaAccumulatingTransformer<B: BlockMetaInfo, T: BlockMetaAccumulatingTransform<B>>
{
inner: T,
input: Arc<InputPort>,
output: Arc<OutputPort>,
called_on_finish: bool,
input_data: Option<DataBlock>,
output_data: Option<DataBlock>,
_phantom_data: PhantomData<B>,
}
impl<B: BlockMetaInfo, T: BlockMetaAccumulatingTransform<B>>
BlockMetaAccumulatingTransformer<B, T>
{
pub fn create(input: Arc<InputPort>, output: Arc<OutputPort>, inner: T) -> Box<dyn Processor> {
Box::new(Self {
inner,
input,
output,
input_data: None,
output_data: None,
called_on_finish: false,
_phantom_data: Default::default(),
})
}
}
impl<B: BlockMetaInfo, T: BlockMetaAccumulatingTransform<B>> Drop
for BlockMetaAccumulatingTransformer<B, T>
{
fn drop(&mut self) {
if !self.called_on_finish {
self.inner.on_finish(false).unwrap();
}
}
}
#[async_trait::async_trait]
impl<B: BlockMetaInfo, T: BlockMetaAccumulatingTransform<B>> Processor
for BlockMetaAccumulatingTransformer<B, T>
{
fn name(&self) -> String {
String::from(T::NAME)
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn event(&mut self) -> Result<Event> {
if self.output.is_finished() {
if !self.called_on_finish {
return Ok(Event::Sync);
}
self.input.finish();
return Ok(Event::Finished);
}
if !self.output.can_push() {
self.input.set_not_need_data();
return Ok(Event::NeedConsume);
}
if let Some(data_block) = self.output_data.take() {
self.output.push_data(Ok(data_block));
return Ok(Event::NeedConsume);
}
if self.input_data.is_some() {
return Ok(Event::Sync);
}
if self.input.has_data() {
self.input_data = Some(self.input.pull_data().unwrap()?);
return Ok(Event::Sync);
}
if self.input.is_finished() {
return match !self.called_on_finish {
true => Ok(Event::Sync),
false => {
self.output.finish();
Ok(Event::Finished)
}
};
}
self.input.set_need_data();
Ok(Event::NeedData)
}
fn process(&mut self) -> Result<()> {
if let Some(mut data_block) = self.input_data.take() {
debug_assert!(data_block.is_empty());
if let Some(block_meta) = data_block.take_meta() {
if let Some(block_meta) = B::downcast_from(block_meta) {
self.output_data = self.inner.transform(block_meta)?;
}
}
return Ok(());
}
if !self.called_on_finish {
self.called_on_finish = true;
self.output_data = self.inner.on_finish(true)?;
}
Ok(())
}
}
|
pub fn is_prime(n: usize) -> bool {
if n == 0 {
return false;
} else if n == 1 {
return false;
} else if n == 2 {
return true;
}
if n % 2 == 0 {
return false;
}
for i in 3..n {
if n < i * i {
break;
}
if n % i == 0 {
return false;
}
}
true
}
#[test]
fn is_prime_test() {
let res1 = is_prime(0);
assert_eq!(res1, false);
let res2 = is_prime(2);
assert_eq!(res2, true);
let res3 = is_prime(20);
assert_eq!(res3, false);
let res4 = is_prime(43);
assert_eq!(res4, true);
}
pub fn prime_list(n: usize) -> Vec<usize> {
let mut ret = vec![];
if n == 0 || n == 1 {
return ret;
}
let mut v = vec![true; n + 1];
v[0] = false;
v[1] = false;
for i in 2..=n {
if v[i] == true {
ret.push(i);
let mut j = i * 2;
while j <= n {
v[j] = false;
j += i;
}
}
}
ret
}
#[test]
fn prime_list_test() {
let res1 = prime_list(0);
assert_eq!(res1, &[]);
let res2 = prime_list(2);
assert_eq!(res2, &[2]);
let res3 = prime_list(5);
assert_eq!(res3, &[2, 3, 5]);
let res4 = prime_list(6);
assert_eq!(res4, &[2, 3, 5]);
let res5 = prime_list(7);
assert_eq!(res5, &[2, 3, 5, 7]);
}
|
use std::fmt::{self, Display, Formatter};
use crate::mssql::protocol::type_info::{DataType, TypeInfo as ProtocolTypeInfo};
use crate::type_info::TypeInfo;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
pub struct MssqlTypeInfo(pub(crate) ProtocolTypeInfo);
impl TypeInfo for MssqlTypeInfo {
fn is_null(&self) -> bool {
matches!(self.0.ty, DataType::Null)
}
fn name(&self) -> &str {
self.0.name()
}
}
impl Display for MssqlTypeInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.pad(self.name())
}
}
#[cfg(feature = "any")]
impl From<MssqlTypeInfo> for crate::any::AnyTypeInfo {
#[inline]
fn from(ty: MssqlTypeInfo) -> Self {
crate::any::AnyTypeInfo(crate::any::type_info::AnyTypeInfoKind::Mssql(ty))
}
}
|
#[doc = "Reader of register MCS"]
pub type R = crate::R<u32, super::MCS>;
#[doc = "Writer for register MCS"]
pub type W = crate::W<u32, super::MCS>;
#[doc = "Register MCS `reset()`'s with value 0"]
impl crate::ResetValue for super::MCS {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `RUN`"]
pub type RUN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RUN`"]
pub struct RUN_W<'a> {
w: &'a mut W,
}
impl<'a> RUN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `BUSY`"]
pub type BUSY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BUSY`"]
pub struct BUSY_W<'a> {
w: &'a mut W,
}
impl<'a> BUSY_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `ERROR`"]
pub type ERROR_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ERROR`"]
pub struct ERROR_W<'a> {
w: &'a mut W,
}
impl<'a> ERROR_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `START`"]
pub type START_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `START`"]
pub struct START_W<'a> {
w: &'a mut W,
}
impl<'a> START_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `ADRACK`"]
pub type ADRACK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ADRACK`"]
pub struct ADRACK_W<'a> {
w: &'a mut W,
}
impl<'a> ADRACK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `STOP`"]
pub type STOP_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `STOP`"]
pub struct STOP_W<'a> {
w: &'a mut W,
}
impl<'a> STOP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `ACK`"]
pub type ACK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ACK`"]
pub struct ACK_W<'a> {
w: &'a mut W,
}
impl<'a> ACK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `DATACK`"]
pub type DATACK_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DATACK`"]
pub struct DATACK_W<'a> {
w: &'a mut W,
}
impl<'a> DATACK_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `ARBLST`"]
pub type ARBLST_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ARBLST`"]
pub struct ARBLST_W<'a> {
w: &'a mut W,
}
impl<'a> ARBLST_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `HS`"]
pub type HS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HS`"]
pub struct HS_W<'a> {
w: &'a mut W,
}
impl<'a> HS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `IDLE`"]
pub type IDLE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `IDLE`"]
pub struct IDLE_W<'a> {
w: &'a mut W,
}
impl<'a> IDLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Reader of field `BUSBSY`"]
pub type BUSBSY_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BUSBSY`"]
pub struct BUSBSY_W<'a> {
w: &'a mut W,
}
impl<'a> BUSBSY_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `CLKTO`"]
pub type CLKTO_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CLKTO`"]
pub struct CLKTO_W<'a> {
w: &'a mut W,
}
impl<'a> CLKTO_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 0 - I2C Master Enable"]
#[inline(always)]
pub fn run(&self) -> RUN_R {
RUN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 0 - I2C Busy"]
#[inline(always)]
pub fn busy(&self) -> BUSY_R {
BUSY_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Error"]
#[inline(always)]
pub fn error(&self) -> ERROR_R {
ERROR_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 1 - Generate START"]
#[inline(always)]
pub fn start(&self) -> START_R {
START_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Acknowledge Address"]
#[inline(always)]
pub fn adrack(&self) -> ADRACK_R {
ADRACK_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 2 - Generate STOP"]
#[inline(always)]
pub fn stop(&self) -> STOP_R {
STOP_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Data Acknowledge Enable"]
#[inline(always)]
pub fn ack(&self) -> ACK_R {
ACK_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 3 - Acknowledge Data"]
#[inline(always)]
pub fn datack(&self) -> DATACK_R {
DATACK_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Arbitration Lost"]
#[inline(always)]
pub fn arblst(&self) -> ARBLST_R {
ARBLST_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 4 - High-Speed Enable"]
#[inline(always)]
pub fn hs(&self) -> HS_R {
HS_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - I2C Idle"]
#[inline(always)]
pub fn idle(&self) -> IDLE_R {
IDLE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Bus Busy"]
#[inline(always)]
pub fn busbsy(&self) -> BUSBSY_R {
BUSBSY_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Clock Timeout Error"]
#[inline(always)]
pub fn clkto(&self) -> CLKTO_R {
CLKTO_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - I2C Master Enable"]
#[inline(always)]
pub fn run(&mut self) -> RUN_W {
RUN_W { w: self }
}
#[doc = "Bit 0 - I2C Busy"]
#[inline(always)]
pub fn busy(&mut self) -> BUSY_W {
BUSY_W { w: self }
}
#[doc = "Bit 1 - Error"]
#[inline(always)]
pub fn error(&mut self) -> ERROR_W {
ERROR_W { w: self }
}
#[doc = "Bit 1 - Generate START"]
#[inline(always)]
pub fn start(&mut self) -> START_W {
START_W { w: self }
}
#[doc = "Bit 2 - Acknowledge Address"]
#[inline(always)]
pub fn adrack(&mut self) -> ADRACK_W {
ADRACK_W { w: self }
}
#[doc = "Bit 2 - Generate STOP"]
#[inline(always)]
pub fn stop(&mut self) -> STOP_W {
STOP_W { w: self }
}
#[doc = "Bit 3 - Data Acknowledge Enable"]
#[inline(always)]
pub fn ack(&mut self) -> ACK_W {
ACK_W { w: self }
}
#[doc = "Bit 3 - Acknowledge Data"]
#[inline(always)]
pub fn datack(&mut self) -> DATACK_W {
DATACK_W { w: self }
}
#[doc = "Bit 4 - Arbitration Lost"]
#[inline(always)]
pub fn arblst(&mut self) -> ARBLST_W {
ARBLST_W { w: self }
}
#[doc = "Bit 4 - High-Speed Enable"]
#[inline(always)]
pub fn hs(&mut self) -> HS_W {
HS_W { w: self }
}
#[doc = "Bit 5 - I2C Idle"]
#[inline(always)]
pub fn idle(&mut self) -> IDLE_W {
IDLE_W { w: self }
}
#[doc = "Bit 6 - Bus Busy"]
#[inline(always)]
pub fn busbsy(&mut self) -> BUSBSY_W {
BUSBSY_W { w: self }
}
#[doc = "Bit 7 - Clock Timeout Error"]
#[inline(always)]
pub fn clkto(&mut self) -> CLKTO_W {
CLKTO_W { w: self }
}
}
|
pub mod domain;
pub mod stat;
pub mod user;
|
/*
给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。
示例 :
输入: [1,2,1,3,2,5]
输出: [3,5]
注意:
结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。
你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
impl Solution {
pub fn single_number(nums: Vec<i32>) -> Vec<i32> {
let xor_res = nums.iter().fold(0, |a, b| a ^ *b);
let mut n = 0;
for i in 0..32 {
if xor_res & (1 << i) != 0 {
n = 1 << i;
break;
}
}
let mut a = 0;
let mut b = 0;
for num in nums.into_iter() {
if num & n == 0 {
a ^= num;
} else {
b ^= num;
}
}
vec![a, b]
}
}
fn main() {
let res = Solution::single_number(vec![3, 5, 1, 3, 2, 5]);
dbg!(res);
}
struct Solution {}
|
// Copyright 2017 Dasein Phaos aka. Luxko
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Types to describe a heap
/// description of a heap
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct HeapDesc {
/// heap size in bytes
pub size: u64,
/// heap properties
pub properties: HeapProperties,
/// alignment
pub alignment: HeapAlignment,
/// misc flags
pub flags: HeapFlags,
}
impl HeapDesc{
/// construction
#[inline]
pub fn new(size: u64, properties: HeapProperties, flags: HeapFlags) -> HeapDesc {
HeapDesc{
size, properties, flags, alignment: Default::default(),
}
}
}
/// describes heap properties
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct HeapProperties {
/// heap type
pub heap_type: HeapType,
/// cpu page property
pub page: PageProperty,
/// memory pool preference
pub pool_preference: MemoryPoolPreference,
pub creation_node_mask: u32,
pub visible_node_mask: u32,
}
impl HeapProperties {
#[inline]
pub fn new(heap_type: HeapType) -> HeapProperties {
HeapProperties{
heap_type,
page: Default::default(),
pool_preference: Default::default(),
creation_node_mask: 0,
visible_node_mask: 0,
}
}
}
impl Default for HeapProperties {
#[inline]
fn default() -> Self {
HeapProperties::new(Default::default())
}
}
bitflags!{
/// [heap type](https://msdn.microsoft.com/library/windows/desktop/dn770374(v=vs.85).aspx).
#[repr(C)]
pub struct HeapType: u32 {
/// GPU RW, no CPU access. This is the default heap type.
const DEFAULT = 1;
/// Optimal for CPU write.
/// Best for CPU write-once, GPU read-once data.
/// Resources in this heap must be created with `GENERATE_READ` state, and
/// cannot be changed away.
const UPLOAD = 2;
/// Optimal for CPU write.
/// Best for GPU write-once, CPU readable data.
/// Resources in this heap must be created with `COPY_DEST` state, and
/// cannot be changed away from this.
const READBACK = 3;
/// Custom heap for advanced usage.
const CUSTOM = 4;
}
}
impl Default for HeapType {
#[inline]
fn default() -> HeapType {
HeapType::DEFAULT
}
}
bitflags!{
/// cpu page properties.
#[repr(C)]
pub struct PageProperty: u32 {
/// The default cpu page property.
const UNKNOWN = 0;
/// The CPU cannot access the heap, thus no property available.
const NOT_AVAILABLE = 1;
const WRITE_COMBINE = 2;
const WRITE_BACK = 3;
}
}
impl Default for PageProperty {
#[inline]
fn default() -> PageProperty {
PageProperty::UNKNOWN
}
}
bitflags!{
/// memory pool preference. [more info](https://msdn.microsoft.com/library/windows/desktop/dn770381(v=vs.85).aspx)
#[repr(C)]
pub struct MemoryPoolPreference: u32 {
/// The default pool preference.
const UNKNOWN = 0;
const L0 = 1;
const L1 = 2;
}
}
impl Default for MemoryPoolPreference {
#[inline]
fn default() -> MemoryPoolPreference {
MemoryPoolPreference::UNKNOWN
}
}
bitflags!{
/// heap alignment
#[repr(C)]
pub struct HeapAlignment: u64 {
/// alias for 64kb, the default.
const DEFAULT = 0;
/// 64kb aligned.
const DEFAULT_RESOURCE_PLACEMENT = ::winapi::D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64;
/// 4mb aligned. MSAA resource heap must use this alignment.
const DEFAULT_MSAA_RESOURCE_PLACEMENT = ::winapi::D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT as u64;
}
}
impl Default for HeapAlignment {
#[inline]
fn default() -> Self {
HeapAlignment::DEFAULT
}
}
bitflags!{
/// misc heap options. [more info](https://msdn.microsoft.com/library/windows/desktop/dn986730(v=vs.85).aspx)
#[repr(C)]
pub struct HeapFlags: u32 {
/// The default, no options specified.
const NONE = 0;
/// a [shared heap](https://msdn.microsoft.com/library/windows/desktop/mt186623(v=vs.85).aspx)
const SHARED = 0x1;
/// the heap isn't allowed to contain buffers
const DENY_BUFFERS = 0x4;
/// the heap can contain swapchain surfaces
const ALLOW_DISPLAY = 0x8;
/// the heap can be shored across adapters
const SHARED_CROSS_ADAPTER = 0x20;
/// the heap can't store render target or depth stencil textures
const DENY_RT_DS_TEXTURES = 0x40;
/// the heap can't contain textures without `ALLOW_RENDER_TARGET` or `ALLOW_DEPTH_STENCIL` flags
const DENY_NON_RT_DS_TEXTURES = 0x80;
/// unsupported
const HARDWARE_PROTECTED = 0x100;
/// allow tools to support `MEM_WRITE_WATCH`
const ALLOW_WRITE_WATCH = 0x200;
const ALLOW_ALL_BUFFERS_AND_TEXTURES = 0;
const ALLOW_ONLY_BUFFERS = 0xc0;
const ALLOW_ONLY_NON_RT_DS_TEXTURES = 0x44;
const ALLOW_ONLY_RT_DS_TEXTURES = 0x84;
}
}
impl Default for HeapFlags {
#[inline]
fn default() -> Self {
HeapFlags::NONE
}
}
|
use serde::Deserialize;
#[derive(Deserialize, Debug, PartialEq)]
pub struct Mash {}
|
//! Futures
//!
//! This module contains the `Future` trait and a number of adaptors for this
//! trait. See the crate docs, and the docs for `Future`, for full detail.
use core::fmt;
use core::result;
// Primitive futures
mod empty;
mod lazy;
mod poll_fn;
#[path = "result.rs"]
mod result_;
mod loop_fn;
mod option;
pub use self::empty::{empty, Empty};
pub use self::lazy::{lazy, Lazy};
pub use self::poll_fn::{poll_fn, PollFn};
pub use self::result_::{result, ok, err, FutureResult};
pub use self::loop_fn::{loop_fn, Loop, LoopFn};
#[doc(hidden)]
#[deprecated(since = "0.1.4", note = "use `ok` instead")]
#[cfg(feature = "with-deprecated")]
pub use self::{ok as finished, Ok as Finished};
#[doc(hidden)]
#[deprecated(since = "0.1.4", note = "use `err` instead")]
#[cfg(feature = "with-deprecated")]
pub use self::{err as failed, Err as Failed};
#[doc(hidden)]
#[deprecated(since = "0.1.4", note = "use `result` instead")]
#[cfg(feature = "with-deprecated")]
pub use self::{result as done, FutureResult as Done};
#[doc(hidden)]
#[deprecated(since = "0.1.7", note = "use `FutureResult` instead")]
#[cfg(feature = "with-deprecated")]
pub use self::{FutureResult as Ok};
#[doc(hidden)]
#[deprecated(since = "0.1.7", note = "use `FutureResult` instead")]
#[cfg(feature = "with-deprecated")]
pub use self::{FutureResult as Err};
// combinators
mod and_then;
mod flatten;
mod flatten_stream;
mod fuse;
mod into_stream;
mod join;
mod map;
mod map_err;
mod from_err;
mod or_else;
mod select;
mod select2;
mod then;
mod either;
mod inspect;
// impl details
mod chain;
pub use self::and_then::AndThen;
pub use self::flatten::Flatten;
pub use self::flatten_stream::FlattenStream;
pub use self::fuse::Fuse;
pub use self::into_stream::IntoStream;
pub use self::join::{Join, Join3, Join4, Join5};
pub use self::map::Map;
pub use self::map_err::MapErr;
pub use self::from_err::FromErr;
pub use self::or_else::OrElse;
pub use self::select::{Select, SelectNext};
pub use self::select2::Select2;
pub use self::then::Then;
pub use self::either::Either;
pub use self::inspect::Inspect;
if_std! {
mod catch_unwind;
mod join_all;
mod select_all;
mod select_ok;
mod shared;
pub use self::catch_unwind::CatchUnwind;
pub use self::join_all::{join_all, JoinAll};
pub use self::select_all::{SelectAll, SelectAllNext, select_all};
pub use self::select_ok::{SelectOk, select_ok};
pub use self::shared::{Shared, SharedItem, SharedError};
#[doc(hidden)]
#[deprecated(since = "0.1.4", note = "use join_all instead")]
#[cfg(feature = "with-deprecated")]
pub use self::join_all::join_all as collect;
#[doc(hidden)]
#[deprecated(since = "0.1.4", note = "use JoinAll instead")]
#[cfg(feature = "with-deprecated")]
pub use self::join_all::JoinAll as Collect;
/// A type alias for `Box<Future + Send>`
#[doc(hidden)]
#[deprecated(note = "removed without replacement, recommended to use a \
local extension trait or function if needed, more \
details in https://github.com/rust-lang-nursery/futures-rs/issues/228")]
pub type BoxFuture<T, E> = ::std::boxed::Box<Future<Item = T, Error = E> + Send>;
impl<F: ?Sized + Future> Future for ::std::boxed::Box<F> {
type Item = F::Item;
type Error = F::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
(**self).poll()
}
}
}
use {Poll, stream};
/// Trait for types which are a placeholder of a value that may become
/// available at some later point in time.
///
/// In addition to the documentation here you can also find more information
/// about futures [online] at [https://tokio.rs](https://tokio.rs)
///
/// [online]: https://tokio.rs/docs/getting-started/futures/
///
/// Futures are used to provide a sentinel through which a value can be
/// referenced. They crucially allow chaining and composing operations through
/// consumption which allows expressing entire trees of computation as one
/// sentinel value.
///
/// The ergonomics and implementation of the `Future` trait are very similar to
/// the `Iterator` trait in that there is just one methods you need
/// to implement, but you get a whole lot of others for free as a result.
///
/// # The `poll` method
///
/// The core method of future, `poll`, is used to attempt to generate the value
/// of a `Future`. This method *does not block* but is allowed to inform the
/// caller that the value is not ready yet. Implementations of `poll` may
/// themselves do work to generate the value, but it's guaranteed that this will
/// never block the calling thread.
///
/// A key aspect of this method is that if the value is not yet available the
/// current task is scheduled to receive a notification when it's later ready to
/// be made available. This follows what's typically known as a "readiness" or
/// "pull" model where values are pulled out of futures on demand, and
/// otherwise a task is notified when a value might be ready to get pulled out.
///
/// The `poll` method is not intended to be called in general, but rather is
/// typically called in the context of a "task" which drives a future to
/// completion. For more information on this see the `task` module.
///
/// More information about the details of `poll` and the nitty-gritty of tasks
/// can be [found online at tokio.rs][poll-dox].
///
/// [poll-dox]: https://tokio.rs/docs/going-deeper-futures/futures-model/
///
/// # Combinators
///
/// Like iterators, futures provide a large number of combinators to work with
/// futures to express computations in a much more natural method than
/// scheduling a number of callbacks. For example the `map` method can change
/// a `Future<Item=T>` to a `Future<Item=U>` or an `and_then` combinator could
/// create a future after the first one is done and only be resolved when the
/// second is done.
///
/// Combinators act very similarly to the methods on the `Iterator` trait itself
/// or those on `Option` and `Result`. Like with iterators, the combinators are
/// zero-cost and don't impose any extra layers of indirection you wouldn't
/// otherwise have to write down.
///
/// More information about combinators can be found [on tokio.rs].
///
/// [on tokio.rs]: https://tokio.rs/docs/going-deeper-futures/futures-mechanics/
#[must_use = "futures do nothing unless polled"]
pub trait Future {
/// The type of value that this future will resolved with if it is
/// successful.
type Item;
/// The type of error that this future will resolve with if it fails in a
/// normal fashion.
type Error;
/// Query this future to see if its value has become available, registering
/// interest if it is not.
///
/// This function will check the internal state of the future and assess
/// whether the value is ready to be produced. Implementers of this function
/// should ensure that a call to this **never blocks** as event loops may
/// not work properly otherwise.
///
/// When a future is not ready yet, the `Async::NotReady` value will be
/// returned. In this situation the future will *also* register interest of
/// the current task in the value being produced. This is done by calling
/// `task::park` to retrieve a handle to the current `Task`. When the future
/// is then ready to make progress (e.g. it should be `poll`ed again) the
/// `unpark` method is called on the `Task`.
///
/// More information about the details of `poll` and the nitty-gritty of
/// tasks can be [found online at tokio.rs][poll-dox].
///
/// [poll-dox]: https://tokio.rs/docs/going-deeper-futures/futures-model/
///
/// # Runtime characteristics
///
/// This function, `poll`, is the primary method for 'making progress'
/// within a tree of futures. For example this method will be called
/// repeatedly as the internal state machine makes its various transitions.
/// Executors are responsible for ensuring that this function is called in
/// the right location (e.g. always on an I/O thread or not). Unless it is
/// otherwise arranged to be so, it should be ensured that **implementations
/// of this function finish very quickly**.
///
/// Returning quickly prevents unnecessarily clogging up threads and/or
/// event loops while a `poll` function call, for example, takes up compute
/// resources to perform some expensive computation. If it is known ahead
/// of time that a call to `poll` may end up taking awhile, the work should
/// be offloaded to a thread pool (or something similar) to ensure that
/// `poll` can return quickly.
///
/// Note that the `poll` function is not called repeatedly in a loop for
/// futures typically, but only whenever the future itself is ready. If
/// you're familiar with the `poll(2)` or `select(2)` syscalls on Unix
/// it's worth noting that futures typically do *not* suffer the same
/// problems of "all wakeups must poll all events". Futures have enough
/// support for only polling futures which cause a wakeup.
///
/// # Return value
///
/// This function returns `Async::NotReady` if the future is not ready yet,
/// `Err` if the future is finished but resolved to an error, or
/// `Async::Ready` with the result of this future if it's finished
/// successfully. Once a future has finished it is considered a contract
/// error to continue polling the future.
///
/// If `NotReady` is returned, then the future will internally register
/// interest in the value being produced for the current task (through
/// `task::park`). In other words, the current task will receive a
/// notification (through the `unpark` method) once the value is ready to be
/// produced or the future can make progress.
///
/// Note that if `NotReady` is returned it only means that *this* task will
/// receive a notification. Historical calls to `poll` with different tasks
/// will not receive notifications. In other words, implementers of the
/// `Future` trait need not store a queue of tasks to notify, but only the
/// last task that called this method. Alternatively callers of this method
/// can only rely on the most recent task which call `poll` being notified
/// when a future is ready.
///
/// # Panics
///
/// Once a future has completed (returned `Ready` or `Err` from `poll`),
/// then any future calls to `poll` may panic, block forever, or otherwise
/// cause wrong behavior. The `Future` trait itself provides no guarantees
/// about the behavior of `poll` after a future has completed.
///
/// Callers who may call `poll` too many times may want to consider using
/// the `fuse` adaptor which defines the behavior of `poll`, but comes with
/// a little bit of extra cost.
///
/// Additionally, calls to `poll` must always be made from within the
/// context of a task. If a current task is not set then this method will
/// likely panic.
///
/// # Errors
///
/// This future may have failed to finish the computation, in which case
/// the `Err` variant will be returned with an appropriate payload of an
/// error.
fn poll(&mut self) -> Poll<Self::Item, Self::Error>;
/// Block the current thread until this future is resolved.
///
/// This method will consume ownership of this future, driving it to
/// completion via `poll` and blocking the current thread while it's waiting
/// for the value to become available. Once the future is resolved the
/// result of this future is returned.
///
/// > **Note:** This method is not appropriate to call on event loops or
/// > similar I/O situations because it will prevent the event
/// > loop from making progress (this blocks the thread). This
/// > method should only be called when it's guaranteed that the
/// > blocking work associated with this future will be completed
/// > by another thread.
///
/// This method is only available when the `use_std` feature of this
/// library is activated, and it is activated by default.
///
/// # Panics
///
/// This function does not attempt to catch panics. If the `poll` function
/// of this future panics, panics will be propagated to the caller.
#[cfg(feature = "use_std")]
fn wait(self) -> result::Result<Self::Item, Self::Error>
where Self: Sized
{
::executor::spawn(self).wait_future()
}
/// Convenience function for turning this future into a trait object which
/// is also `Send`.
///
/// This simply avoids the need to write `Box::new` and can often help with
/// type inference as well by always returning a trait object. Note that
/// this method requires the `Send` bound and returns a `BoxFuture`, which
/// also encodes this. If you'd like to create a `Box<Future>` without the
/// `Send` bound, then the `Box::new` function can be used instead.
///
/// This method is only available when the `use_std` feature of this
/// library is activated, and it is activated by default.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future::{BoxFuture, result};
///
/// let a: BoxFuture<i32, i32> = result(Ok(1)).boxed();
/// ```
#[cfg(feature = "use_std")]
#[doc(hidden)]
#[deprecated(note = "removed without replacement, recommended to use a \
local extension trait or function if needed, more \
details in https://github.com/rust-lang-nursery/futures-rs/issues/228")]
#[allow(deprecated)]
fn boxed(self) -> BoxFuture<Self::Item, Self::Error>
where Self: Sized + Send + 'static
{
::std::boxed::Box::new(self)
}
/// Map this future's result to a different type, returning a new future of
/// the resulting type.
///
/// This function is similar to the `Option::map` or `Iterator::map` where
/// it will change the type of the underlying future. This is useful to
/// chain along a computation once a future has been resolved.
///
/// The closure provided will only be called if this future is resolved
/// successfully. If this future returns an error, panics, or is dropped,
/// then the closure provided will never be invoked.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it, similar to the existing `map` methods in the
/// standard library.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let future = future::ok::<u32, u32>(1);
/// let new_future = future.map(|x| x + 3);
/// assert_eq!(new_future.wait(), Ok(4));
/// ```
///
/// Calling `map` on an errored `Future` has no effect:
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let future = future::err::<u32, u32>(1);
/// let new_future = future.map(|x| x + 3);
/// assert_eq!(new_future.wait(), Err(1));
/// ```
fn map<F, U>(self, f: F) -> Map<Self, F>
where F: FnOnce(Self::Item) -> U,
Self: Sized,
{
assert_future::<U, Self::Error, _>(map::new(self, f))
}
/// Map this future's error to a different error, returning a new future.
///
/// This function is similar to the `Result::map_err` where it will change
/// the error type of the underlying future. This is useful for example to
/// ensure that futures have the same error type when used with combinators
/// like `select` and `join`.
///
/// The closure provided will only be called if this future is resolved
/// with an error. If this future returns a success, panics, or is
/// dropped, then the closure provided will never be invoked.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
///
/// # Examples
///
/// ```
/// use futures::future::*;
///
/// let future = err::<u32, u32>(1);
/// let new_future = future.map_err(|x| x + 3);
/// assert_eq!(new_future.wait(), Err(4));
/// ```
///
/// Calling `map_err` on a successful `Future` has no effect:
///
/// ```
/// use futures::future::*;
///
/// let future = ok::<u32, u32>(1);
/// let new_future = future.map_err(|x| x + 3);
/// assert_eq!(new_future.wait(), Ok(1));
/// ```
fn map_err<F, E>(self, f: F) -> MapErr<Self, F>
where F: FnOnce(Self::Error) -> E,
Self: Sized,
{
assert_future::<Self::Item, E, _>(map_err::new(self, f))
}
/// Map this future's error to any error implementing `From` for
/// this future's `Error`, returning a new future.
///
/// This function does for futures what `try!` does for `Result`,
/// by letting the compiler infer the type of the resulting error.
/// Just as `map_err` above, this is useful for example to ensure
/// that futures have the same error type when used with
/// combinators like `select` and `join`.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let future_with_err_u8 = future::err::<(), u8>(1);
/// let future_with_err_u32 = future_with_err_u8.from_err::<u32>();
/// ```
fn from_err<E:From<Self::Error>>(self) -> FromErr<Self, E>
where Self: Sized,
{
assert_future::<Self::Item, E, _>(from_err::new(self))
}
/// Chain on a computation for when a future finished, passing the result of
/// the future to the provided closure `f`.
///
/// This function can be used to ensure a computation runs regardless of
/// the conclusion of the future. The closure provided will be yielded a
/// `Result` once the future is complete.
///
/// The returned value of the closure must implement the `IntoFuture` trait
/// and can represent some more work to be done before the composed future
/// is finished. Note that the `Result` type implements the `IntoFuture`
/// trait so it is possible to simply alter the `Result` yielded to the
/// closure and return it.
///
/// If this future is dropped or panics then the closure `f` will not be
/// run.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let future_of_1 = future::ok::<u32, u32>(1);
/// let future_of_4 = future_of_1.then(|x| {
/// x.map(|y| y + 3)
/// });
///
/// let future_of_err_1 = future::err::<u32, u32>(1);
/// let future_of_4 = future_of_err_1.then(|x| {
/// match x {
/// Ok(_) => panic!("expected an error"),
/// Err(y) => future::ok::<u32, u32>(y + 3),
/// }
/// });
/// ```
fn then<F, B>(self, f: F) -> Then<Self, B, F>
where F: FnOnce(result::Result<Self::Item, Self::Error>) -> B,
B: IntoFuture,
Self: Sized,
{
assert_future::<B::Item, B::Error, _>(then::new(self, f))
}
/// Execute another future after this one has resolved successfully.
///
/// This function can be used to chain two futures together and ensure that
/// the final future isn't resolved until both have finished. The closure
/// provided is yielded the successful result of this future and returns
/// another value which can be converted into a future.
///
/// Note that because `Result` implements the `IntoFuture` trait this method
/// can also be useful for chaining fallible and serial computations onto
/// the end of one future.
///
/// If this future is dropped, panics, or completes with an error then the
/// provided closure `f` is never called.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future::{self, FutureResult};
///
/// let future_of_1 = future::ok::<u32, u32>(1);
/// let future_of_4 = future_of_1.and_then(|x| {
/// Ok(x + 3)
/// });
///
/// let future_of_err_1 = future::err::<u32, u32>(1);
/// future_of_err_1.and_then(|_| -> FutureResult<u32, u32> {
/// panic!("should not be called in case of an error");
/// });
/// ```
fn and_then<F, B>(self, f: F) -> AndThen<Self, B, F>
where F: FnOnce(Self::Item) -> B,
B: IntoFuture<Error = Self::Error>,
Self: Sized,
{
assert_future::<B::Item, Self::Error, _>(and_then::new(self, f))
}
/// Execute another future if this one resolves with an error.
///
/// Return a future that passes along this future's value if it succeeds,
/// and otherwise passes the error to the closure `f` and waits for the
/// future it returns. The closure may also simply return a value that can
/// be converted into a future.
///
/// Note that because `Result` implements the `IntoFuture` trait this method
/// can also be useful for chaining together fallback computations, where
/// when one fails, the next is attempted.
///
/// If this future is dropped, panics, or completes successfully then the
/// provided closure `f` is never called.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future::{self, FutureResult};
///
/// let future_of_err_1 = future::err::<u32, u32>(1);
/// let future_of_4 = future_of_err_1.or_else(|x| -> Result<u32, u32> {
/// Ok(x + 3)
/// });
///
/// let future_of_1 = future::ok::<u32, u32>(1);
/// future_of_1.or_else(|_| -> FutureResult<u32, u32> {
/// panic!("should not be called in case of success");
/// });
/// ```
fn or_else<F, B>(self, f: F) -> OrElse<Self, B, F>
where F: FnOnce(Self::Error) -> B,
B: IntoFuture<Item = Self::Item>,
Self: Sized,
{
assert_future::<Self::Item, B::Error, _>(or_else::new(self, f))
}
/// Waits for either one of two futures to complete.
///
/// This function will return a new future which awaits for either this or
/// the `other` future to complete. The returned future will finish with
/// both the value resolved and a future representing the completion of the
/// other work. Both futures must have the same item and error type.
///
/// Note that this function consumes the receiving futures and returns a
/// wrapped version of them.
///
/// # Examples
///
/// ```no_run
/// use futures::prelude::*;
/// use futures::future;
/// use std::thread;
/// use std::time;
///
/// let future1 = future::lazy(|| {
/// thread::sleep(time::Duration::from_secs(5));
/// future::ok::<char, ()>('a')
/// });
///
/// let future2 = future::lazy(|| {
/// thread::sleep(time::Duration::from_secs(3));
/// future::ok::<char, ()>('b')
/// });
///
/// let (value, last_future) = future1.select(future2).wait().ok().unwrap();
/// assert_eq!(value, 'a');
/// assert_eq!(last_future.wait().unwrap(), 'b');
/// ```
///
/// A poor-man's `join` implemented on top of `select`:
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// fn join<A>(a: A, b: A) -> Box<Future<Item=(u32, u32), Error=u32>>
/// where A: Future<Item = u32, Error = u32> + 'static,
/// {
/// Box::new(a.select(b).then(|res| -> Box<Future<Item=_, Error=_>> {
/// match res {
/// Ok((a, b)) => Box::new(b.map(move |b| (a, b))),
/// Err((a, _)) => Box::new(future::err(a)),
/// }
/// }))
/// }
/// ```
fn select<B>(self, other: B) -> Select<Self, B::Future>
where B: IntoFuture<Item=Self::Item, Error=Self::Error>,
Self: Sized,
{
let f = select::new(self, other.into_future());
assert_future::<(Self::Item, SelectNext<Self, B::Future>),
(Self::Error, SelectNext<Self, B::Future>), _>(f)
}
/// Waits for either one of two differently-typed futures to complete.
///
/// This function will return a new future which awaits for either this or
/// the `other` future to complete. The returned future will finish with
/// both the value resolved and a future representing the completion of the
/// other work.
///
/// Note that this function consumes the receiving futures and returns a
/// wrapped version of them.
///
/// Also note that if both this and the second future have the same
/// success/error type you can use the `Either::split` method to
/// conveniently extract out the value at the end.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future::{self, Either};
///
/// // A poor-man's join implemented on top of select2
///
/// fn join<A, B, E>(a: A, b: B) -> Box<Future<Item=(A::Item, B::Item), Error=E>>
/// where A: Future<Error = E> + 'static,
/// B: Future<Error = E> + 'static,
/// E: 'static,
/// {
/// Box::new(a.select2(b).then(|res| -> Box<Future<Item=_, Error=_>> {
/// match res {
/// Ok(Either::A((x, b))) => Box::new(b.map(move |y| (x, y))),
/// Ok(Either::B((y, a))) => Box::new(a.map(move |x| (x, y))),
/// Err(Either::A((e, _))) => Box::new(future::err(e)),
/// Err(Either::B((e, _))) => Box::new(future::err(e)),
/// }
/// }))
/// }
/// ```
fn select2<B>(self, other: B) -> Select2<Self, B::Future>
where B: IntoFuture, Self: Sized
{
select2::new(self, other.into_future())
}
/// Joins the result of two futures, waiting for them both to complete.
///
/// This function will return a new future which awaits both this and the
/// `other` future to complete. The returned future will finish with a tuple
/// of both results.
///
/// Both futures must have the same error type, and if either finishes with
/// an error then the other will be dropped and that error will be
/// returned.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let a = future::ok::<u32, u32>(1);
/// let b = future::ok::<u32, u32>(2);
/// let pair = a.join(b);
///
/// assert_eq!(pair.wait(), Ok((1, 2)));
/// ```
///
/// If one or both of the joined `Future`s is errored, the resulting
/// `Future` will be errored:
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let a = future::ok::<u32, u32>(1);
/// let b = future::err::<u32, u32>(2);
/// let pair = a.join(b);
///
/// assert_eq!(pair.wait(), Err(2));
/// ```
fn join<B>(self, other: B) -> Join<Self, B::Future>
where B: IntoFuture<Error=Self::Error>,
Self: Sized,
{
let f = join::new(self, other.into_future());
assert_future::<(Self::Item, B::Item), Self::Error, _>(f)
}
/// Same as `join`, but with more futures.
fn join3<B, C>(self, b: B, c: C) -> Join3<Self, B::Future, C::Future>
where B: IntoFuture<Error=Self::Error>,
C: IntoFuture<Error=Self::Error>,
Self: Sized,
{
join::new3(self, b.into_future(), c.into_future())
}
/// Same as `join`, but with more futures.
fn join4<B, C, D>(self, b: B, c: C, d: D)
-> Join4<Self, B::Future, C::Future, D::Future>
where B: IntoFuture<Error=Self::Error>,
C: IntoFuture<Error=Self::Error>,
D: IntoFuture<Error=Self::Error>,
Self: Sized,
{
join::new4(self, b.into_future(), c.into_future(), d.into_future())
}
/// Same as `join`, but with more futures.
fn join5<B, C, D, E>(self, b: B, c: C, d: D, e: E)
-> Join5<Self, B::Future, C::Future, D::Future, E::Future>
where B: IntoFuture<Error=Self::Error>,
C: IntoFuture<Error=Self::Error>,
D: IntoFuture<Error=Self::Error>,
E: IntoFuture<Error=Self::Error>,
Self: Sized,
{
join::new5(self, b.into_future(), c.into_future(), d.into_future(),
e.into_future())
}
/// Convert this future into a single element stream.
///
/// The returned stream contains single success if this future resolves to
/// success or single error if this future resolves into error.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let future = future::ok::<_, bool>(17);
/// let mut stream = future.into_stream();
/// assert_eq!(Ok(Async::Ready(Some(17))), stream.poll());
/// assert_eq!(Ok(Async::Ready(None)), stream.poll());
///
/// let future = future::err::<bool, _>(19);
/// let mut stream = future.into_stream();
/// assert_eq!(Err(19), stream.poll());
/// assert_eq!(Ok(Async::Ready(None)), stream.poll());
/// ```
fn into_stream(self) -> IntoStream<Self>
where Self: Sized
{
into_stream::new(self)
}
/// Flatten the execution of this future when the successful result of this
/// future is itself another future.
///
/// This can be useful when combining futures together to flatten the
/// computation out the final result. This method can only be called
/// when the successful result of this future itself implements the
/// `IntoFuture` trait and the error can be created from this future's error
/// type.
///
/// This method is roughly equivalent to `self.and_then(|x| x)`.
///
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let nested_future = future::ok::<_, u32>(future::ok::<u32, u32>(1));
/// let future = nested_future.flatten();
/// assert_eq!(future.wait(), Ok(1));
/// ```
///
/// Calling `flatten` on an errored `Future`, or if the inner `Future` is
/// errored, will result in an errored `Future`:
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let nested_future = future::ok::<_, u32>(future::err::<u32, u32>(1));
/// let future = nested_future.flatten();
/// assert_eq!(future.wait(), Err(1));
/// ```
fn flatten(self) -> Flatten<Self>
where Self::Item: IntoFuture,
<<Self as Future>::Item as IntoFuture>::Error:
From<<Self as Future>::Error>,
Self: Sized
{
let f = flatten::new(self);
assert_future::<<<Self as Future>::Item as IntoFuture>::Item,
<<Self as Future>::Item as IntoFuture>::Error,
_>(f)
}
/// Flatten the execution of this future when the successful result of this
/// future is a stream.
///
/// This can be useful when stream initialization is deferred, and it is
/// convenient to work with that stream as if stream was available at the
/// call site.
///
/// Note that this function consumes this future and returns a wrapped
/// version of it.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
/// use futures::stream;
///
/// let stream_items = vec![17, 18, 19];
/// let future_of_a_stream = future::ok::<_, bool>(stream::iter_ok(stream_items));
///
/// let stream = future_of_a_stream.flatten_stream();
///
/// let mut iter = stream.wait();
/// assert_eq!(Ok(17), iter.next().unwrap());
/// assert_eq!(Ok(18), iter.next().unwrap());
/// assert_eq!(Ok(19), iter.next().unwrap());
/// assert_eq!(None, iter.next());
/// ```
fn flatten_stream(self) -> FlattenStream<Self>
where <Self as Future>::Item: stream::Stream<Error=Self::Error>,
Self: Sized
{
flatten_stream::new(self)
}
/// Fuse a future such that `poll` will never again be called once it has
/// completed.
///
/// Currently once a future has returned `Ready` or `Err` from
/// `poll` any further calls could exhibit bad behavior such as blocking
/// forever, panicking, never returning, etc. If it is known that `poll`
/// may be called too often then this method can be used to ensure that it
/// has defined semantics.
///
/// Once a future has been `fuse`d and it returns a completion from `poll`,
/// then it will forever return `NotReady` from `poll` again (never
/// resolve). This, unlike the trait's `poll` method, is guaranteed.
///
/// This combinator will drop this future as soon as it's been completed to
/// ensure resources are reclaimed as soon as possible.
///
/// # Examples
///
/// ```rust
/// use futures::prelude::*;
/// use futures::future;
///
/// let mut future = future::ok::<i32, u32>(2);
/// assert_eq!(future.poll(), Ok(Async::Ready(2)));
///
/// // Normally, a call such as this would panic:
/// //future.poll();
///
/// // This, however, is guaranteed to not panic
/// let mut future = future::ok::<i32, u32>(2).fuse();
/// assert_eq!(future.poll(), Ok(Async::Ready(2)));
/// assert_eq!(future.poll(), Ok(Async::NotReady));
/// ```
fn fuse(self) -> Fuse<Self>
where Self: Sized
{
let f = fuse::new(self);
assert_future::<Self::Item, Self::Error, _>(f)
}
/// Do something with the item of a future, passing it on.
///
/// When using futures, you'll often chain several of them together.
/// While working on such code, you might want to check out what's happening at
/// various parts in the pipeline. To do that, insert a call to inspect().
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let future = future::ok::<u32, u32>(1);
/// let new_future = future.inspect(|&x| println!("about to resolve: {}", x));
/// assert_eq!(new_future.wait(), Ok(1));
/// ```
fn inspect<F>(self, f: F) -> Inspect<Self, F>
where F: FnOnce(&Self::Item) -> (),
Self: Sized,
{
assert_future::<Self::Item, Self::Error, _>(inspect::new(self, f))
}
/// Catches unwinding panics while polling the future.
///
/// In general, panics within a future can propagate all the way out to the
/// task level. This combinator makes it possible to halt unwinding within
/// the future itself. It's most commonly used within task executors. It's
/// not recommended to use this for error handling.
///
/// Note that this method requires the `UnwindSafe` bound from the standard
/// library. This isn't always applied automatically, and the standard
/// library provides an `AssertUnwindSafe` wrapper type to apply it
/// after-the fact. To assist using this method, the `Future` trait is also
/// implemented for `AssertUnwindSafe<F>` where `F` implements `Future`.
///
/// This method is only available when the `use_std` feature of this
/// library is activated, and it is activated by default.
///
/// # Examples
///
/// ```rust
/// use futures::prelude::*;
/// use futures::future::{self, FutureResult};
///
/// let mut future = future::ok::<i32, u32>(2);
/// assert!(future.catch_unwind().wait().is_ok());
///
/// let mut future = future::lazy(|| -> FutureResult<i32, u32> {
/// panic!();
/// future::ok::<i32, u32>(2)
/// });
/// assert!(future.catch_unwind().wait().is_err());
/// ```
#[cfg(feature = "use_std")]
fn catch_unwind(self) -> CatchUnwind<Self>
where Self: Sized + ::std::panic::UnwindSafe
{
catch_unwind::new(self)
}
/// Create a cloneable handle to this future where all handles will resolve
/// to the same result.
///
/// The shared() method provides a method to convert any future into a
/// cloneable future. It enables a future to be polled by multiple threads.
///
/// The returned `Shared` future resolves successfully with
/// `SharedItem<Self::Item>` or erroneously with `SharedError<Self::Error>`.
/// Both `SharedItem` and `SharedError` implements `Deref` to allow shared
/// access to the underlying result. Ownership of `Self::Item` and
/// `Self::Error` cannot currently be reclaimed.
///
/// This method is only available when the `use_std` feature of this
/// library is activated, and it is activated by default.
///
/// # Examples
///
/// ```
/// use futures::prelude::*;
/// use futures::future;
///
/// let future = future::ok::<_, bool>(6);
/// let shared1 = future.shared();
/// let shared2 = shared1.clone();
/// assert_eq!(6, *shared1.wait().unwrap());
/// assert_eq!(6, *shared2.wait().unwrap());
/// ```
///
/// ```
/// use std::thread;
/// use futures::prelude::*;
/// use futures::future;
///
/// let future = future::ok::<_, bool>(6);
/// let shared1 = future.shared();
/// let shared2 = shared1.clone();
/// let join_handle = thread::spawn(move || {
/// assert_eq!(6, *shared2.wait().unwrap());
/// });
/// assert_eq!(6, *shared1.wait().unwrap());
/// join_handle.join().unwrap();
/// ```
#[cfg(feature = "use_std")]
fn shared(self) -> Shared<Self>
where Self: Sized
{
shared::new(self)
}
}
impl<'a, F: ?Sized + Future> Future for &'a mut F {
type Item = F::Item;
type Error = F::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
(**self).poll()
}
}
// Just a helper function to ensure the futures we're returning all have the
// right implementations.
fn assert_future<A, B, F>(t: F) -> F
where F: Future<Item=A, Error=B>,
{
t
}
/// Class of types which can be converted into a future.
///
/// This trait is very similar to the `IntoIterator` trait and is intended to be
/// used in a very similar fashion.
pub trait IntoFuture {
/// The future that this type can be converted into.
type Future: Future<Item=Self::Item, Error=Self::Error>;
/// The item that the future may resolve with.
type Item;
/// The error that the future may resolve with.
type Error;
/// Consumes this object and produces a future.
fn into_future(self) -> Self::Future;
}
impl<F: Future> IntoFuture for F {
type Future = F;
type Item = F::Item;
type Error = F::Error;
fn into_future(self) -> F {
self
}
}
impl<T, E> IntoFuture for result::Result<T, E> {
type Future = FutureResult<T, E>;
type Item = T;
type Error = E;
fn into_future(self) -> FutureResult<T, E> {
result(self)
}
}
/// Asynchronous conversion from a type `T`.
///
/// This trait is analogous to `std::convert::From`, adapted to asynchronous
/// computation.
pub trait FutureFrom<T>: Sized {
/// The future for the conversion.
type Future: Future<Item=Self, Error=Self::Error>;
/// Possible errors during conversion.
type Error;
/// Consume the given value, beginning the conversion.
fn future_from(T) -> Self::Future;
}
/// A trait for types which can spawn fresh futures.
///
/// This trait is typically implemented for "executors", or those types which
/// can execute futures to completion. Futures passed to `Spawn::spawn`
/// typically get turned into a *task* and are then driven to completion.
///
/// On spawn, the executor takes ownership of the future and becomes responsible
/// to call `Future::poll()` whenever a readiness notification is raised.
pub trait Executor<F: Future<Item = (), Error = ()>> {
/// Spawns a future to run on this `Executor`, typically in the
/// "background".
///
/// This function will return immediately, and schedule the future `future`
/// to run on `self`. The details of scheduling and execution are left to
/// the implementations of `Executor`, but this is typically a primary point
/// for injecting concurrency in a futures-based system. Futures spawned
/// through this `execute` function tend to run concurrently while they're
/// waiting on events.
///
/// # Errors
///
/// Implementers of this trait are allowed to reject accepting this future
/// as well. This can happen for various reason such as:
///
/// * The executor is shut down
/// * The executor has run out of capacity to execute futures
///
/// The decision is left to the caller how to work with this form of error.
/// The error returned transfers ownership of the future back to the caller.
fn execute(&self, future: F) -> Result<(), ExecuteError<F>>;
}
/// Errors returned from the `Spawn::spawn` function.
pub struct ExecuteError<F> {
future: F,
kind: ExecuteErrorKind,
}
/// Kinds of errors that can be returned from the `Execute::spawn` function.
///
/// Executors which may not always be able to accept a future may return one of
/// these errors, indicating why it was unable to spawn a future.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ExecuteErrorKind {
/// This executor has shut down and will no longer accept new futures to
/// spawn.
Shutdown,
/// This executor has no more capacity to run more futures. Other futures
/// need to finish before this executor can accept another.
NoCapacity,
#[doc(hidden)]
__Nonexhaustive,
}
impl<F> ExecuteError<F> {
/// Create a new `ExecuteError`
pub fn new(kind: ExecuteErrorKind, future: F) -> ExecuteError<F> {
ExecuteError {
future: future,
kind: kind,
}
}
/// Returns the associated reason for the error
pub fn kind(&self) -> ExecuteErrorKind {
self.kind
}
/// Consumes self and returns the original future that was spawned.
pub fn into_future(self) -> F {
self.future
}
}
impl<F> fmt::Debug for ExecuteError<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
ExecuteErrorKind::Shutdown => "executor has shut down".fmt(f),
ExecuteErrorKind::NoCapacity => "executor has no more capacity".fmt(f),
ExecuteErrorKind::__Nonexhaustive => panic!(),
}
}
}
|
//! Provides types for fetching tool distributions into the Notion catalog.
mod error;
pub mod node;
pub mod yarn;
use catalog::Collection;
use notion_fail::Fallible;
use semver::Version;
use std::fs::File;
/// The result of a requested installation.
pub enum Fetched {
/// Indicates that the given tool was already installed.
Already(Version),
/// Indicates that the given tool was not already installed but has now been installed.
Now(Version),
}
impl Fetched {
/// Consumes this value and produces the installed version.
pub fn into_version(self) -> Version {
match self {
Fetched::Already(version) | Fetched::Now(version) => version,
}
}
/// Produces a reference to the installed version.
pub fn version(&self) -> &Version {
match self {
&Fetched::Already(ref version) | &Fetched::Now(ref version) => version,
}
}
}
pub trait Distro: Sized {
/// Provision a distribution from the public distributor (e.g. `https://nodejs.org`).
fn public(version: Version) -> Fallible<Self>;
/// Provision a distribution from a remote distributor.
fn remote(version: Version, url: &str) -> Fallible<Self>;
/// Provision a distribution from the filesystem.
fn cached(version: Version, file: File) -> Fallible<Self>;
/// Produces a reference to this distro's Tool version.
fn version(&self) -> &Version;
/// Fetches this version of the Tool. (It is left to the responsibility of the `Collection`
/// to update its state after fetching succeeds.)
fn fetch(self, catalog: &Collection<Self>) -> Fallible<Fetched>;
}
|
use num_bigint::BigInt;
use num_complex::Complex64;
use num_traits::ToPrimitive;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::num::Wrapping;
pub type PyHash = i64;
pub type PyUHash = u64;
/// Prime multiplier used in string and various other hashes.
pub const MULTIPLIER: PyHash = 1_000_003; // 0xf4243
/// Numeric hashes are based on reduction modulo the prime 2**_BITS - 1
pub const BITS: usize = 61;
pub const MODULUS: PyUHash = (1 << BITS) - 1;
pub const INF: PyHash = 314_159;
pub const NAN: PyHash = 0;
pub const IMAG: PyHash = MULTIPLIER;
pub const ALGO: &str = "siphasher13";
pub const HASH_BITS: usize = std::mem::size_of::<PyHash>() * 8;
// internally DefaultHasher uses 2 u64s as the seed, but
// that's not guaranteed to be consistent across Rust releases
// TODO: use something like the siphasher crate as our hash algorithm
pub const SEED_BITS: usize = std::mem::size_of::<PyHash>() * 2 * 8;
// pub const CUTOFF: usize = 7;
#[inline]
pub fn mod_int(value: i64) -> PyHash {
value % MODULUS as i64
}
pub fn hash_value<T: Hash + ?Sized>(data: &T) -> PyHash {
let mut hasher = DefaultHasher::new();
data.hash(&mut hasher);
mod_int(hasher.finish() as PyHash)
}
pub fn hash_float(value: f64) -> PyHash {
// cpython _Py_HashDouble
if !value.is_finite() {
return if value.is_infinite() {
if value > 0.0 {
INF
} else {
-INF
}
} else {
NAN
};
}
let frexp = super::float_ops::ufrexp(value);
// process 28 bits at a time; this should work well both for binary
// and hexadecimal floating point.
let mut m = frexp.0;
let mut e = frexp.1;
let mut x: PyUHash = 0;
while m != 0.0 {
x = ((x << 28) & MODULUS) | x >> (BITS - 28);
m *= 268_435_456.0; // 2**28
e -= 28;
let y = m as PyUHash; // pull out integer part
m -= y as f64;
x += y;
if x >= MODULUS {
x -= MODULUS;
}
}
// adjust for the exponent; first reduce it modulo BITS
const BITS32: i32 = BITS as i32;
e = if e >= 0 {
e % BITS32
} else {
BITS32 - 1 - ((-1 - e) % BITS32)
};
x = ((x << e) & MODULUS) | x >> (BITS32 - e);
x as PyHash * value.signum() as PyHash
}
pub fn hash_complex(value: &Complex64) -> PyHash {
let re_hash = hash_float(value.re);
let im_hash = hash_float(value.im);
let ret = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(IMAG);
ret.0
}
pub fn hash_iter<'a, T: 'a, I, F, E>(iter: I, hashf: F) -> Result<PyHash, E>
where
I: IntoIterator<Item = &'a T>,
F: Fn(&'a T) -> Result<PyHash, E>,
{
let mut hasher = DefaultHasher::new();
for element in iter {
let item_hash = hashf(element)?;
item_hash.hash(&mut hasher);
}
Ok(mod_int(hasher.finish() as PyHash))
}
pub fn hash_iter_unordered<'a, T: 'a, I, F, E>(iter: I, hashf: F) -> Result<PyHash, E>
where
I: IntoIterator<Item = &'a T>,
F: Fn(&'a T) -> Result<PyHash, E>,
{
let mut hash: PyHash = 0;
for element in iter {
let item_hash = hashf(element)?;
// xor is commutative and hash should be independent of order
hash ^= item_hash;
}
Ok(mod_int(hash))
}
pub fn hash_bigint(value: &BigInt) -> PyHash {
value.to_i64().map_or_else(
|| {
(value % MODULUS).to_i64().unwrap_or_else(||
// guaranteed to be safe by mod
unsafe { std::hint::unreachable_unchecked() })
},
mod_int,
)
}
pub fn hash_str(value: &str) -> PyHash {
hash_value(value.as_bytes())
}
|
extern crate proconio;
use proconio::input;
fn main() {
input! {
n: f64,
m: f64,
d: i64,
}
println!(
"{}",
if d == 0 {
1.0 / n * (m - 1.0)
} else {
(n - (d as f64)) * 2.0 / n / n * (m - 1.0)
}
);
}
|
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::vec::Vec;
use vtf::Error;
fn main() -> Result<(), Error> {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
panic!("Usage: info <path to vtf file>");
}
let path = Path::new(&args[1]);
let mut file = File::open(path)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let vtf = vtf::from_bytes(&mut buf)?;
println!("{:#?}", vtf.header);
Ok(())
}
|
mod receiver;
mod sender;
pub use self::{receiver::Receiver, sender::Sender};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.