text stringlengths 8 4.13M |
|---|
use super::{u256mod, ModulusTrait};
use super::super::bignum_u512::u512;
// Creation from unsigned integer values
// All types other that &u512 are handled by converting to &u512
impl<M: ModulusTrait> From<&u512> for u256mod<M> {
fn from(val: &u512) -> u256mod<M> {
return u256mod::<M> {
value: val % M::modulus(),
this_is_stupid_why: std::marker::PhantomData
};
}
}
impl<M: ModulusTrait> From<u8> for u256mod<M> { fn from(val: u8) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<&u8> for u256mod<M> { fn from(val: &u8) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<u16> for u256mod<M> { fn from(val: u16) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<&u16> for u256mod<M> { fn from(val: &u16) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<u32> for u256mod<M> { fn from(val: u32) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<&u32> for u256mod<M> { fn from(val: &u32) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<u64> for u256mod<M> { fn from(val: u64) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<&u64> for u256mod<M> { fn from(val: &u64) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<u128> for u256mod<M> { fn from(val: u128) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<&u128> for u256mod<M> { fn from(val: &u128) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
impl<M: ModulusTrait> From<u512> for u256mod<M> { fn from(val: u512) -> u256mod<M> { u256mod::from(&u512::from(val)) } }
// Creation from integer values
// All types other are handled by converting to i128
impl<M: ModulusTrait> From<i128> for u256mod<M> {
fn from(val: i128) -> u256mod<M> {
if val >= 0 {
return u256mod::from(val as u128);
}
// if val < 0 then calculate (0 - |val|) % M
// TODO - does this work when |val| > M ? - this shouldnt matter for Ed25519 probably
// For now lets panic!
let positive_val = u512::from(-val);
if positive_val >= M::modulus() {
panic!("This has not been implemented yet, negative values must be smaller than modulus");
}
return u256mod::from(u512::zero()) - u256mod::from(positive_val);
}
}
impl<M: ModulusTrait> From<i8> for u256mod<M> { fn from(val: i8) -> u256mod<M> { u256mod::from(val as i128) }}
impl<M: ModulusTrait> From<&i8> for u256mod<M> { fn from(val: &i8) -> u256mod<M> { u256mod::from(*val as i128) }}
impl<M: ModulusTrait> From<i16> for u256mod<M> { fn from(val: i16) -> u256mod<M> { u256mod::from(val as i128) }}
impl<M: ModulusTrait> From<&i16> for u256mod<M> { fn from(val: &i16) -> u256mod<M> { u256mod::from(*val as i128) }}
impl<M: ModulusTrait> From<i32> for u256mod<M> { fn from(val: i32) -> u256mod<M> { u256mod::from(val as i128) }}
impl<M: ModulusTrait> From<&i32> for u256mod<M> { fn from(val: &i32) -> u256mod<M> { u256mod::from(*val as i128) }}
impl<M: ModulusTrait> From<i64> for u256mod<M> { fn from(val: i64) -> u256mod<M> { u256mod::from(val as i128) }}
impl<M: ModulusTrait> From<&i64> for u256mod<M> { fn from(val: &i64) -> u256mod<M> { u256mod::from(*val as i128) }}
impl<M: ModulusTrait> From<&i128> for u256mod<M> { fn from(val: &i128) -> u256mod<M> { u256mod::from(*val as i128) }} |
mod generated;
pub use generated::*;
use std::fmt;
pub type drr_begin = dmu_replay_record__bindgen_ty_2_drr_begin;
pub type drr_end = dmu_replay_record__bindgen_ty_2_drr_end;
impl fmt::Debug for drr_begin {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
/*
pub struct drr_begin {
pub drr_magic: u64,
pub drr_versioninfo: u64,
pub drr_creation_time: u64,
pub drr_type: dmu_objset_type_t,
pub drr_flags: u32,
pub drr_toguid: u64,
pub drr_fromguid: u64,
pub drr_toname: [::std::os::raw::c_char; 256usize],
}
*/
let drr_toname = unsafe {
std::slice::from_raw_parts(
self.drr_toname[..].as_ptr() as *const u8,
self.drr_toname.len(),
)
};
let term = drr_toname
.iter()
.enumerate()
.filter_map(|(i, c)| if *c == 0 { Some(i) } else { None })
.next()
.expect("drr_toname should be null terminated");
use std::ffi::CStr;
let drr_toname = unsafe { CStr::from_bytes_with_nul_unchecked(&drr_toname[0..=term]) };
out.debug_struct("drr_begin")
.field("drr_magic", &self.drr_magic)
.field("drr_versioninfo", &self.drr_versioninfo)
.field("drr_creation_time", &self.drr_creation_time)
.field("drr_type", &self.drr_type)
.field("drr_flags", &self.drr_flags)
.field("drr_toguid", &self.drr_toguid)
.field("drr_fromguid", &self.drr_fromguid)
.field("drr_toname", &drr_toname)
.finish()
}
}
use std::borrow::Borrow;
pub struct drr_debug<R: Borrow<dmu_replay_record>>(pub R);
impl<R: Borrow<dmu_replay_record>> fmt::Debug for drr_debug<R> {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
let drr = self.0.borrow();
let dbg: &dyn fmt::Debug = unsafe {
if drr.drr_type == dmu_replay_record_DRR_OBJECT {
&drr.drr_u.drr_object
} else if drr.drr_type == dmu_replay_record_DRR_FREEOBJECTS {
&drr.drr_u.drr_freeobjects
} else if drr.drr_type == dmu_replay_record_DRR_WRITE {
&drr.drr_u.drr_write
} else if drr.drr_type == dmu_replay_record_DRR_FREE {
&drr.drr_u.drr_free
} else if drr.drr_type == dmu_replay_record_DRR_BEGIN {
&drr.drr_u.drr_begin
} else if drr.drr_type == dmu_replay_record_DRR_END {
&drr.drr_u.drr_end
} else if drr.drr_type == dmu_replay_record_DRR_SPILL {
&drr.drr_u.drr_spill
} else if drr.drr_type == dmu_replay_record_DRR_OBJECT_RANGE {
&drr.drr_u.drr_object_range
} else {
unreachable!()
}
};
if !out.alternate() {
write!(out, "{:?}", dbg)
} else {
write!(out, "{:#?}", dbg)
}
}
}
pub mod byte_serialize_impls {
use super::dmu_replay_record;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
struct dmu_replay_record_visitor;
impl<'de> Visitor<'de> for dmu_replay_record_visitor {
type Value = dmu_replay_record;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"expecting a byte array of size {}",
std::mem::size_of::<Self::Value>()
)
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
assert!(v.len() == std::mem::size_of::<dmu_replay_record>());
let mut record: dmu_replay_record;
unsafe {
record = std::mem::zeroed();
let record_aligned_ptr = &mut record as *mut _ as *mut u8;
std::ptr::copy(v.as_ptr(), record_aligned_ptr, v.len());
}
Ok(record)
}
}
impl Serialize for dmu_replay_record {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let as_bytes = unsafe {
std::slice::from_raw_parts(
self as *const _ as *const u8,
std::mem::size_of_val(&*self),
)
};
serializer.serialize_bytes(as_bytes)
}
}
impl<'de> Deserialize<'de> for dmu_replay_record {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_bytes(dmu_replay_record_visitor)
}
}
}
|
extern crate actix;
#[macro_use] extern crate actix_derive;
extern crate futures;
use actix::{msgs, Actor, Address, Arbiter, Context, Handler, Response, ResponseType, System};
use futures::{future, Future};
#[derive(Message)]
#[Message(usize)]
struct Sum(usize, usize);
struct SumActor;
impl Actor for SumActor {
type Context = Context<Self>;
}
impl Handler<Sum> for SumActor {
fn handle(&mut self, message: Sum, _context: &mut Context<Self>) -> Response<Self, Sum> {
Self::reply(message.0 + message.1)
}
}
#[test]
fn message_derive() {
let system = System::new("test");
let addr: Address<_> = SumActor.start();
let res = addr.call_fut(Sum(10, 5));
system.handle().spawn(res.then(|res| {
match res {
Ok(Ok(result)) => assert!(result == 10 + 5),
_ => panic!("Something went wrong"),
}
Arbiter::system().send(msgs::SystemExit(0));
future::result(Ok(()))
}));
system.run();
} |
use phf;
/// Contains replacements for an entity in LaTeX, HTML, ASCII, Latin1 and UTF-8.
pub struct EntityReplacement {
pub latex: &'static str,
pub requires_latex_math: bool,
pub html: &'static str,
pub ascii: &'static str,
pub latin1: &'static str,
pub utf8: &'static str,
}
const fn make(
latex: &'static str,
requires_latex_math: bool,
html: &'static str,
ascii: &'static str,
latin1: &'static str,
utf8: &'static str,
) -> EntityReplacement {
EntityReplacement {
latex,
requires_latex_math,
html,
ascii,
latin1,
utf8,
}
}
/// This is a map of entity names to their replacement in the LaTeX, HTML, ASCII, Latin1 and UTF-8
/// exporters.
///
/// This list is taken from lisp/org-entities.el in the org-mode repository.
pub static ORG_ENTITIES: phf::Map<
&'static str,
EntityReplacement,
//(
// &'static str,
// bool,
// &'static str,
// &'static str,
// &'static str,
// &'static str,
//),
> = phf_map! {
// name => LaTeX, requires LaTeX math?, html, ascii, latin1, utf-8
// Letters
// Latin
"Agrave" => make("\\`{A}", false, "À", "A", "À", "À"),
"agrave" => make("\\`{a}", false, "à", "a", "à", "à"),
"Aacute" => make("\\'{A}", false, "Á", "A", "Á", "Á"),
"aacute" => make("\\'{a}", false, "á", "a", "á", "á"),
"Acirc" => make("\\^{A}", false, "Â", "A", "Â", "Â"),
"acirc" => make("\\^{a}", false, "â", "a", "â", "â"),
"Amacr" => make("\\bar{A}", false, "Ā", "A", "Ã", "Ã"),
"amacr" => make("\\bar{a}", false, "ā", "a", "ã", "ã"),
"Atilde" => make("\\~{A}", false, "Ã", "A", "Ã", "Ã"),
"atilde" => make("\\~{a}", false, "ã", "a", "ã", "ã"),
"Auml" => make("\\\"{A}", false, "Ä", "Ae", "Ä", "Ä"),
"auml" => make("\\\"{a}", false, "ä", "ae", "ä", "ä"),
"Aring" => make("\\AA{}", false, "Å", "A", "Å", "Å"),
"AA" => make("\\AA{}", false, "Å", "A", "Å", "Å"),
"aring" => make("\\aa{}", false, "å", "a", "å", "å"),
"AElig" => make("\\AE{}", false, "Æ", "AE", "Æ", "Æ"),
"aelig" => make("\\ae{}", false, "æ", "ae", "æ", "æ"),
"Ccedil" => make("\\c{C}", false, "Ç", "C", "Ç", "Ç"),
"ccedil" => make("\\c{c}", false, "ç", "c", "ç", "ç"),
"Egrave" => make("\\`{E}", false, "È", "E", "È", "È"),
"egrave" => make("\\`{e}", false, "è", "e", "è", "è"),
"Eacute" => make("\\'{E}", false, "É", "E", "É", "É"),
"eacute" => make("\\'{e}", false, "é", "e", "é", "é"),
"Ecirc" => make("\\^{E}", false, "Ê", "E", "Ê", "Ê"),
"ecirc" => make("\\^{e}", false, "ê", "e", "ê", "ê"),
"Euml" => make("\\\"{E}", false, "Ë", "E", "Ë", "Ë"),
"euml" => make("\\\"{e}", false, "ë", "e", "ë", "ë"),
"Igrave" => make("\\`{I}", false, "Ì", "I", "Ì", "Ì"),
"igrave" => make("\\`{i}", false, "ì", "i", "ì", "ì"),
"Iacute" => make("\\'{I}", false, "Í", "I", "Í", "Í"),
"iacute" => make("\\'{i}", false, "í", "i", "í", "í"),
"Icirc" => make("\\^{I}", false, "Î", "I", "Î", "Î"),
"icirc" => make("\\^{i}", false, "î", "i", "î", "î"),
"Iuml" => make("\\\"{I}", false, "Ï", "I", "Ï", "Ï"),
"iuml" => make("\\\"{i}", false, "ï", "i", "ï", "ï"),
"Ntilde" => make("\\~{N}", false, "Ñ", "N", "Ñ", "Ñ"),
"ntilde" => make("\\~{n}", false, "ñ", "n", "ñ", "ñ"),
"Ograve" => make("\\`{O}", false, "Ò", "O", "Ò", "Ò"),
"ograve" => make("\\`{o}", false, "ò", "o", "ò", "ò"),
"Oacute" => make("\\'{O}", false, "Ó", "O", "Ó", "Ó"),
"oacute" => make("\\'{o}", false, "ó", "o", "ó", "ó"),
"Ocirc" => make("\\^{O}", false, "Ô", "O", "Ô", "Ô"),
"ocirc" => make("\\^{o}", false, "ô", "o", "ô", "ô"),
"Otilde" => make("\\~{O}", false, "Õ", "O", "Õ", "Õ"),
"otilde" => make("\\~{o}", false, "õ", "o", "õ", "õ"),
"Ouml" => make("\\\"{O}", false, "Ö", "Oe", "Ö", "Ö"),
"ouml" => make("\\\"{o}", false, "ö", "oe", "ö", "ö"),
"Oslash" => make("\\O", false, "Ø", "O", "Ø", "Ø"),
"oslash" => make("\\o{}", false, "ø", "o", "ø", "ø"),
"OElig" => make("\\OE{}", false, "Œ", "OE", "OE", "Œ"),
"oelig" => make("\\oe{}", false, "œ", "oe", "oe", "œ"),
"Scaron" => make("\\v{S}", false, "Š", "S", "S", "Š"),
"scaron" => make("\\v{s}", false, "š", "s", "s", "š"),
"szlig" => make("\\ss{}", false, "ß", "ss", "ß", "ß"),
"Ugrave" => make("\\`{U}", false, "Ù", "U", "Ù", "Ù"),
"ugrave" => make("\\`{u}", false, "ù", "u", "ù", "ù"),
"Uacute" => make("\\'{U}", false, "Ú", "U", "Ú", "Ú"),
"uacute" => make("\\'{u}", false, "ú", "u", "ú", "ú"),
"Ucirc" => make("\\^{U}", false, "Û", "U", "Û", "Û"),
"ucirc" => make("\\^{u}", false, "û", "u", "û", "û"),
"Uuml" => make("\\\"{U}", false, "Ü", "Ue", "Ü", "Ü"),
"uuml" => make("\\\"{u}", false, "ü", "ue", "ü", "ü"),
"Yacute" => make("\\'{Y}", false, "Ý", "Y", "Ý", "Ý"),
"yacute" => make("\\'{y}", false, "ý", "y", "ý", "ý"),
"Yuml" => make("\\\"{Y}", false, "Ÿ", "Y", "Y", "Ÿ"),
"yuml" => make("\\\"{y}", false, "ÿ", "y", "ÿ", "ÿ"),
// Latin (special face)
"fnof" => make("\\textit{f}", false, "ƒ", "f", "f", "ƒ"),
"real" => make("\\Re", true, "ℜ", "R", "R", "ℜ"),
"image" => make("\\Im", true, "ℑ", "I", "I", "ℑ"),
"weierp" => make("\\wp", true, "℘", "P", "P", "℘"),
"ell" => make("\\ell", true, "ℓ", "ell", "ell", "ℓ"),
"imath" => make("\\imath", true, "ı", "[dotless i]", "dotless i", "ı"),
"jmath" => make("\\jmath", true, "ȷ", "[dotless j]", "dotless j", "ȷ"),
// Greek
"Alpha" => make("A", false, "Α", "Alpha", "Alpha", "Α"),
"alpha" => make("\\alpha", true, "α", "alpha", "alpha", "α"),
"Beta" => make("B", false, "Β", "Beta", "Beta", "Β"),
"beta" => make("\\beta", true, "β", "beta", "beta", "β"),
"Gamma" => make("\\Gamma", true, "Γ", "Gamma", "Gamma", "Γ"),
"gamma" => make("\\gamma", true, "γ", "gamma", "gamma", "γ"),
"Delta" => make("\\Delta", true, "Δ", "Delta", "Delta", "Δ"),
"delta" => make("\\delta", true, "δ", "delta", "delta", "δ"),
"Epsilon" => make("E", false, "Ε", "Epsilon", "Epsilon", "Ε"),
"epsilon" => make("\\epsilon", true, "ε", "epsilon", "epsilon", "ε"),
"varepsilon" => make("\\varepsilon", true, "ε", "varepsilon", "varepsilon", "ε"),
"Zeta" => make("Z", false, "Ζ", "Zeta", "Zeta", "Ζ"),
"zeta" => make("\\zeta", true, "ζ", "zeta", "zeta", "ζ"),
"Eta" => make("H", false, "Η", "Eta", "Eta", "Η"),
"eta" => make("\\eta", true, "η", "eta", "eta", "η"),
"Theta" => make("\\Theta", true, "Θ", "Theta", "Theta", "Θ"),
"theta" => make("\\theta", true, "θ", "theta", "theta", "θ"),
"thetasym" => make("\\vartheta", true, "ϑ", "theta", "theta", "ϑ"),
"vartheta" => make("\\vartheta", true, "ϑ", "theta", "theta", "ϑ"),
"Iota" => make("I", false, "Ι", "Iota", "Iota", "Ι"),
"iota" => make("\\iota", true, "ι", "iota", "iota", "ι"),
"Kappa" => make("K", false, "Κ", "Kappa", "Kappa", "Κ"),
"kappa" => make("\\kappa", true, "κ", "kappa", "kappa", "κ"),
"Lambda" => make("\\Lambda", true, "Λ", "Lambda", "Lambda", "Λ"),
"lambda" => make("\\lambda", true, "λ", "lambda", "lambda", "λ"),
"Mu" => make("M", false, "Μ", "Mu", "Mu", "Μ"),
"mu" => make("\\mu", true, "μ", "mu", "mu", "μ"),
"nu" => make("\\nu", true, "ν", "nu", "nu", "ν"),
"Nu" => make("N", false, "Ν", "Nu", "Nu", "Ν"),
"Xi" => make("\\Xi", true, "Ξ", "Xi", "Xi", "Ξ"),
"xi" => make("\\xi", true, "ξ", "xi", "xi", "ξ"),
"Omicron" => make("O", false, "Ο", "Omicron", "Omicron", "Ο"),
"omicron" => make("\\textit{o}", false, "ο", "omicron", "omicron", "ο"),
"Pi" => make("\\Pi", true, "Π", "Pi", "Pi", "Π"),
"pi" => make("\\pi", true, "π", "pi", "pi", "π"),
"Rho" => make("P", false, "Ρ", "Rho", "Rho", "Ρ"),
"rho" => make("\\rho", true, "ρ", "rho", "rho", "ρ"),
"Sigma" => make("\\Sigma", true, "Σ", "Sigma", "Sigma", "Σ"),
"sigma" => make("\\sigma", true, "σ", "sigma", "sigma", "σ"),
"sigmaf" => make("\\varsigma", true, "ς", "sigmaf", "sigmaf", "ς"),
"varsigma" => make("\\varsigma", true, "ς", "varsigma", "varsigma", "ς"),
"Tau" => make("T", false, "Τ", "Tau", "Tau", "Τ"),
"Upsilon" => make("\\Upsilon", true, "Υ", "Upsilon", "Upsilon", "Υ"),
"upsih" => make("\\Upsilon", true, "ϒ", "upsilon", "upsilon", "ϒ"),
"upsilon" => make("\\upsilon", true, "υ", "upsilon", "upsilon", "υ"),
"Phi" => make("\\Phi", true, "Φ", "Phi", "Phi", "Φ"),
"phi" => make("\\phi", true, "φ", "phi", "phi", "ɸ"),
"varphi" => make("\\varphi", true, "ϕ", "varphi", "varphi", "φ"),
"Chi" => make("X", false, "Χ", "Chi", "Chi", "Χ"),
"chi" => make("\\chi", true, "χ", "chi", "chi", "χ"),
"acutex" => make("\\acute x", true, "´x", "'x", "'x", "𝑥́"),
"Psi" => make("\\Psi", true, "Ψ", "Psi", "Psi", "Ψ"),
"psi" => make("\\psi", true, "ψ", "psi", "psi", "ψ"),
"tau" => make("\\tau", true, "τ", "tau", "tau", "τ"),
"Omega" => make("\\Omega", true, "Ω", "Omega", "Omega", "Ω"),
"omega" => make("\\omega", true, "ω", "omega", "omega", "ω"),
"piv" => make("\\varpi", true, "ϖ", "omega-pi", "omega-pi", "ϖ"),
"varpi" => make("\\varpi", true, "ϖ", "omega-pi", "omega-pi", "ϖ"),
"partial" => make("\\partial", true, "∂", "[partial differential]", "[partial differential]", "∂"),
// Hebrew
"alefsym" => make("\\aleph", true, "ℵ", "aleph", "aleph", "ℵ"),
"aleph" => make("\\aleph", true, "ℵ", "aleph", "aleph", "ℵ"),
"gimel" => make("\\gimel", true, "ℷ", "gimel", "gimel", "ℷ"),
"beth" => make("\\beth", true, "ℶ", "beth", "beth", "ב"),
"dalet" => make("\\daleth", true, "ℸ", "dalet", "dalet", "ד"),
// Dead languages
"ETH" => make("\\DH{}", false, "Ð", "D", "Ð", "Ð"),
"eth" => make("\\dh{}", false, "ð", "dh", "ð", "ð"),
"THORN" => make("\\TH{}", false, "Þ", "TH", "Þ", "Þ"),
"thorn" => make("\\th{}", false, "þ", "th", "þ", "þ"),
// Punctuation
// Dots and Marks
"dots" => make("\\dots{}", false, "…", "...", "...", "…"),
"cdots" => make("\\cdots{}", true, "⋯", "...", "...", "⋯"),
"hellip" => make("\\dots{}", false, "…", "...", "...", "…"),
"middot" => make("\\textperiodcentered{}", false, "·", ".", "·", "·"),
"iexcl" => make("!`", false, "¡", "!", "¡", "¡"),
"iquest" => make("?`", false, "¿", "?", "¿", "¿"),
// Dash-like
"shy" => make("\\-", false, "­", "", "", ""),
"ndash" => make("--", false, "–", "-", "-", "–"),
"mdash" => make("---", false, "—", "--", "--", "—"),
// Quotations
"quot" => make("\\textquotedbl{}", false, """, "\"", "\"", "\""),
"acute" => make("\\textasciiacute{}", false, "´", "'", "´", "´"),
"ldquo" => make("\\textquotedblleft{}", false, "“", "\"", "\"", "“"),
"rdquo" => make("\\textquotedblright{}", false, "”", "\"", "\"", "”"),
"bdquo" => make("\\quotedblbase{}", false, "„", "\"", "\"", "„"),
"lsquo" => make("\\textquoteleft{}", false, "‘", "`", "`", "‘"),
"rsquo" => make("\\textquoteright{}", false, "’", "'", "'", "’"),
"sbquo" => make("\\quotesinglbase{}", false, "‚", ",", ",", "‚"),
"laquo" => make("\\guillemotleft{}", false, "«", "<<", "«", "«"),
"raquo" => make("\\guillemotright{}", false, "»", ">>", "»", "»"),
"lsaquo" => make("\\guilsinglleft{}", false, "‹", "<", "<", "‹"),
"rsaquo" => make("\\guilsinglright{}", false, "›", ">", ">", "›"),
// Other
// Misc. (often used)
"circ" => make("\\^{}", false, "ˆ", "^", "^", "∘"),
"vert" => make("\\vert{}", true, "|", "|", "|", "|"),
"vbar" => make("|", false, "|", "|", "|", "|"),
"brvbar" => make("\\textbrokenbar{}", false, "¦", "|", "¦", "¦"),
"S" => make("\\S", false, "§", "paragraph", "§", "§"),
"sect" => make("\\S", false, "§", "paragraph", "§", "§"),
"amp" => make("\\&", false, "&", "&", "&", "&"),
"lt" => make("\\textless{}", false, "<", "<", "<", "<"),
"gt" => make("\\textgreater{}", false, ">", ">", ">", ">"),
"tilde" => make("\\textasciitilde{}", false, "~", "~", "~", "~"),
"slash" => make("/", false, "/", "/", "/", "/"),
"plus" => make("+", false, "+", "+", "+", "+"),
"under" => make("\\_", false, "_", "_", "_", "_"),
"equal" => make("=", false, "=", "=", "=", "="),
"asciicirc" => make("\\textasciicircum{}", false, "^", "^", "^", "^"),
"dagger" => make("\\textdagger{}", false, "†", "[dagger]", "[dagger]", "†"),
"dag" => make("\\dag{}", false, "†", "[dagger]", "[dagger]", "†"),
"Dagger" => make("\\textdaggerdbl{}", false, "‡", "[doubledagger]", "[doubledagger]", "‡"),
"ddag" => make("\\ddag{}", false, "‡", "[doubledagger]", "[doubledagger]", "‡"),
// Whitespace
"nbsp" => make("~", false, " ", " ", "\x00A0", "\x00A0"),
"ensp" => make("\\hspace*{.5em}", false, " ", " ", " ", " "),
"emsp" => make("\\hspace*{1em}", false, " ", " ", " ", " "),
"thinsp" => make("\\hspace*{.2em}", false, " ", " ", " ", " "),
// Currency
"curren" => make("\\textcurrency{}", false, "¤", "curr.", "¤", "¤"),
"cent" => make("\\textcent{}", false, "¢", "cent", "¢", "¢"),
"pound" => make("\\pounds{}", false, "£", "pound", "£", "£"),
"yen" => make("\\textyen{}", false, "¥", "yen", "¥", "¥"),
"euro" => make("\\texteuro{}", false, "€", "EUR", "EUR", "€"),
"EUR" => make("\\texteuro{}", false, "€", "EUR", "EUR", "€"),
"dollar" => make("\\$", false, "$", "$", "$", "$"),
"USD" => make("\\$", false, "$", "$", "$", "$"),
// Property Marks
"copy" => make("\\textcopyright{}", false, "©", "(c)", "©", "©"),
"reg" => make("\\textregistered{}", false, "®", "(r)", "®", "®"),
"trade" => make("\\texttrademark{}", false, "™", "TM", "TM", "™"),
// Science et al.
"minus" => make("\\minus", true, "−", "-", "-", "−"),
"pm" => make("\\textpm{}", false, "±", "+-", "±", "±"),
"plusmn" => make("\\textpm{}", false, "±", "+-", "±", "±"),
"times" => make("\\texttimes{}", false, "×", "*", "×", "×"),
"frasl" => make("/", false, "⁄", "/", "/", "⁄"),
"colon" => make("\\colon", true, ":", ":", ":", ":"),
"div" => make("\\textdiv{}", false, "÷", "/", "÷", "÷"),
"frac12" => make("\\textonehalf{}", false, "½", "1/2", "½", "½"),
"frac14" => make("\\textonequarter{}", false, "¼", "1/4", "¼", "¼"),
"frac34" => make("\\textthreequarters{}", false, "¾", "3/4", "¾", "¾"),
"permil" => make("\\textperthousand{}", false, "‰", "per thousand", "per thousand", "‰"),
"sup1" => make("\\textonesuperior{}", false, "¹", "^1", "¹", "¹"),
"sup2" => make("\\texttwosuperior{}", false, "²", "^2", "²", "²"),
"sup3" => make("\\textthreesuperior{}", false, "³", "^3", "³", "³"),
"radic" => make("\\sqrt{\\,}", true, "√", "[square root]", "[square root]", "√"),
"sum" => make("\\sum", true, "∑", "[sum]", "[sum]", "∑"),
"prod" => make("\\prod", true, "∏", "[product]", "[n-ary product]", "∏"),
"micro" => make("\\textmu{}", false, "µ", "micro", "µ", "µ"),
"macr" => make("\\textasciimacron{}", false, "¯", "[macron]", "¯", "¯"),
"deg" => make("\\textdegree{}", false, "°", "degree", "°", "°"),
"prime" => make("\\prime", true, "′", "'", "'", "′"),
"Prime" => make("\\prime{}\\prime", true, "″", "''", "''", "″"),
"infin" => make("\\infty", true, "∞", "[infinity]", "[infinity]", "∞"),
"infty" => make("\\infty", true, "∞", "[infinity]", "[infinity]", "∞"),
"prop" => make("\\propto", true, "∝", "[proportional to]", "[proportional to]", "∝"),
"propto" => make("\\propto", true, "∝", "[proportional to]", "[proportional to]", "∝"),
"not" => make("\\textlnot{}", false, "¬", "[angled dash]", "¬", "¬"),
"neg" => make("\\neg{}", true, "¬", "[angled dash]", "¬", "¬"),
"land" => make("\\land", true, "∧", "[logical and]", "[logical and]", "∧"),
"wedge" => make("\\wedge", true, "∧", "[logical and]", "[logical and]", "∧"),
"lor" => make("\\lor", true, "∨", "[logical or]", "[logical or]", "∨"),
"vee" => make("\\vee", true, "∨", "[logical or]", "[logical or]", "∨"),
"cap" => make("\\cap", true, "∩", "[intersection]", "[intersection]", "∩"),
"cup" => make("\\cup", true, "∪", "[union]", "[union]", "∪"),
"smile" => make("\\smile", true, "⌣", "[cup product]", "[cup product]", "⌣"),
"frown" => make("\\frown", true, "⌢", "[Cap product]", "[cap product]", "⌢"),
"int" => make("\\int", true, "∫", "[integral]", "[integral]", "∫"),
"therefore" => make("\\therefore", true, "∴", "[therefore]", "[therefore]", "∴"),
"there4" => make("\\therefore", true, "∴", "[therefore]", "[therefore]", "∴"),
"because" => make("\\because", true, "∵", "[because]", "[because]", "∵"),
"sim" => make("\\sim", true, "∼", "~", "~", "∼"),
"cong" => make("\\cong", true, "≅", "[approx. equal to]", "[approx. equal to]", "≅"),
"simeq" => make("\\simeq", true, "≅", "[approx. equal to]", "[approx. equal to]", "≅"),
"asymp" => make("\\asymp", true, "≈", "[almost equal to]", "[almost equal to]", "≈"),
"approx" => make("\\approx", true, "≈", "[almost equal to]", "[almost equal to]", "≈"),
"ne" => make("\\ne", true, "≠", "[not equal to]", "[not equal to]", "≠"),
"neq" => make("\\neq", true, "≠", "[not equal to]", "[not equal to]", "≠"),
"equiv" => make("\\equiv", true, "≡", "[identical to]", "[identical to]", "≡"),
"triangleq" => make("\\triangleq", true, "≜", "[defined to]", "[defined to]", "≜"),
"le" => make("\\le", true, "≤", "<=", "<=", "≤"),
"leq" => make("\\le", true, "≤", "<=", "<=", "≤"),
"ge" => make("\\ge", true, "≥", ">=", ">=", "≥"),
"geq" => make("\\ge", true, "≥", ">=", ">=", "≥"),
"lessgtr" => make("\\lessgtr", true, "≶", "[less than or greater than]", "[less than or greater than]", "≶"),
"lesseqgtr" => make("\\lesseqgtr", true, "⋚", "[less than or equal or greater than or equal]", "[less than or equal or greater than or equal]", "⋚"),
"ll" => make("\\ll", true, "≪", "<<", "<<", "≪"),
"Ll" => make("\\lll", true, "⋘", "<<<", "<<<", "⋘"),
"lll" => make("\\lll", true, "⋘", "<<<", "<<<", "⋘"),
"gg" => make("\\gg", true, "≫", ">>", ">>", "≫"),
"Gg" => make("\\ggg", true, "⋙", ">>>", ">>>", "⋙"),
"ggg" => make("\\ggg", true, "⋙", ">>>", ">>>", "⋙"),
"prec" => make("\\prec", true, "≺", "[precedes]", "[precedes]", "≺"),
"preceq" => make("\\preceq", true, "≼", "[precedes or equal]", "[precedes or equal]", "≼"),
"preccurlyeq" => make("\\preccurlyeq", true, "≼", "[precedes or equal]", "[precedes or equal]", "≼"),
"succ" => make("\\succ", true, "≻", "[succeeds]", "[succeeds]", "≻"),
"succeq" => make("\\succeq", true, "≽", "[succeeds or equal]", "[succeeds or equal]", "≽"),
"succcurlyeq" => make("\\succcurlyeq", true, "≽", "[succeeds or equal]", "[succeeds or equal]", "≽"),
"sub" => make("\\subset", true, "⊂", "[subset of]", "[subset of]", "⊂"),
"subset" => make("\\subset", true, "⊂", "[subset of]", "[subset of]", "⊂"),
"sup" => make("\\supset", true, "⊃", "[superset of]", "[superset of]", "⊃"),
"supset" => make("\\supset", true, "⊃", "[superset of]", "[superset of]", "⊃"),
"nsub" => make("\\not\\subset", true, "⊄", "[not a subset of]", "[not a subset of", "⊄"),
"sube" => make("\\subseteq", true, "⊆", "[subset of or equal to]", "[subset of or equal to]", "⊆"),
"nsup" => make("\\not\\supset", true, "⊅", "[not a superset of]", "[not a superset of]", "⊅"),
"supe" => make("\\supseteq", true, "⊇", "[superset of or equal to]", "[superset of or equal to]", "⊇"),
"setminus" => make("\\setminus", true, "∖", "\\", "\\", "⧵"),
"forall" => make("\\forall", true, "∀", "[for all]", "[for all]", "∀"),
"exist" => make("\\exists", true, "∃", "[there exists]", "[there exists]", "∃"),
"exists" => make("\\exists", true, "∃", "[there exists]", "[there exists]", "∃"),
"nexist" => make("\\nexists", true, "∃", "[there does not exists]", "[there does not exists]", "∄"),
"nexists" => make("\\nexists", true, "∃", "[there does not exists]", "[there does not exists]", "∄"),
"empty" => make("\\empty", true, "∅", "[empty set]", "[empty set]", "∅"),
"emptyset" => make("\\emptyset", true, "∅", "[empty set]", "[empty set]", "∅"),
"isin" => make("\\in", true, "∈", "[element of]", "[element of]", "∈"),
"in" => make("\\in", true, "∈", "[element of]", "[element of]", "∈"),
"notin" => make("\\notin", true, "∉", "[not an element of]", "[not an element of]", "∉"),
"ni" => make("\\ni", true, "∋", "[contains as member]", "[contains as member]", "∋"),
"nabla" => make("\\nabla", true, "∇", "[nabla]", "[nabla]", "∇"),
"ang" => make("\\angle", true, "∠", "[angle]", "[angle]", "∠"),
"angle" => make("\\angle", true, "∠", "[angle]", "[angle]", "∠"),
"perp" => make("\\perp", true, "⊥", "[up tack]", "[up tack]", "⊥"),
"parallel" => make("\\parallel", true, "∥", "||", "||", "∥"),
"sdot" => make("\\cdot", true, "⋅", "[dot]", "[dot]", "⋅"),
"cdot" => make("\\cdot", true, "⋅", "[dot]", "[dot]", "⋅"),
"lceil" => make("\\lceil", true, "⌈", "[left ceiling]", "[left ceiling]", "⌈"),
"rceil" => make("\\rceil", true, "⌉", "[right ceiling]", "[right ceiling]", "⌉"),
"lfloor" => make("\\lfloor", true, "⌊", "[left floor]", "[left floor]", "⌊"),
"rfloor" => make("\\rfloor", true, "⌋", "[right floor]", "[right floor]", "⌋"),
"lang" => make("\\langle", true, "⟨", "<", "<", "⟨"),
"rang" => make("\\rangle", true, "⟩", ">", ">", "⟩"),
"langle" => make("\\langle", true, "⟨", "<", "<", "⟨"),
"rangle" => make("\\rangle", true, "⟩", ">", ">", "⟩"),
"hbar" => make("\\hbar", true, "ℏ", "hbar", "hbar", "ℏ"),
"mho" => make("\\mho", true, "℧", "mho", "mho", "℧"),
// Arrows
"larr" => make("\\leftarrow", true, "←", "<-", "<-", "←"),
"leftarrow" => make("\\leftarrow", true, "←", "<-", "<-", "←"),
"gets" => make("\\gets", true, "←", "<-", "<-", "←"),
"lArr" => make("\\Leftarrow", true, "⇐", "<=", "<=", "⇐"),
"Leftarrow" => make("\\Leftarrow", true, "⇐", "<=", "<=", "⇐"),
"uarr" => make("\\uparrow", true, "↑", "[uparrow]", "[uparrow]", "↑"),
"uparrow" => make("\\uparrow", true, "↑", "[uparrow]", "[uparrow]", "↑"),
"uArr" => make("\\Uparrow", true, "⇑", "[dbluparrow]", "[dbluparrow]", "⇑"),
"Uparrow" => make("\\Uparrow", true, "⇑", "[dbluparrow]", "[dbluparrow]", "⇑"),
"rarr" => make("\\rightarrow", true, "→", "->", "->", "→"),
"to" => make("\\to", true, "→", "->", "->", "→"),
"rightarrow" => make("\\rightarrow", true, "→", "->", "->", "→"),
"rArr" => make("\\Rightarrow", true, "⇒", "=>", "=>", "⇒"),
"Rightarrow" => make("\\Rightarrow", true, "⇒", "=>", "=>", "⇒"),
"darr" => make("\\downarrow", true, "↓", "[downarrow]", "[downarrow]", "↓"),
"downarrow" => make("\\downarrow", true, "↓", "[downarrow]", "[downarrow]", "↓"),
"dArr" => make("\\Downarrow", true, "⇓", "[dbldownarrow]", "[dbldownarrow]", "⇓"),
"Downarrow" => make("\\Downarrow", true, "⇓", "[dbldownarrow]", "[dbldownarrow]", "⇓"),
"harr" => make("\\leftrightarrow", true, "↔", "<->", "<->", "↔"),
"leftrightarrow" => make("\\leftrightarrow", true, "↔", "<->", "<->", "↔"),
"hArr" => make("\\Leftrightarrow", true, "⇔", "<=>", "<=>", "⇔"),
"Leftrightarrow" => make("\\Leftrightarrow", true, "⇔", "<=>", "<=>", "⇔"),
"crarr" => make("\\hookleftarrow", true, "↵", "<-'", "<-'", "↵"),
"hookleftarrow" => make("\\hookleftarrow", true, "↵", "<-'", "<-'", "↵"),
// Function names
"arccos" => make("\\arccos", true, "arccos", "arccos", "arccos", "arccos"),
"arcsin" => make("\\arcsin", true, "arcsin", "arcsin", "arcsin", "arcsin"),
"arctan" => make("\\arctan", true, "arctan", "arctan", "arctan", "arctan"),
"arg" => make("\\arg", true, "arg", "arg", "arg", "arg"),
"cos" => make("\\cos", true, "cos", "cos", "cos", "cos"),
"cosh" => make("\\cosh", true, "cosh", "cosh", "cosh", "cosh"),
"cot" => make("\\cot", true, "cot", "cot", "cot", "cot"),
"coth" => make("\\coth", true, "coth", "coth", "coth", "coth"),
"csc" => make("\\csc", true, "csc", "csc", "csc", "csc"),
//"deg" => make("\\deg", true, "°", "deg", "deg", "deg"), // duplicate key
"det" => make("\\det", true, "det", "det", "det", "det"),
"dim" => make("\\dim", true, "dim", "dim", "dim", "dim"),
"exp" => make("\\exp", true, "exp", "exp", "exp", "exp"),
"gcd" => make("\\gcd", true, "gcd", "gcd", "gcd", "gcd"),
"hom" => make("\\hom", true, "hom", "hom", "hom", "hom"),
"inf" => make("\\inf", true, "inf", "inf", "inf", "inf"),
"ker" => make("\\ker", true, "ker", "ker", "ker", "ker"),
"lg" => make("\\lg", true, "lg", "lg", "lg", "lg"),
"lim" => make("\\lim", true, "lim", "lim", "lim", "lim"),
"liminf" => make("\\liminf", true, "liminf", "liminf", "liminf", "liminf"),
"limsup" => make("\\limsup", true, "limsup", "limsup", "limsup", "limsup"),
"ln" => make("\\ln", true, "ln", "ln", "ln", "ln"),
"log" => make("\\log", true, "log", "log", "log", "log"),
"max" => make("\\max", true, "max", "max", "max", "max"),
"min" => make("\\min", true, "min", "min", "min", "min"),
"Pr" => make("\\Pr", true, "Pr", "Pr", "Pr", "Pr"),
"sec" => make("\\sec", true, "sec", "sec", "sec", "sec"),
"sin" => make("\\sin", true, "sin", "sin", "sin", "sin"),
"sinh" => make("\\sinh", true, "sinh", "sinh", "sinh", "sinh"),
//"sup" => make("\\sup", true, "⊃", "sup", "sup", "sup"), // duplicate key
"tan" => make("\\tan", true, "tan", "tan", "tan", "tan"),
"tanh" => make("\\tanh", true, "tanh", "tanh", "tanh", "tanh"),
// Signs & Symbols
"bull" => make("\\textbullet{}", false, "•", "*", "*", "•"),
"bullet" => make("\\textbullet{}", false, "•", "*", "*", "•"),
"star" => make("\\star", true, "*", "*", "*", "⋆"),
"lowast" => make("\\ast", true, "∗", "*", "*", "∗"),
"ast" => make("\\ast", true, "∗", "*", "*", "*"),
"odot" => make("\\odot", true, "o", "[circled dot]", "[circled dot]", "ʘ"),
"oplus" => make("\\oplus", true, "⊕", "[circled plus]", "[circled plus]", "⊕"),
"otimes" => make("\\otimes", true, "⊗", "[circled times]", "[circled times]", "⊗"),
"check" => make("\\checkmark", true, "✓", "[checkmark]", "[checkmark]", "✓"),
"checkmark" => make("\\checkmark", true, "✓", "[checkmark]", "[checkmark]", "✓"),
// Miscellaneous (seldom used)
"para" => make("\\P{}", false, "¶", "[pilcrow]", "¶", "¶"),
"ordf" => make("\\textordfeminine{}", false, "ª", "_a_", "ª", "ª"),
"ordm" => make("\\textordmasculine{}", false, "º", "_o_", "º", "º"),
"cedil" => make("\\c{}", false, "¸", "[cedilla]", "¸", "¸"),
"oline" => make("\\overline{~}", true, "‾", "[overline]", "¯", "‾"),
"uml" => make("\\textasciidieresis{}", false, "¨", "[diaeresis]", "¨", "¨"),
"zwnj" => make("\\/{}", false, "‌", "", "", ""),
"zwj" => make("", false, "‍", "", "", ""),
"lrm" => make("", false, "‎", "", "", ""),
"rlm" => make("", false, "‏", "", "", ""),
// Smilies
"smiley" => make("\\ddot\\smile", true, "☺", ":-)", ":-)", "☺"),
"blacksmile" => make("\\ddot\\smile", true, "☻", ":-)", ":-)", "☻"),
"sad" => make("\\ddot\\frown", true, "☹", ":-(", ":-(", "☹"),
"frowny" => make("\\ddot\\frown", true, "☹", ":-(", ":-(", "☹"),
// Suits
"clubs" => make("\\clubsuit", true, "♣", "[clubs]", "[clubs]", "♣"),
"clubsuit" => make("\\clubsuit", true, "♣", "[clubs]", "[clubs]", "♣"),
"spades" => make("\\spadesuit", true, "♠", "[spades]", "[spades]", "♠"),
"spadesuit" => make("\\spadesuit", true, "♠", "[spades]", "[spades]", "♠"),
"hearts" => make("\\heartsuit", true, "♥", "[hearts]", "[hearts]", "♥"),
"heartsuit" => make("\\heartsuit", true, "♥", "[hearts]", "[hearts]", "♥"),
"diams" => make("\\diamondsuit", true, "♦", "[diamonds]", "[diamonds]", "◆"),
"diamondsuit" => make("\\diamondsuit", true, "♦", "[diamonds]", "[diamonds]", "◆"),
"diamond" => make("\\diamondsuit", true, "⋄", "[diamond]", "[diamond]", "◆"),
"Diamond" => make("\\diamondsuit", true, "⋄", "[diamond]", "[diamond]", "◆"),
"loz" => make("\\lozenge", true, "◊", "[lozenge]", "[lozenge]", "⧫"),
// TODO needs build script to include at compile time
// Spaces ("\_ ")
// (let (space-entities html-spaces (entity "_"))
// (dolist (n (number-sequence 1 20) (nreverse space-entities))
// (let ((spaces (make-string n ?\s)))
// (push (list (setq entity (concat entity " "))
// (format "\\hspace*{%sem}" (* n .5))
// nil
// (setq html-spaces (concat " " html-spaces))
// spaces
// spaces
// (make-string n ?\x2002))
// space-entities))))
};
|
extern crate subprocess;
use subprocess::Exec;
use std::env;
// Try running "cargo build -vv" to see this output.
// For development, just run npm commands in "web" directly.
fn main() {
env::set_current_dir("web").unwrap();
Exec::shell("npm run build").join().unwrap();
println!("cargo:rerun-if-changed=web");
}
|
use schema::horus_licenses;
#[derive(Insertable, Queryable, Serialize)]
#[table_name = "horus_licenses"]
pub struct License
{
pub key: String,
pub owner: i32,
pub type_: Option<i16>, // Since "type" is a rust keyword, needed for diesel
pub resource_count: i32
}
|
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(not(feature = "std"), no_std)]
//! # semval
//!
//! A lightweight and versatile toolbox for implementing semantic validation.
//!
//! Please refer to the bundled `reservation.rs` example to get an idea of how it works.
//!
//! Without any macro magic, at least not now.
/// Invalidity context
pub mod context;
/// The crate's prelude
///
/// A proposed set of imports to ease usage of this crate.
pub mod prelude {
pub use super::{
context::Context as ValidationContext, Invalidity, Result as ValidationResult, Validate,
};
}
use context::Context;
use core::{any::Any, fmt::Debug};
/// Result of a validation
///
/// The result is `Ok` and empty if the validation succeeded. It is
/// a validation context wrapped into `Err` that carries one or more
/// invalidities.
///
/// In contrast to common results the actual payload is carried by
/// the error variant while a successful result is just the unit type.
pub type Result<V> = core::result::Result<(), Context<V>>;
/// Invalidities that cause validation failures
///
/// Validations fail if one or more objectives are considered invalid.
/// These invalidity objectives are typically represented by sum types
/// (`enum`) with one variant per objective. Some of the variants may
/// recursively wrap an invalidity of a subordinate validation to trace
/// back root causes.
///
/// Implementations are required to implement `Debug` to enable analysis
/// and low-level logging of those recursively wrapped sum types.
///
/// The trait bound `Any` is implicitly implemented for most types and
/// enables basic type inspection and downcasting for generically handling
/// validation results though runtime reflection.
pub trait Invalidity: Any + Debug {}
impl<V> Invalidity for V where V: Any + Debug {}
/// A trait for validating types
///
/// Validation is expected to be an expensive operation that should
/// only be invoked when crossing boundaries between independent
/// components.
pub trait Validate {
/// Invalidity objectives
type Invalidity: Invalidity;
/// Perform the validation
fn validate(&self) -> Result<Self::Invalidity>;
}
/// Validate `Some` or otherwise implicitly evaluate to `Ok`
/// in case of `None`
///
/// If the absence of an optional value is considered a validation
/// error this must be checked separately.
impl<V> Validate for Option<V>
where
V: Validate,
{
type Invalidity = V::Invalidity;
fn validate(&self) -> Result<Self::Invalidity> {
if let Some(ref some) = self {
some.validate()
} else {
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct AlwaysValid;
impl Validate for AlwaysValid {
type Invalidity = ();
fn validate(&self) -> Result<Self::Invalidity> {
Context::new().into()
}
}
struct AlwaysInvalid;
impl Validate for AlwaysInvalid {
type Invalidity = ();
fn validate(&self) -> Result<Self::Invalidity> {
Context::new().invalidate(()).into()
}
}
#[test]
fn validate() {
assert!(AlwaysValid.validate().is_ok());
assert!(AlwaysInvalid.validate().is_err());
}
#[test]
fn validate_option_none() {
assert!((None as Option<AlwaysValid>).validate().is_ok());
assert!((None as Option<AlwaysInvalid>).validate().is_ok());
}
#[test]
fn validate_option_some() {
assert!(Some(AlwaysValid).validate().is_ok());
assert!(Some(AlwaysInvalid).validate().is_err());
}
}
|
use std::convert::TryFrom;
use num_enum::TryFromPrimitive;
use crate::crtc::Crtc;
use crate::device::Device;
use crate::error::Result;
#[derive(Debug)]
#[derive(TryFromPrimitive)]
#[repr(u32)]
pub enum EncoderType {
None,
DAC,
TMDS,
LVDS,
TVDAC,
Virtual,
DSI,
DPMST,
}
#[derive(Debug)]
pub struct Encoder<'a> {
dev: &'a Device,
id: u32,
type_: EncoderType,
}
impl<'a> Encoder<'a> {
pub(crate) fn new_from_id(dev: &'a Device, id: u32) -> Result<Encoder<'a>> {
let encoder = dev.raw.get_encoder(id)?;
Ok(Encoder {
dev,
id,
type_: EncoderType::try_from(encoder.encoder_type).unwrap(),
})
}
pub fn get_possible_crtcs(&'_ self) -> Result<Vec<Crtc<'a>>> {
let encoder = self.dev.raw.get_encoder(self.id)?;
let crtcs = self.dev.get_crtcs()?;
let ret = crtcs
.into_iter()
.enumerate()
.filter(|&(index, _)| ((1 << index) & encoder.possible_crtcs) > 0)
.map(|(_, crtc)| crtc)
.collect();
Ok(ret)
}
}
|
use tlsh::{BucketKind, ChecksumKind, TlshBuilder};
use rustler::Binary;
#[rustler::nif]
pub fn hash(b64: Binary) -> String {
let mut builder = TlshBuilder::new(
BucketKind::Bucket128,
ChecksumKind::OneByte,
tlsh::Version::Version4,
);
builder.update(&b64);
let tlsh1 = builder.build().unwrap();
tlsh1.hash()
}
rustler::init!("Elixir.ExTlsh", [hash]); |
#![feature(const_generics)]
use std::fs::File;
use std::io::prelude::*;
use
struct ThreshArray<U, const N : usize> {
len : usize,
member : [U ; N],
}
impl<U, const N : usize> ThreshArray<U,N> {
fn new() -> Self {
return
}
}
struct Instruction {
prefix: ThreshArray<u8, 4>,
instruction: ThreshArray<u8, 2>,
modreg: ThreshArray<u8, 1>,
OSIB: ThreshArray<u8, 1>,
displacement : ThreshArray<u8, 4>,
constant: ThreshArray<u8, 4>
}
struct ByteReader {
cursor : usize,
vec : Vec<u8>,
}
impl ByteReader {
fn new(v : Vec<u8>) -> Self {
Self {
cursor : 0,
vec : v
}
}
fn skip_elf_header(&mut self) {
self.cursor += 0x40;
}
fn match_prefix(&mut self) -> {
match self.vec[self.cursor] {
0xf0..0xf3 => ,
_ =>
}
}
fn match_opcode
}
fn openfile(filename : impl AsRef<str>) -> Result<Vec<u8>, std::io::Error> {
let mut file = File::open(filename.as_ref())?;
let mut contents = Vec::new();
match file.read_to_end(&mut contents) {
Ok(_) => Ok(contents),
Err(e) => Err(e)
}
}
fn main() {
let v = openfile("lab4_ex1").unwrap();
let br = ByteReader::new(v);
}
|
#![allow(dead_code)]
#[macro_use]
extern crate log;
extern crate chrono;
extern crate crossbeam_channel;
#[macro_export]
macro_rules! import {
($($name:ident),+) => {
$(
mod $name;
#[allow(unused_imports)]
use self::$name::*;
)*
};
}
mod config;
mod irc;
mod ui;
pub use self::config::Config;
pub use self::ui::Gui;
|
use jni::sys::jlong;
use wasmer::{Instance, NativeFunc};
use std::ops::Deref;
#[allow(non_camel_case_types)]
pub type jptr = jlong;
#[derive(Debug)]
pub struct Pointer<Kind> {
value: Box<Kind>,
}
impl<Kind> Pointer<Kind> {
pub fn new(value: Kind) -> Self {
Pointer {
value: Box::new(value),
}
}
pub fn borrow<'a>(self) -> &'a mut Kind {
Box::leak(self.value)
}
}
impl<Kind> From<Pointer<Kind>> for jptr {
fn from(pointer: Pointer<Kind>) -> Self {
Box::into_raw(pointer.value) as _
}
}
impl<Kind> From<jptr> for Pointer<Kind> {
fn from(pointer: jptr) -> Self {
Self {
value: unsafe { Box::from_raw(pointer as *mut Kind) },
}
}
}
impl<Kind> Deref for Pointer<Kind> {
type Target = Kind;
fn deref(&self) -> &Self::Target {
&self.value
}
}
pub struct WasmModule {
pub instance: Pointer<Instance>,
pub alloc_func: NativeFunc<i64, i32>,
pub dealloc_func: NativeFunc<(i64, i64)>,
}
#[repr(C)]
#[derive(Debug)]
pub struct Tuple (pub i64, pub i64 ); |
use tch::{Tensor, kind};
// struct LidarSimulator {
// }
// impl LidarSimulator {
// fn
// }
// struct MySLAM {
// lsim: &LidarSimulator,
// /// Step size for scan
// step_size: f32,
// /// Maximum scanning range
// max_step: f32,
// /// Threshold of probability in (0, 1) for collision check in scan
// col_threshold: f32,
// }
/// Return scan points given parameters
///
/// This function is used to compute simulated observations (distances) and
/// log probability of observations.
/// Poses `x` is batched for particles. Its size is (n, 3),
/// where n is the number of particles. The size of scan points,
/// which is the return value, is (n, n_dirs, max_step, 2).
/// n_dirs is the number of scan directions: length of `dirs`.
/// `max_step` is `int(max_range / step_size)`, which is determined by
/// `Tensor::arange2()`. The last dimension is for x and y coordinate of
/// the map.
///
/// # Arguments
/// * `xs` - Poses of the agent: (x, y, theta)
/// * `step_size` - Step size for scan
/// * `max_range` - Maximum scanning range
/// * `dirs` - Scan directions in radian
fn scan_points(xs: &Tensor, step_size: f64, max_range: f64, dirs: &Tensor)
-> Tensor {
let n = xs.size()[0];
let n_dirs = dirs.size()[0];
// Angles, shape is (n, n_dirs)
let thetas = xs.slice(1, 2, 3, 1).reshape(&[-1, 1]) +
dirs.reshape(&[1, -1]);
// Directional vectors, shape is (n, n_dirs, 2)
let dxs = thetas.cos();
let dys = thetas.sin();
let dxys = Tensor::stack(&[dxs, dys], -1);
// shape is (n, n_dirs, 1, 2) for broadcasting
let dxys = dxys.reshape(&[n, n_dirs, 1, 2]);
// Replicate directional vectors
let steps = Tensor::arange2(0.0, max_range, step_size,
kind::FLOAT_CPU);
let steps = steps.reshape(&[1, 1, -1, 1]);
let dxys = dxys * steps;
// Reshape xs[:, :2] into (n, 1, 1, 2)
let xs = xs.slice(1, 0, 2, 1);
let xs = xs.reshape(&[-1, 1, 1, 2]);
dxys + xs
}
/// Collision check based on given log probability
///
/// Argument `lps` is log probabilities of scan points.
/// It can be occupancy grid values of a simulated map. In this case,
/// the values would be `log(1)=0` or `log(small_val)`, because occupancy
/// values woule be binalized. The size of `lps` is (n, n_dirs, max_step),
/// where `n` is the batch size, `n_dirs` is the number of scan directions and
/// `max_step` is the number of scan steps (see `scan_points()`).
///
/// The size of the return value of this function is (n, n_dirs).
/// It contains the minimum value of the scan index, whose log probability
/// is greater than the threshold `threshold_lp`, in each direction.
/// You would multiply `step_size` with these indices in order to get the
/// distance where collision happens. It's precision is up to `step_size`.
fn check_collision(lps: &Tensor, threshold_lp: f64) -> Tensor {
let n = lps.size()[0];
let n_dirs = lps.size()[1];
let mut buf = vec![0.0 as f32; (n * n_dirs) as usize];
for i in 0..n {
let lps_i = lps.slice(0, i, i + 1, 1).squeeze();
for j in 0..n_dirs {
// Get vector of length max_steps
let lps_ij = lps_i.slice(0, j, j + 1, 1);
// Collision check for each scan (direction)
let ix = lps_ij.ge(threshold_lp).nonzero().min().double_value(&[]);
buf.push(ix as f32);
}
}
Tensor::of_slice(buf.as_slice()).reshape(&[n, n_dirs])
}
#[cfg(test)]
mod tests {
// TODO: is importing here idiomatic?
use tch::{Tensor};
use crate::scan_points;
// This test is intended to run with `cargo test -- --nocapture`,
// print debug
#[test]
fn test_scan_points() {
let xs = Tensor::of_slice(
&[ 0.0, 0.0, 0.0,
-10.0, 10.0, -0.1 as f32]
).reshape(&[2, 3]);
let step_size = 0.1;
let max_range = 0.5;
let dirs = Tensor::of_slice(&[-0.1 as f32, 0.0, 0.1]);
let xys = scan_points(&xs, step_size, max_range, &dirs);
xys.print();
assert_eq!(2 + 2, 4);
}
}
// impl MySLAM {
// /// Log probability of Lidar observation
// ///
// fn logp_obs(z: Tensor&, x: Tensor&) -> Tensor {
// let n_directions = z.size()[z.dim() - 1];
// for i in 0..n_directions {
// }
// }
// }
|
#[doc = "Register `DOUTR27` reader"]
pub type R = crate::R<DOUTR27_SPEC>;
#[doc = "Register `DOUTR27` writer"]
pub type W = crate::W<DOUTR27_SPEC>;
#[doc = "Field `DOUT27` reader - Output data sent to MDIO Master during read frames"]
pub type DOUT27_R = crate::FieldReader<u16>;
#[doc = "Field `DOUT27` writer - Output data sent to MDIO Master during read frames"]
pub type DOUT27_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 16, O, u16>;
impl R {
#[doc = "Bits 0:15 - Output data sent to MDIO Master during read frames"]
#[inline(always)]
pub fn dout27(&self) -> DOUT27_R {
DOUT27_R::new((self.bits & 0xffff) as u16)
}
}
impl W {
#[doc = "Bits 0:15 - Output data sent to MDIO Master during read frames"]
#[inline(always)]
#[must_use]
pub fn dout27(&mut self) -> DOUT27_W<DOUTR27_SPEC, 0> {
DOUT27_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "MDIOS output data register 27\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`doutr27::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`doutr27::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct DOUTR27_SPEC;
impl crate::RegisterSpec for DOUTR27_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`doutr27::R`](R) reader structure"]
impl crate::Readable for DOUTR27_SPEC {}
#[doc = "`write(|w| ..)` method takes [`doutr27::W`](W) writer structure"]
impl crate::Writable for DOUTR27_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets DOUTR27 to value 0"]
impl crate::Resettable for DOUTR27_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crypto::PublicKey;
use assets::AssetBundle;
use transactions::components::service::SERVICE_ID;
use error::{Error, ErrorKind};
/// Transaction ID.
pub const TRANSFER_ID: u16 = 200;
evo_message! {
/// `transfer` transaction.
struct Transfer {
const TYPE = SERVICE_ID;
const ID = TRANSFER_ID;
from: &PublicKey,
to: &PublicKey,
amount: u64,
assets: Vec<AssetBundle>,
seed: u64,
memo: &str,
}
}
#[derive(Debug, Clone)]
pub struct TransferWrapper {
from: PublicKey,
to: PublicKey,
amount: u64,
assets: Vec<AssetBundle>,
seed: u64,
memo: String,
}
impl TransferWrapper {
pub fn new(from: &PublicKey, to: &PublicKey, amount: u64, seed: u64, memo: &str) -> Self {
TransferWrapper {
from: *from,
to: *to,
amount: amount,
assets: Vec::new(),
seed: seed,
memo: memo.to_string(),
}
}
pub fn from_ptr<'a>(wrapper: *mut TransferWrapper) -> Result<&'a mut TransferWrapper, Error> {
if wrapper.is_null() {
return Err(Error::new(ErrorKind::Text(
"wrapper isn't initialized".to_string(),
)));
}
Ok(unsafe { &mut *wrapper })
}
pub fn add_asset(&mut self, asset: AssetBundle) {
self.assets.push(asset);
}
pub fn unwrap(&self) -> Transfer {
Transfer::new(
&self.from,
&self.to,
self.amount,
self.assets.clone(),
self.seed,
&self.memo
)
}
}
|
#[cfg(test)]
mod test {
extern crate interior_mut;
use super::*;
use std::cell::RefCell;
struct MockMessenger {
sent_messages: RefCell<Vec<String>>,
}
impl MockMessenger {
fn new() -> MockMessenger {
MockMessenger {
sent_messages: RefCell::new(vec![]),
}
}
}
impl interior_mut::Messenger for MockMessenger {
fn send(&self, message: &str) {
self.sent_messages.borrow_mut().push(String::from(message));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
// --snip--
let mock_messenger = MockMessenger::new();
let mut limit_tracker = interior_mut::LimitTracker::new(&mock_messenger, 100);
limit_tracker.set_value(80);
assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);
}
} |
use radmin::uuid::Uuid;
use serde::{Deserialize, Serialize};
use super::OrganizationInfo as Organization;
use crate::models::Address;
use crate::schema::organization_addresses;
#[derive(
Debug,
PartialEq,
Clone,
Serialize,
Deserialize,
Queryable,
Identifiable,
AsChangeset,
Associations,
)]
#[belongs_to(Organization)]
#[belongs_to(Address)]
#[table_name = "organization_addresses"]
pub struct OrganizationAddress {
pub id: Uuid,
pub organization_id: Uuid,
pub address_id: Uuid,
pub address_type: String,
}
|
#![allow(non_camel_case_types)]
pub use libc::c_char;
pub use libc::c_int;
pub use libc::c_long;
pub use libc::c_ulong;
pub use libc::size_t;
//mod bitset_macro;
pub static TERMKEY_VERSION_MAJOR: c_int = 0;
pub static TERMKEY_VERSION_MINOR: c_int = 17;
#[allow(non_snake_case)]
pub unsafe fn TERMKEY_CHECK_VERSION()
{
termkey_check_version(TERMKEY_VERSION_MAJOR, TERMKEY_VERSION_MINOR);
}
#[repr(C)] #[deriving(PartialEq, PartialOrd)]
pub enum TermKeySym
{
TERMKEY_SYM_UNKNOWN = -1,
TERMKEY_SYM_NONE = 0,
/* Special names in C0 */
TERMKEY_SYM_BACKSPACE,
TERMKEY_SYM_TAB,
TERMKEY_SYM_ENTER,
TERMKEY_SYM_ESCAPE,
/* Special names in G0 */
TERMKEY_SYM_SPACE,
TERMKEY_SYM_DEL,
/* Special keys */
TERMKEY_SYM_UP,
TERMKEY_SYM_DOWN,
TERMKEY_SYM_LEFT,
TERMKEY_SYM_RIGHT,
TERMKEY_SYM_BEGIN,
TERMKEY_SYM_FIND,
TERMKEY_SYM_INSERT,
TERMKEY_SYM_DELETE,
TERMKEY_SYM_SELECT,
TERMKEY_SYM_PAGEUP,
TERMKEY_SYM_PAGEDOWN,
TERMKEY_SYM_HOME,
TERMKEY_SYM_END,
/* Special keys from terminfo */
TERMKEY_SYM_CANCEL,
TERMKEY_SYM_CLEAR,
TERMKEY_SYM_CLOSE,
TERMKEY_SYM_COMMAND,
TERMKEY_SYM_COPY,
TERMKEY_SYM_EXIT,
TERMKEY_SYM_HELP,
TERMKEY_SYM_MARK,
TERMKEY_SYM_MESSAGE,
TERMKEY_SYM_MOVE,
TERMKEY_SYM_OPEN,
TERMKEY_SYM_OPTIONS,
TERMKEY_SYM_PRINT,
TERMKEY_SYM_REDO,
TERMKEY_SYM_REFERENCE,
TERMKEY_SYM_REFRESH,
TERMKEY_SYM_REPLACE,
TERMKEY_SYM_RESTART,
TERMKEY_SYM_RESUME,
TERMKEY_SYM_SAVE,
TERMKEY_SYM_SUSPEND,
TERMKEY_SYM_UNDO,
/* Numeric keypad special keys */
TERMKEY_SYM_KP0,
TERMKEY_SYM_KP1,
TERMKEY_SYM_KP2,
TERMKEY_SYM_KP3,
TERMKEY_SYM_KP4,
TERMKEY_SYM_KP5,
TERMKEY_SYM_KP6,
TERMKEY_SYM_KP7,
TERMKEY_SYM_KP8,
TERMKEY_SYM_KP9,
TERMKEY_SYM_KPENTER,
TERMKEY_SYM_KPPLUS,
TERMKEY_SYM_KPMINUS,
TERMKEY_SYM_KPMULT,
TERMKEY_SYM_KPDIV,
TERMKEY_SYM_KPCOMMA,
TERMKEY_SYM_KPPERIOD,
TERMKEY_SYM_KPEQUALS,
/* et cetera ad nauseum */
TERMKEY_N_SYMS
}
impl ::std::fmt::Show for TermKeySym
{
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result
{
let symi: c_int = unsafe { ::std::mem::transmute(*self) };
let _ = write!(fmt, "{}", symi);
Ok(())
}
}
#[repr(C)]
pub enum TermKeyType
{
TERMKEY_TYPE_UNICODE,
TERMKEY_TYPE_FUNCTION,
TERMKEY_TYPE_KEYSYM,
TERMKEY_TYPE_MOUSE,
TERMKEY_TYPE_POSITION,
TERMKEY_TYPE_MODEREPORT,
/* add other recognised types here */
TERMKEY_TYPE_UNKNOWN_CSI = -1
}
#[repr(C)] #[deriving(PartialEq)]
pub enum TermKeyResult
{
TERMKEY_RES_NONE,
TERMKEY_RES_KEY,
TERMKEY_RES_EOF,
TERMKEY_RES_AGAIN,
TERMKEY_RES_ERROR
}
#[repr(C)] #[deriving(PartialEq, PartialOrd)]
pub enum TermKeyMouseEvent
{
TERMKEY_MOUSE_UNKNOWN,
TERMKEY_MOUSE_PRESS,
TERMKEY_MOUSE_DRAG,
TERMKEY_MOUSE_RELEASE
}
impl ::std::fmt::Show for TermKeyMouseEvent
{
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result
{
let symi: c_int = unsafe { ::std::mem::transmute(*self) };
let _ = write!(fmt, "{}", symi);
Ok(())
}
}
bitset!(X_TermKey_KeyMod: c_int
{
TERMKEY_KEYMOD_SHIFT = 1 << 0,
TERMKEY_KEYMOD_ALT = 1 << 1,
TERMKEY_KEYMOD_CTRL = 1 << 2
})
impl ::std::fmt::Show for X_TermKey_KeyMod
{
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result
{
let symi: c_int = unsafe { ::std::mem::transmute(*self) };
let _ = write!(fmt, "{}", symi);
Ok(())
}
}
#[repr(C)]
pub struct TermKeyKey
{
pub type_: TermKeyType,
pub code: c_long,
/*
union {
long codepoint; /* TERMKEY_TYPE_UNICODE */
int number; /* TERMKEY_TYPE_FUNCTION */
TermKeySym sym; /* TERMKEY_TYPE_KEYSYM */
char mouse[4]; /* TERMKEY_TYPE_MOUSE */
/* opaque. see termkey_interpret_mouse */
} code;
*/
pub modifiers: c_int,
/* Any Unicode character can be UTF-8 encoded in no more than 6 bytes, plus
* terminating NUL */
pub utf8: [c_char, ..7],
}
impl ::std::default::Default for TermKeyKey
{
fn default() -> TermKeyKey
{
TermKeyKey{type_: TERMKEY_TYPE_UNICODE, code: 0, modifiers: 0, utf8: [0, ..7]}
}
}
impl TermKeyKey
{
pub unsafe fn codepoint(&self) -> c_long
{
self.code
}
pub unsafe fn num(&self) -> c_int
{
let s: &c_int = ::std::mem::transmute(&self.code);
*s
}
pub unsafe fn sym(&self) -> TermKeySym
{
let s: &TermKeySym = ::std::mem::transmute(&self.code);
*s
}
}
impl TermKeyKey
{
pub fn from_codepoint(mods: X_TermKey_KeyMod, codepoint: char, utf8: [c_char, ..7]) -> TermKeyKey
{
unsafe
{
let mods: c_int = ::std::mem::transmute(mods);
let codepoint: c_long = codepoint as c_long;
TermKeyKey{type_: TERMKEY_TYPE_UNICODE, code: codepoint, modifiers: mods, utf8: utf8}
}
}
pub fn from_num(mods: X_TermKey_KeyMod, num: int) -> TermKeyKey
{
unsafe
{
let mods: c_int = ::std::mem::transmute(mods);
let num: c_int = num as c_int;
let mut key = TermKeyKey{type_: TERMKEY_TYPE_FUNCTION, code: 0, modifiers: mods, utf8: [0, ..7]};
let code: &mut c_int = ::std::mem::transmute(&mut key.code);
*code = num;
key
}
}
pub fn from_sym(mods: X_TermKey_KeyMod, sym: TermKeySym) -> TermKeyKey
{
unsafe
{
let mods: c_int = ::std::mem::transmute(mods);
let mut key = TermKeyKey{type_: TERMKEY_TYPE_KEYSYM, code: 0, modifiers: mods, utf8: [0, ..7]};
let code: &mut TermKeySym = ::std::mem::transmute(&mut key.code);
*code = sym;
key
}
}
pub fn from_mouse(tk: *mut TermKey, mods: X_TermKey_KeyMod, ev: TermKeyMouseEvent, button: c_int, line: c_int, col: c_int) -> TermKeyKey
{
unsafe
{
let mods: c_int = ::std::mem::transmute(mods);
let mut key = TermKeyKey{type_: TERMKEY_TYPE_UNICODE, code: 0, modifiers: mods, utf8: [0, ..7]};
termkey_construct_mouse(tk, &mut key, ev, button, line, col);
key
}
}
pub fn from_position(tk: *mut TermKey, line: c_int, col: c_int) -> TermKeyKey
{
unsafe
{
let mut key = TermKeyKey{type_: TERMKEY_TYPE_UNICODE, code: 0, modifiers: 0, utf8: [0, ..7]};
termkey_construct_position(tk, &mut key, line, col);
key
}
}
pub fn from_mode_report(tk: *mut TermKey, initial: c_int, mode: c_int, value: c_int) -> TermKeyKey
{
unsafe
{
let mut key = TermKeyKey{type_: TERMKEY_TYPE_UNICODE, code: 0, modifiers: 0, utf8: [0, ..7]};
termkey_construct_modereport(tk, &mut key, initial, mode, value);
key
}
}
}
pub enum TermKey {}
bitset!(X_TermKey_Flag : c_int
{
TERMKEY_FLAG_NOINTERPRET = 1 << 0, /* Do not interpret C0//DEL codes if possible */
TERMKEY_FLAG_CONVERTKP = 1 << 1, /* Convert KP codes to regular keypresses */
TERMKEY_FLAG_RAW = 1 << 2, /* Input is raw bytes, not UTF-8 */
TERMKEY_FLAG_UTF8 = 1 << 3, /* Input is definitely UTF-8 */
TERMKEY_FLAG_NOTERMIOS = 1 << 4, /* Do not make initial termios calls on construction */
TERMKEY_FLAG_SPACESYMBOL = 1 << 5, /* Sets TERMKEY_CANON_SPACESYMBOL */
TERMKEY_FLAG_CTRLC = 1 << 6, /* Allow Ctrl-C to be read as normal, disabling SIGINT */
TERMKEY_FLAG_EINTR = 1 << 7 /* Return ERROR on signal (EINTR) rather than retry */
})
bitset!(X_TermKey_Canon : c_int
{
TERMKEY_CANON_SPACESYMBOL = 1 << 0, /* Space is symbolic rather than Unicode */
TERMKEY_CANON_DELBS = 1 << 1 /* Del is converted to Backspace */
})
bitset!(TermKeyFormat : c_int
{
TERMKEY_FORMAT_LONGMOD = 1 << 0, /* Shift-... instead of S-... */
TERMKEY_FORMAT_CARETCTRL = 1 << 1, /* ^X instead of C-X */
TERMKEY_FORMAT_ALTISMETA = 1 << 2, /* Meta- or M- instead of Alt- or A- */
TERMKEY_FORMAT_WRAPBRACKET = 1 << 3, /* Wrap special keys in brackets like <Escape> */
TERMKEY_FORMAT_SPACEMOD = 1 << 4, /* M Foo instead of M-Foo */
TERMKEY_FORMAT_LOWERMOD = 1 << 5, /* meta or m instead of Meta or M */
TERMKEY_FORMAT_LOWERSPACE = 1 << 6, /* page down instead of PageDown */
TERMKEY_FORMAT_MOUSE_POS = 1 << 8, /* Include mouse position if relevant; @ col,line */
/* Some useful combinations */
TERMKEY_FORMAT_VIM = (TERMKEY_FORMAT_ALTISMETA.bits|TERMKEY_FORMAT_WRAPBRACKET.bits),
TERMKEY_FORMAT_URWID = (TERMKEY_FORMAT_LONGMOD.bits|TERMKEY_FORMAT_ALTISMETA.bits|
TERMKEY_FORMAT_LOWERMOD.bits|TERMKEY_FORMAT_SPACEMOD.bits|TERMKEY_FORMAT_LOWERSPACE.bits)
})
// Better to handle in makefile
//#[link(name = "termkey")]
extern
{
pub fn termkey_check_version(major: c_int, minor: c_int);
pub fn termkey_new(fd: c_int, flags: c_int) -> *mut TermKey;
pub fn termkey_new_abstract(term: *const c_char, flags: c_int) -> *mut TermKey;
pub fn termkey_free(tk: *mut TermKey);
pub fn termkey_destroy(tk: *mut TermKey);
pub fn termkey_start(tk: *mut TermKey) -> c_int;
pub fn termkey_stop(tk: *mut TermKey) -> c_int;
pub fn termkey_is_started(tk: *mut TermKey) -> c_int;
pub fn termkey_get_fd(tk: *mut TermKey) -> c_int;
pub fn termkey_get_flags(tk: *mut TermKey) -> c_int;
pub fn termkey_set_flags(tk: *mut TermKey, newflags: c_int);
pub fn termkey_get_waittime(tk: *mut TermKey) -> c_int;
pub fn termkey_set_waittime(tk: *mut TermKey, msec: c_int);
pub fn termkey_get_canonflags(tk: *mut TermKey) -> c_int;
pub fn termkey_set_canonflags(tk: *mut TermKey, cflags: c_int);
pub fn termkey_get_buffer_size(tk: *mut TermKey) -> size_t;
pub fn termkey_set_buffer_size(tk: *mut TermKey, size: size_t) -> c_int;
pub fn termkey_get_buffer_remaining(tk: *mut TermKey) -> size_t;
pub fn termkey_canonicalise(tk: *mut TermKey, key: *mut TermKeyKey);
pub fn termkey_getkey(tk: *mut TermKey, key: *mut TermKeyKey) -> TermKeyResult;
pub fn termkey_getkey_force(tk: *mut TermKey, key: *mut TermKeyKey) -> TermKeyResult;
pub fn termkey_waitkey(tk: *mut TermKey, key: *mut TermKeyKey) -> TermKeyResult;
pub fn termkey_advisereadable(tk: *mut TermKey) -> TermKeyResult;
pub fn termkey_push_bytes(tk: *mut TermKey, bytes: *const c_char, len: size_t) -> size_t;
pub fn termkey_register_keyname(tk: *mut TermKey, sym: TermKeySym, name: *const c_char) -> TermKeySym;
pub fn termkey_get_keyname(tk: *mut TermKey, sym: TermKeySym) -> *const c_char;
pub fn termkey_lookup_keyname(tk: *mut TermKey, str: *const c_char, sym: *mut TermKeySym) -> *const c_char;
pub fn termkey_keyname2sym(tk: *mut TermKey, keyname: *const c_char) -> TermKeySym;
pub fn termkey_interpret_mouse(tk: *mut TermKey, key: *const TermKeyKey, event: *mut TermKeyMouseEvent, button: *mut c_int, line: *mut c_int, col: *mut c_int) -> TermKeyResult;
pub fn termkey_construct_mouse(tk: *mut TermKey, key: *mut TermKeyKey, event: TermKeyMouseEvent, button: c_int, line: c_int, col: c_int);
pub fn termkey_interpret_position(tk: *mut TermKey, key: *const TermKeyKey, line: *mut c_int, col: *mut c_int) -> TermKeyResult;
pub fn termkey_construct_position(tk: *mut TermKey, key: *mut TermKeyKey, line: c_int, col: c_int);
pub fn termkey_interpret_modereport(tk: *mut TermKey, key: *const TermKeyKey, initial: *mut c_int, mode: *mut c_int, value: *mut c_int) -> TermKeyResult;
pub fn termkey_construct_modereport(tk: *mut TermKey, key: *mut TermKeyKey, initial: c_int, mode: c_int, value: c_int);
pub fn termkey_interpret_csi(tk: *mut TermKey, key: *const TermKeyKey, args: *mut c_long, nargs: *mut size_t, cmd: *mut c_ulong) -> TermKeyResult;
pub fn termkey_strfkey(tk: *mut TermKey, buffer: *mut c_char, len: size_t, key: *mut TermKeyKey, format: TermKeyFormat) -> size_t;
pub fn termkey_strpkey(tk: *mut TermKey, str: *const c_char, key: *mut TermKeyKey, format: TermKeyFormat) -> *const c_char;
pub fn termkey_keycmp(tk: *mut TermKey, key1: *const TermKeyKey, key2: *const TermKeyKey) -> c_int;
}
|
use amethyst::core::transform::Transform;
use amethyst::prelude::World;
use amethyst::prelude::WorldExt;
use amethyst::ecs::Entity;
pub trait CanTransform {
fn set_position(&mut self,position:(f32,f32,f32));
fn get_entity(&self)-> Entity;
fn set_rotation(&mut self, dir: RotateDirection, rad: f32);
}
#[derive(Copy, Clone)]
pub enum RotateDirection {
Vertical,
Horizontal
}
pub fn r#move(world: &mut World, movable: &mut impl CanTransform, position:(f32, f32, f32)){
let mut storage = world.write_storage::<Transform>();
let transform = storage.get_mut(movable.get_entity()).expect("Failed to get transform for the entity");
movable.set_position(position);
transform.set_translation_xyz(position.0,position.1,position.2);
}
pub fn rotate(world: &mut World, rotatable: &mut impl CanTransform, dir: RotateDirection, rad: f32 ){
let mut storage = world.write_storage::<Transform>();
let transform = storage.get_mut(rotatable.get_entity()).expect("Failed to get transform for the entity");
rotatable.set_rotation(dir, rad);
match dir {
RotateDirection::Horizontal=>{
transform.append_rotation_y_axis(rad);
}
RotateDirection::Vertical=>{
transform.append_rotation_x_axis(rad);
}
};
} |
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use serum_common::pack::*;
use solana_client_gen::prelude::*;
#[derive(Debug, Clone, Copy, BorshSerialize, BorshDeserialize, BorshSchema, PartialEq)]
pub enum FundType {
/// similar to a gofundme
FundMe,
Raise {
private: bool,
},
}
impl Default for FundType {
fn default() -> Self {
FundType::FundMe
}
}
/// The Owner of the fund has the right to withdraw all or some of the funds
#[derive(Default, Debug, BorshSerialize, BorshDeserialize, BorshSchema)]
pub struct Fund {
/// check to see if a fund is ininitialized
pub initialized: bool,
/// open defines if a fund is open for deposits
pub open: bool,
/// type of fund
pub fund_type: FundType,
/// fund Owner
pub owner: Pubkey,
/// Owner authority
pub authority: Pubkey,
/// max size of the fund
pub max_balance: u64,
/// balance of the
pub balance: u64,
/// Nonce of the program account
pub nonce: u8,
/// Mint
pub mint: Pubkey,
/// Address of the token vault controlled by the Safe.
pub vault: Pubkey,
/// Params
/// shares, shares increment with investment, but do not decrement with withdraw
pub shares: u64,
/// nft account
pub nft_account: Pubkey,
/// nft mint
pub nft_mint: Pubkey,
/// whitelist represents a list of pubkeys that can deposit into a fund
pub whitelist: Pubkey,
/// Payback info
pub paybacks: Vec<Payback>,
/// round refers to the round of payback
pub round: u32,
}
impl Fund {
pub fn deduct(&mut self, amount: u64) {
if self.balance > 0 {
self.balance -= amount;
}
}
/// Add adds the depoist amount to the total balance and shares
pub fn add(&mut self, amount: u64) {
self.balance += amount;
if self.fund_type.eq(&FundType::Raise { private: true })
|| self.fund_type.eq(&FundType::Raise { private: false })
{
self.shares += amount;
}
}
/// close_fund is called when the owner starts the withdrawl process
pub fn close_fund(&mut self) {
if self.open {
self.open = false;
}
}
pub fn add_new_payback(&mut self, total: u64, per_share: u64) {
let pb = Payback::new(total, per_share);
self.paybacks.push(pb);
self.round += 1;
}
}
serum_common::packable!(Fund);
#[derive(Default, Debug, BorshSerialize, BorshDeserialize, BorshSchema)]
pub struct Payback {
/// total of the paybck
pub total: u64,
/// per_share
pub per_share: u64,
}
impl Payback {
pub fn new(total: u64, per_share: u64) -> Self {
Payback { total, per_share }
}
pub fn add_total(&mut self, amount: u64) {
self.total += amount;
}
pub fn add_payback_per_share(&mut self, amount: u64) {
self.per_share += amount;
}
}
|
mod camera;
mod mask_renderer;
mod model_matrix;
mod program;
mod view_renderer;
mod webgl;
use crate::{
block::{self, BlockId},
resource,
};
pub use camera::Camera;
use mask_renderer::MaskRenderer;
pub use mask_renderer::TableBlock;
use model_matrix::ModelMatrix;
use ndarray::{arr1, Array2};
use std::rc::Rc;
use view_renderer::ViewRenderer;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use webgl::WebGlRenderingContext;
pub struct Renderer {
gl: Rc<WebGlRenderingContext>,
view_renderer: ViewRenderer,
mask_renderer: MaskRenderer,
}
impl Renderer {
pub fn new(canvas: web_sys::HtmlCanvasElement) -> Self {
let option = object! {stencil: true};
let option: js_sys::Object = option.into();
let gl = canvas
.get_context_with_context_options("webgl", &option.into())
.unwrap()
.unwrap()
.dyn_into::<web_sys::WebGlRenderingContext>()
.unwrap();
gl.get_extension("EXT_frag_depth")
.map_err(|err| crate::debug::log_1(&err))
.unwrap()
.unwrap();
let gl = Rc::new(WebGlRenderingContext(gl));
let view_renderer = ViewRenderer::new(&gl);
let mask_renderer = MaskRenderer::new();
Self {
gl,
view_renderer,
mask_renderer,
}
}
pub fn table_object_id(
&self,
canvas_size: &[f32; 2],
position: &[f32; 2],
) -> Option<&TableBlock> {
self.mask_renderer.table_object_id(canvas_size, position)
}
pub fn table_position(
vertex: &[f32; 3],
movement: &[f32; 3],
camera: &Camera,
canvas_size: &[f32; 2],
is_billboard: bool,
) -> [f32; 3] {
let vp_matrix = camera
.perspective_matrix(&canvas_size)
.dot(&camera.view_matrix());
let model_matrix: Array2<f32> = if is_billboard {
ModelMatrix::new()
.with_x_axis_rotation(camera.x_axis_rotation() - std::f32::consts::FRAC_PI_2)
.with_z_axis_rotation(camera.z_axis_rotation())
.with_movement(&movement)
.into()
} else {
ModelMatrix::new().with_movement(&movement).into()
};
let mvp_matrix = vp_matrix.dot(&model_matrix);
let screen_position = mvp_matrix.dot(&arr1(&[vertex[0], vertex[1], vertex[2], 1.0]));
[
screen_position[0] / screen_position[3],
screen_position[1] / screen_position[3],
screen_position[2],
]
}
pub async fn render(
&mut self,
block_arena: &block::Arena,
resource_arena: &resource::Arena,
world_id: &BlockId,
camera: &Camera,
canvas_size: &[f32; 2],
floating_object: &Option<&BlockId>,
client_id: &String,
) {
if Rc::strong_count(&self.gl) < 3 {
block_arena
.map(world_id, {
let block_arena = block::Arena::clone(&block_arena);
let resource_arena = resource::Arena::clone(&resource_arena);
move |world: &block::world::World| async move {
self.view_renderer.render(
&self.gl,
&canvas_size,
&camera,
&block_arena,
&resource_arena,
world,
client_id,
);
self.mask_renderer.render(
&canvas_size,
&camera,
block_arena,
world,
floating_object,
client_id,
);
let view_gl = Rc::clone(&self.gl);
let mask_gl = self.mask_renderer.gl();
let a = Closure::once(Box::new(move || {
view_gl.flush();
mask_gl.flush();
}) as Box<dyn FnOnce()>);
let _ = web_sys::window()
.unwrap()
.request_animation_frame(a.as_ref().unchecked_ref());
a.forget();
}
})
.await;
}
}
}
|
use super::prelude::*;
pub(crate) fn config(cfg: &mut web::ServiceConfig) {
cfg.service(show_executor_groups)
.service(show_executor_group_detail)
.service(create_executor_group)
.service(update_executor_group)
.service(delete_executor_group);
}
#[post("/api/executor_group/create")]
async fn create_executor_group(
web::Json(executor_group): web::Json<model::NewExecutorGroup>,
pool: ShareData<db::ConnectionPool>,
) -> HttpResponse {
use db::schema::executor_group;
if let Ok(conn) = pool.get() {
return HttpResponse::Ok().json(Into::<UnifiedResponseMessages<u64>>::into(
web::block(move || {
diesel::insert_into(executor_group::table)
.values(&executor_group)
.execute(&conn)?;
diesel::select(db::last_insert_id).get_result::<u64>(&conn)
})
.await,
));
}
HttpResponse::Ok().json(UnifiedResponseMessages::<()>::error())
}
#[post("/api/executor_group/list")]
async fn show_executor_groups(
web::Json(query_params): web::Json<model::QueryParamsExecutorGroup>,
pool: ShareData<db::ConnectionPool>,
) -> HttpResponse {
if let Ok(conn) = pool.get() {
return HttpResponse::Ok().json(Into::<
UnifiedResponseMessages<PaginateData<model::ExecutorGroup>>,
>::into(
web::block::<_, _, diesel::result::Error>(move || {
let query_builder = model::ExecutorGroupQueryBuilder::query_all_columns();
let executor_groups = query_params
.clone()
.query_filter(query_builder)
.paginate(query_params.page)
.set_per_page(query_params.per_page)
.load::<model::ExecutorGroup>(&conn)?;
let per_page = query_params.per_page;
let count_builder = model::ExecutorGroupQueryBuilder::query_count();
let count = query_params
.query_filter(count_builder)
.get_result::<i64>(&conn)?;
Ok(PaginateData::<model::ExecutorGroup>::default()
.set_data_source(executor_groups)
.set_page_size(per_page)
.set_total(count))
})
.await,
));
}
HttpResponse::Ok().json(UnifiedResponseMessages::<PaginateData<model::ExecutorGroup>>::error())
}
#[post("/api/executor_group/detail")]
async fn show_executor_group_detail(
web::Json(model::ExecutorGroupId { executor_group_id }): web::Json<model::ExecutorGroupId>,
pool: ShareData<db::ConnectionPool>,
) -> HttpResponse {
let executor_group_detail_result =
pre_show_executor_group_detail(executor_group_id, pool).await;
if let Ok(executor_group_detail) = executor_group_detail_result {
return HttpResponse::Ok().json(
UnifiedResponseMessages::<model::ExecutorGroupDetail>::success_with_data(
executor_group_detail,
),
);
};
HttpResponse::Ok().json(
UnifiedResponseMessages::<()>::error()
.customized_error_msg(executor_group_detail_result.expect_err("").to_string()),
)
}
async fn pre_show_executor_group_detail(
executor_group_id: i64,
pool: ShareData<db::ConnectionPool>,
) -> Result<model::ExecutorGroupDetail, CommonError> {
use db::schema::{executor_group, executor_processor, executor_processor_bind};
let conn = pool.get()?;
let executor_group_detail: model::ExecutorGroupDetail =
web::block::<_, _, diesel::result::Error>(move || {
let executor_group_detail_inner = executor_group::table
.select(executor_group::all_columns)
.find(executor_group_id)
.first::<model::ExecutorGroup>(&conn)?;
let bindings = executor_processor_bind::table
.inner_join(executor_processor::table)
.filter(executor_processor_bind::group_id.eq(executor_group_id))
.select((
executor_processor_bind::id,
executor_processor_bind::name,
executor_processor_bind::executor_id,
executor_processor_bind::weight,
executor_processor::name,
executor_processor::host,
executor_processor::machine_id,
))
.load::<model::ExecutorGroupBinding>(&conn)?;
Ok(model::ExecutorGroupDetail {
inner: executor_group_detail_inner,
bindings,
})
})
.await?;
Ok(executor_group_detail)
}
#[post("/api/executor_group/update")]
async fn update_executor_group(
web::Json(executor_group): web::Json<model::UpdateExecutorGroup>,
pool: ShareData<db::ConnectionPool>,
) -> HttpResponse {
if let Ok(conn) = pool.get() {
return HttpResponse::Ok().json(Into::<UnifiedResponseMessages<usize>>::into(
web::block(move || {
diesel::update(&executor_group)
.set(&executor_group)
.execute(&conn)
})
.await,
));
}
HttpResponse::Ok().json(UnifiedResponseMessages::<usize>::error())
}
#[post("/api/executor_group/delete")]
async fn delete_executor_group(
web::Json(model::ExecutorGroupId { executor_group_id }): web::Json<model::ExecutorGroupId>,
pool: ShareData<db::ConnectionPool>,
) -> HttpResponse {
use db::schema::executor_group::dsl::*;
if let Ok(conn) = pool.get() {
return HttpResponse::Ok().json(Into::<UnifiedResponseMessages<usize>>::into(
web::block(move || {
// Cannot link to delete internal bindings, otherwise it will cause data misalignment.
diesel::delete(executor_group.find(executor_group_id)).execute(&conn)
})
.await,
));
}
HttpResponse::Ok().json(UnifiedResponseMessages::<usize>::error())
}
|
//! Counts the number of points in a las file.
extern crate las;
use las::{Read, Reader};
fn main() {
let path = std::env::args()
.skip(1)
.next()
.expect("Must provide a path to a las file");
let mut reader = Reader::from_path(path).expect("Unable to open reader");
let npoints = reader
.points()
.map(|p| p.expect("Unable to read point"))
.count();
println!("Number of points: {}", npoints);
}
|
use std::collections::HashMap;
use super::dom::{ ElementData, Node, NodeType };
use super::css::{ Selector, SimpleSelector, Rule, Specificity, Stylesheet, Value };
pub type PropertyMap = HashMap<String, Value>;
pub enum Display {
Inline,
Block,
None,
}
#[derive(Debug)]
pub struct StyleNode<'a> {
pub node: &'a Node,
pub specified_values: PropertyMap,
pub children: Vec<StyleNode<'a>>,
}
impl<'a> StyleNode<'a> {
pub fn value(&self, name: &str) -> Option<Value> {
self.specified_values.get(name).map(|v| v.clone())
}
pub fn display(&self) -> Display {
match self.value("display") {
Some(Value::Keyword(s)) => match &*s {
"block" => Display::Block,
"none" => Display::None,
_ => Display::Inline,
},
_ => Display::Inline
}
}
pub fn lookup(&self, name: &str, fallback_name: &str, default: &Value) -> Value {
self.value(name).unwrap_or_else(|| self.value(fallback_name)
.unwrap_or_else(|| default.clone()))
}
}
pub fn style_tree<'a>(root: &'a Node, stylesheet: &'a Stylesheet) -> StyleNode<'a> {
StyleNode {
node: root,
specified_values: match root.node_type {
NodeType::Element(ref elem) => specified_values(elem, &stylesheet),
NodeType::Text(_) => HashMap::new(),
},
children: root.children.iter().map(|child| style_tree(child, stylesheet)).collect()
}
}
fn specified_values(elem: &ElementData, stylesheet: &Stylesheet) -> PropertyMap {
let mut values = HashMap::new();
let mut rules = match_rules(elem, stylesheet);
rules.sort_by(|&(a, _), &(b, _)| a.cmp(&b) );
for (_, rule) in rules {
for declaration in &rule.declarations {
values.insert(declaration.name.clone(), declaration.value.clone());
}
}
return values;
}
type MatchedRule<'a> = (Specificity, &'a Rule);
fn match_rules<'a>(elem: &'a ElementData, stylesheet: &'a Stylesheet) -> Vec<MatchedRule<'a>> {
stylesheet.rules.iter()
.filter_map(|rule| match_rule(elem, rule)).collect()
}
fn match_rule<'a>(elem: &'a ElementData, rule: &'a Rule) -> Option<MatchedRule<'a>> {
rule.selectors.iter().find(|selector| matches(elem, *selector))
.map(|selector| (selector.specificity(), rule))
}
fn matches(elem: &ElementData, selector: &Selector) -> bool {
match *selector {
Selector::Simple(ref simple_selector) => matches_simple_selector(elem, simple_selector)
}
}
fn matches_simple_selector(elem: &ElementData, selector: &SimpleSelector) -> bool {
if selector.tag_name.iter().any(|name| elem.tag_name != *name) {
return false;
}
if selector.id.iter().any(|id| elem.id() != Some(id)) {
return false;
}
let classes = elem.classes();
if selector.class.iter().any(|class| !classes.contains(&**class)) {
return false;
}
return true;
} |
use super::*;
#[test]
fn test_decode_add() {
let inst = decode(&vec!(1,2,3,4)[..], 0).unwrap();
assert_eq!(inst, Inst::Add(InParam::Position(2), InParam::Position(3), OutParam::Position(4)));
let inst = decode(&vec!(101,2,3,4)[..], 0).unwrap();
assert_eq!(inst, Inst::Add(InParam::Immediate(2), InParam::Position(3), OutParam::Position(4)));
let inst = decode(&vec!(1001,2,3,4)[..], 0).unwrap();
assert_eq!(inst, Inst::Add(InParam::Position(2), InParam::Immediate(3), OutParam::Position(4)));
}
#[test]
fn test_decode_mult() {
let inst = decode(&vec!(2,2,3,4)[..], 0).unwrap();
assert_eq!(inst, Inst::Mult(InParam::Position(2), InParam::Position(3), OutParam::Position(4)));
let inst = decode(&vec!(102,2,3,4)[..], 0).unwrap();
assert_eq!(inst, Inst::Mult(InParam::Immediate(2), InParam::Position(3), OutParam::Position(4)));
let inst = decode(&vec!(1002,2,3,4)[..], 0).unwrap();
assert_eq!(inst, Inst::Mult(InParam::Position(2), InParam::Immediate(3), OutParam::Position(4)));
}
#[test]
fn test_decode_input() {
let inst = decode(&vec!(3,0)[..], 0).unwrap();
assert_eq!(inst, Inst::Input(OutParam::Position(0)));
}
#[test]
fn test_decode_output() {
let inst = decode(&vec!(4,0)[..], 0).unwrap();
assert_eq!(inst, Inst::Output(InParam::Position(0)));
let inst = decode(&vec!(104,0)[..], 0).unwrap();
assert_eq!(inst, Inst::Output(InParam::Immediate(0)));
}
#[test]
fn test_decode_jumpiftrue() {
let inst = decode(&vec!(5,1,2)[..], 0).unwrap();
assert_eq!(inst, Inst::JumpIfTrue(InParam::Position(1), InParam::Position(2)));
let inst = decode(&vec!(105,1,2)[..], 0).unwrap();
assert_eq!(inst, Inst::JumpIfTrue(InParam::Immediate(1), InParam::Position(2)));
let inst = decode(&vec!(1105,1,2)[..], 0).unwrap();
assert_eq!(inst, Inst::JumpIfTrue(InParam::Immediate(1), InParam::Immediate(2)));
}
#[test]
fn test_decode_jumpiffalse() {
let inst = decode(&vec!(6,1,2)[..], 0).unwrap();
assert_eq!(inst, Inst::JumpIfFalse(InParam::Position(1), InParam::Position(2)));
let inst = decode(&vec!(106,1,2)[..], 0).unwrap();
assert_eq!(inst, Inst::JumpIfFalse(InParam::Immediate(1), InParam::Position(2)));
let inst = decode(&vec!(1106,1,2)[..], 0).unwrap();
assert_eq!(inst, Inst::JumpIfFalse(InParam::Immediate(1), InParam::Immediate(2)));
}
#[test]
fn test_decode_lessthan() {
let inst = decode(&vec!(7,1,2,3)[..], 0).unwrap();
assert_eq!(inst, Inst::LessThan(InParam::Position(1), InParam::Position(2), OutParam::Position(3)));
let inst = decode(&vec!(107,1,2,3)[..], 0).unwrap();
assert_eq!(inst, Inst::LessThan(InParam::Immediate(1), InParam::Position(2), OutParam::Position(3)));
let inst = decode(&vec!(1107,1,2,3)[..], 0).unwrap();
assert_eq!(inst, Inst::LessThan(InParam::Immediate(1), InParam::Immediate(2), OutParam::Position(3)));
}
#[test]
fn test_decode_equal() {
let inst = decode(&vec!(8,1,2,3)[..], 0).unwrap();
assert_eq!(inst, Inst::Equal(InParam::Position(1), InParam::Position(2), OutParam::Position(3)));
let inst = decode(&vec!(108,1,2,3)[..], 0).unwrap();
assert_eq!(inst, Inst::Equal(InParam::Immediate(1), InParam::Position(2), OutParam::Position(3)));
let inst = decode(&vec!(1108,1,2,3)[..], 0).unwrap();
assert_eq!(inst, Inst::Equal(InParam::Immediate(1), InParam::Immediate(2), OutParam::Position(3)));
}
#[test]
fn provided_case_1() {
let mut c = Computer::new(vec!(1,9,10,3,2,3,11,0,99,30,40,50));
c.run().unwrap();
assert_eq!(c.mem, vec!(3500,9,10,70,2,3,11,0,99,30,40,50));
}
#[test]
fn provided_case_2() {
let mut c = Computer::new(vec!(1,0,0,0,99));
c.run().unwrap();
assert_eq!(c.mem, vec!(2,0,0,0,99));
}
#[test]
fn run_with_io() {
// single input
let mut computer = Computer::new(vec!(3,1,99));
computer.input.push_back(7);
computer.run().unwrap();
assert_eq!(computer.mem, vec!(3,7,99));
assert_eq!(computer.output.len(), 0);
// input + output
let mut computer = Computer::new(vec!(3,5,104,10,4,11,99));
computer.input.push_back(0);
computer.run().unwrap();
assert_eq!(computer.mem, vec!(3,5,104,10,4,0,99));
assert_eq!(computer.take_output(), vec!(10,3));
}
#[test]
fn run_with_multiple_io() {
// multiple inputs, multiple outputs
let mut c = Computer::new(vec!(3,13,3,14,3,15,4,15,4,14,4,13,99,0,0,0));
c.input.push_back(22);
c.input.push_back(33);
c.input.push_back(44);
c.run().unwrap();
assert_eq!(c.mem, vec!(3,13,3,14,3,15,4,15,4,14,4,13,99,22,33,44));
assert_eq!(c.take_output(), vec!(44,33,22));
}
#[test]
fn run_with_branches() {
let mut c = Computer::new(vec!(
1001,12,-1,12, // [12] = ADD [12],-1
108,0,12,13, // [13] = EQ 0,[12]
1006,13,0, // IF ![13] GOTO 0
99, // EXIT
10,0)); // 12, 13
c.run().unwrap();
assert_eq!(c.mem, vec!(1001,12,-1,12,108,0,12,13,1006,13,0,99,0,1));
}
#[test]
fn run_with_comparisons() {
let mut c = Computer::new(vec!(3,9,8,9,10,9,4,9,99,-1,8));
c.input.push_back(7);
c.run().unwrap();
assert_eq!(c.take_output(), vec!(0));
let mut c = Computer::new(vec!(3,9,8,9,10,9,4,9,99,-1,8));
c.input.push_back(8);
c.run().unwrap();
assert_eq!(c.take_output(), vec!(1));
}
#[test]
fn day9_case_1() {
// takes no input and produces a copy of itself as output
let input = vec!(109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99);
let mut c = Computer::new(input.clone());
c.run().unwrap();
assert_eq!(input, c.take_output());
}
#[test]
fn day9_case_2() {
// should output a 16-digit number
let mut c = Computer::new(vec!(1102,34915192,34915192,7,4,7,99,0));
c.run().unwrap();
let output_as_string = format!("{}", c.take_output()[0]);
assert_eq!(output_as_string.len(), 16);
}
#[test]
fn day9_case_3() {
let mut c = Computer::new(vec!(104,1125899906842624,99));
c.run().unwrap();
assert_eq!(c.take_output()[0], 1125899906842624);
} |
mod filter;
mod searchable;
pub use self::{filter::*, searchable::*};
|
//! This module contains macros which implements `egml!` macro
//! and JSX-like templates.
#![allow(non_camel_case_types, dead_code)]
use crate::egml::{Component, Node, Comp, Rect, Circle, Path, Group, Text, Word, Listener};
#[macro_export]
macro_rules! egml_impl {
// Start of component tag
($state:ident (< $comp:ty : $($tail:tt)*)) => {
#[allow(unused_mut)]
let mut pair = $crate::egml::Comp::lazy::<$comp>();
$crate::egml_impl! { @comp $state $comp, pair ($($tail)*) }
};
// Set a whole struct as a properties
(@comp $state:ident $comp:ty, $pair:ident (with $props:ident, $($tail:tt)*)) => {
$pair.0 = $props;
$crate::egml_impl! { @comp $state $comp, $pair ($($tail)*) }
};
(@comp $state:ident $comp:ty, $pair:ident (id = $val:expr, $($tail:tt)*)) => {
($pair.1).inner_mut::<$comp>().id = $crate::egml::Converter::convert($val);
$crate::egml_impl! { @comp $state $comp, $pair ($($tail)*) }
};
(@comp $state:ident $comp:ty, $pair:ident (modifier = | $this:pat, $model:ident | $handler:expr, $($tail:tt)*)) => {
$crate::egml_impl! { @comp $state $comp, $pair (modifier = | $this, $model : $comp | $handler, $($tail)*) }
};
(@comp $state:ident $comp:ty, $pair:ident (modifier = | $this:pat, $model:ident : $pcm:ty | $handler:expr, $($tail:tt)*)) => {
($pair.1).modifier = Some(move |$this: &mut $crate::egml::Comp, $model: &dyn $crate::egml::AnyModel| {
let $model = $model.as_any().downcast_ref::<$pcm>()
.expect(concat!("Modifier of ", stringify!($comp), " can't downcast model to ", stringify!($pcm)));
$handler
});
$crate::egml_impl! { @comp $state $comp, $pair ($($tail)*) }
};
(@comp $state:ident $comp:ty, $pair:ident (modifier = for <$pcm:ty> $handler:ident, $($tail:tt)*)) => {
$crate::egml_impl! { @comp $state $comp, $pair (modifier = | this, model : $pcm | $handler(this, model), $($tail)*) }
};
(@comp $state:ident $comp:ty, $pair:ident (modifier = for <$pcm:ty> $handler:expr, $($tail:tt)*)) => {
$crate::egml_impl! { @comp $state $comp, $pair (modifier = | this, model : $pcm | ($handler)(this, model), $($tail)*) }
};
(@comp $state:ident $comp:ty, $pair:ident (pass_up = | $msg:ident | $handler:expr, $($tail:tt)*)) => {
($pair.1).inner_mut::<$comp>().pass_up_handler = Some(move |$msg: &dyn $crate::egml::AnyMessage| {
let $msg = $msg.as_any().downcast_ref::<<$comp as $crate::egml::Component>::Message>()
.expect(concat!("Pass up handler of ", stringify!($comp), " can't downcast msg to ", stringify!($comp::Message)))
.clone();
Box::new($handler) as Box<dyn $crate::egml::AnyMessage>
});
$crate::egml_impl! { @comp $state $comp, $pair ($($tail)*) }
};
// Set a specific field as a property.
// It uses `Transformer` trait to convert a type used in template to a type of the field.
(@comp $state:ident $comp:ty, $pair:ident ($attr:ident = $val:expr, $($tail:tt)*)) => {
// It cloned for ergonomics in templates. Attribute with
// `self.param` value could be reused and sholdn't be cloned
// by yourself
($pair.0).$attr = $crate::egml::comp::Transformer::<$comp, _, _>::transform(&mut $pair.1, $val);
$crate::egml_impl! { @comp $state $comp, $pair ($($tail)*) }
};
// Self-closing of tag
(@comp $state:ident $comp:ty, $pair:ident (/ > $($tail:tt)*)) => {
let (props, mut comp) = $pair;
comp.inner_mut::<$comp>().init(props);
$state.init_inner_comp::<$comp>(&mut comp);
$state.stack.push(comp.into());
$crate::egml::macros::child_to_parent(&mut $state.stack, None);
$crate::egml_impl! { $state ($($tail)*) }
};
// Start of opening prim tag
($state:ident (< $starttag:ident $($tail:tt)*)) => {
let prim = $crate::egml::Prim::new(stringify!($starttag), $crate::egml::macros::$starttag::default().into());
$state.stack.push(prim.into());
$crate::egml_impl! { @prim $state $starttag ($($tail)*) }
};
(@prim $state:ident $shape:ident (modifier = | $this:pat, $model:ident : $cm:ty | $handler:expr, $($tail:tt)*)) => {
$crate::egml_impl! { $state $shape (false, modifier = |$this, $model:$cm| $handler, $($tail)*) }
$crate::egml_impl! { @prim $state $shape ($($tail)*) }
};
(@prim $state:ident $shape:ident (modifier = for <$cm:ty> $handler:ident, $($tail:tt)*)) => {
$crate::egml_impl! { @prim $state $shape (modifier = |this, model:$cm| $handler(this, model), $($tail)*) }
};
(@prim $state:ident $shape:ident (modifier = for <$cm:ty> $handler:expr, $($tail:tt)*)) => {
$crate::egml_impl! { @prim $state $shape (modifier = |this, model:$cm| ($handler)(this, model), $($tail)*) }
};
// Events:
(@prim $state:ident $shape:ident (onclick = | $var:pat | $handler:expr, $($tail:tt)*)) => {
$crate::egml_impl! { @prim $state $shape ((onclick) = move | $var: $crate::egml::event::ClickEvent | $handler, $($tail)*) }
};
// PATTERN: (action)=expression,
(@prim $state:ident $shape:ident (($action:ident) = $handler:expr, $($tail:tt)*)) => {
// Catch value to a separate variable for clear error messages
let handler = $handler;
let listener = $crate::egml::event::listener::$action(handler);
$crate::egml::macros::attach_listener(&mut $state.stack, Box::new(listener));
$crate::egml_impl! { @prim $state $shape ($($tail)*) }
};
(@prim $state:ident $shape:ident ($attr:ident = $val:expr, $($tail:tt)*)) => {
$crate::set_attr!($state, $shape.$attr = $crate::egml::Converter::convert($val));
$crate::egml_impl! { @prim $state $shape ($($tail)*) }
};
// End of openging tag
(@prim $state:ident $shape:ident (> $($tail:tt)*)) => {
$crate::egml_impl! { $state ($($tail)*) }
};
// Self-closing of tag
(@prim $state:ident $shape:ident (/ > $($tail:tt)*)) => {
$crate::egml::macros::child_to_parent(&mut $state.stack, None);
$crate::egml_impl! { $state ($($tail)*) }
};
// Traditional tag closing
($state:ident (< / $endtag:ident > $($tail:tt)*)) => {
let endtag = stringify!($endtag);
$crate::egml::macros::child_to_parent(&mut $state.stack, Some(endtag));
$crate::egml_impl! { $state ($($tail)*) }
};
// PATTERN: { for expression }
($state:ident ({ for $eval:expr } $($tail:tt)*)) => {
let nodes = $eval;
let mut prim = $crate::egml::Prim::new("list group", $crate::egml::Group::default().into());
for node in nodes {
prim.add_child($crate::egml::Node::from(node));
}
$crate::egml::macros::add_child(&mut $state.stack, prim.into());
$crate::egml_impl! { $state ($($tail)*) }
};
// PATTERN: { expression }
($state:ident ({ $eval:expr } $($tail:tt)*)) => {
let node = $crate::egml::Node::from($eval);
$crate::egml::macros::add_child(&mut $state.stack, node);
$crate::egml_impl! { $state ($($tail)*) }
};
($state:ident (. $shape:ident . modifier = | $this:pat, $model:ident : $cm:ty | $handler:expr, $($tail:tt)*)) => {
$crate::egml_impl! { $state $shape (true, modifier = |$this, $model:$cm| $handler, $($tail)*) }
$crate::egml_impl! { $state ($($tail)*) }
};
($state:ident $shape:ident ($for_child:expr, modifier = | $this:pat, $model:ident : $cm:ty | $handler:expr, $($tail:tt)*)) => {
$crate::set_child_attr!($state, $for_child, $shape.modifier = Some(move |$this: &mut $crate::egml::macros::$shape, $model: &dyn $crate::egml::AnyModel| {
let $model = $model.as_any().downcast_ref::<$cm>()
.expect(concat!("Modifier of ", stringify!($shape), " can't downcast model to ", stringify!($cm)));
$handler
}));
};
// "End of paring" rule
($state:ident ()) => {
$crate::egml::macros::unpack($state.stack)
};
($state:ident $($tail:tt)*) => {
compile_error!("You should use curly bracets for text nodes: <a>{ \"Link\" }</a>");
};
}
// This entrypoint and implementation had separated to prevent infinite recursion.
#[macro_export]
macro_rules! egml {
($($tail:tt)*) => {{
let mut state = $crate::macros::State { stack: Vec::new() };
$crate::egml_impl! { state ($($tail)*) }
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! set_attr {
($state:ident, $shape:ident.$attr:ident = $val:expr) => {
$crate::set_child_attr!($state, false, $shape.$attr = $val);
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! set_child_attr {
($state:ident, $for_child:expr, $shape:ident.$attr:ident = $val:expr) => {
{
let last = $state.stack.last_mut()
.and_then(|node| if $for_child {
if let &mut Node::Prim(ref mut prim) = node {
prim.childs.last_mut()
} else {
None
}
} else {
Some(node)
});
if let Some(&mut Node::Prim(ref mut prim)) = last {
if let Some(shape) = prim.shape.as_ref_mut().$shape() {
shape.$attr = $val;
} else {
panic!("no shape '{}' to set attribute '{}'", stringify!($shape), stringify!($attr));
}
} else {
panic!("no prim to set attribute: {}", stringify!($attr));
}
}
};
}
pub type Stack<M> = Vec<Node<M>>;
pub struct State<M: Component> {
pub stack: Stack<M>,
}
impl<M: Component> State<M> {
pub fn init_inner_comp<CM: Component>(&self, comp: &mut Comp) {
comp.inner_mut::<CM>().init_as_child::<M>();
}
}
pub type rect = Rect;
pub type circle = Circle;
pub type path = Path;
pub type group = Group;
pub type text = Text;
pub type word = Word;
#[doc(hidden)]
pub fn unpack<MC: Component>(mut stack: Stack<MC>) -> Node<MC> {
if stack.len() != 1 {
panic!("exactly one element have to be in hgml!");
}
stack.pop().expect("no hgml elements in the stack")
}
#[doc(hidden)]
pub fn attach_listener<MC: Component>(stack: &mut Stack<MC>, listener: Box<dyn Listener<MC>>) {
if let Some(&mut Node::Prim(ref mut prim)) = stack.last_mut() {
prim.add_listener(listener);
} else {
panic!("no prim to attach listener: {:?}", listener);
}
}
#[doc(hidden)]
pub fn add_child<MC: Component>(stack: &mut Stack<MC>, child: Node<MC>) {
match stack.last_mut() {
Some(&mut Node::Prim(ref mut prim)) => {
prim.add_child(child);
}
// Some(&mut Node::VList(ref mut vlist)) => {
// vlist.add_child(child);
// }
_ => {
panic!("parent must be a prim or a fragment to add the node: {:?}", child);
}
}
}
#[doc(hidden)]
pub fn child_to_parent<MC: Component>(stack: &mut Stack<MC>, endtag: Option<&'static str>) {
if let Some(mut node) = stack.pop() {
// Check the enclosing prim
// TODO Check it during compilation. Possible?
if let (&mut Node::Prim(ref mut prim), Some(endtag)) = (&mut node, endtag) {
let starttag = prim.name();
if !starttag.eq_ignore_ascii_case(endtag) {
panic!("wrong closing tag: <{}> -> </{}>", starttag, endtag);
}
}
// Push the popped element to the last in the stack
if !stack.is_empty() {
match stack.last_mut() {
Some(&mut Node::Prim(ref mut prim)) => {
prim.add_child(node);
}
// Some(&mut Node::VList(ref mut vlist)) => {
// vlist.add_child(node);
// }
_ => {
panic!("can't add child to this type of node");
}
}
} else {
// Keep the last node in the stack
stack.push(node);
}
} else {
panic!("redundant closing tag: {:?}", endtag);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::egml::{self, Shapeable, Color, ChangeView};
struct Model {
val: f32,
}
#[derive(Copy, Clone)]
enum Msg {
InnerToggle(i32),
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_props: &Self::Properties) -> Self {
Model {
val: 0.0,
}
}
fn update(&mut self, msg: Self::Message) -> ChangeView {
match msg {
Msg::InnerToggle(_) => ChangeView::None,
}
}
fn view(&self) -> Node<Self> {
egml! {
<rect />
}
}
}
struct InnerModel {
val: bool,
}
#[derive(Copy, Clone)]
enum InnerMsg {
Toggle(i32),
}
impl Component for InnerModel {
type Message = InnerMsg;
type Properties = ();
fn create(_props: &Self::Properties) -> Self {
InnerModel {
val: false,
}
}
fn update(&mut self, msg: Self::Message) -> ChangeView {
match msg {
InnerMsg::Toggle(_) => ChangeView::None,
}
}
fn view(&self) -> Node<Self> {
egml! {
<rect />
}
}
}
#[test]
fn set_attr() {
let mut state = State { stack: Vec::<Node<Model>>::new() };
let rect = egml::macros::rect::default();
let prim = egml::Prim::new("rect", rect.into());
state.stack.push(prim.into());
set_attr!(state, rect.x = 1.2.into());
match state.stack.last().unwrap() {
Node::Prim(ref prim) => {
let x = prim.rect().unwrap().x.val();
assert_eq!(1.2, x);
},
_ => (),
}
let circle = egml::macros::circle::default();
let prim = egml::Prim::new("circle", circle.into());
state.stack.push(prim.into());
set_attr!(state, circle.r = 2.5.into());
match state.stack.last().unwrap() {
Node::Prim(ref prim) => {
let r = prim.circle().unwrap().r.val();
assert_eq!(2.5, r);
},
_ => (),
}
}
#[test]
fn set_prim_modifier() {
let _node: Node<Model> = egml! {
<group translate = (50.0, 50.0), >
<rect x = 0.0, y = 0.0, width = 300.0, height = 300.0,
fill = None, stroke = (Color::Black, 2.0, 0.5), >
<circle cx = 150.0, cy = 150.0, r = 20.0,
fill = Color::Blue,
modifier = |circle, model: Model| {
circle.cy = model.val.into();
}, />
<circle modifier = for <Model> get_prim_handler(), />
<circle modifier = for <Model> prim_handler, />
</rect>
</group>
};
}
fn get_prim_handler() -> impl Fn(&mut Circle, &Model) {
|circle: &mut Circle, model: &Model| {
circle.cy = model.val.into();
}
}
fn prim_handler(circle: &mut Circle, model: &Model) {
circle.cy = model.val.into();
}
#[test]
fn set_comp_modifier() {
let _node: Node<Model> = egml! {
<group translate = (50.0, 50.0), >
<rect x = 0.0, y = 0.0, width = 300.0, height = 300.0,
fill = None, stroke = (Color::Black, 2.0, 0.5), >
<InnerModel : modifier = |this, model: Model| {
this.send_self(InnerMsg::Toggle(model.val as i32));
}, />
<InnerModel : modifier = for <Model> get_comp_handler(), />
<InnerModel : modifier = for <Model> comp_handler, />
</rect>
</group>
};
}
fn get_comp_handler() -> impl Fn(&mut Comp, &Model) {
|this: &mut Comp, model: &Model| {
this.send_self(InnerMsg::Toggle(model.val as i32));
}
}
fn comp_handler(this: &mut Comp, model: &Model) {
this.send_self(InnerMsg::Toggle(model.val as i32));
}
#[test]
fn set_pass_up() {
let _node: Node<Model> = egml! {
<group translate = (50.0, 50.0), >
<rect x = 0.0, y = 0.0, width = 300.0, height = 300.0,
fill = None, stroke = (Color::Black, 2.0, 0.5), >
<InnerModel : pass_up = |msg| {
match msg { InnerMsg::Toggle(s) => Msg::InnerToggle(s) }
}, />
</rect>
</group>
};
}
} |
pub mod boxify;
pub mod flatten_closures;
pub mod generate_bytecode;
use super::syntax::Expression;
pub trait Transformer {
fn visit(&mut self, expr: Expression) -> Visited;
}
pub enum Visited {
Transformed(Expression),
Recurse(Expression),
}
impl<T: Into<Expression>> From<T> for Visited {
fn from(x: T) -> Self {
Visited::Transformed(x.into())
}
}
|
pub mod player;
pub mod block;
pub mod stage;
pub mod object;
pub mod score; |
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// SyntheticsListTestsResponse : Object containing an array of Synthetic tests configuration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SyntheticsListTestsResponse {
/// Array of Synthetic tests configuration.
#[serde(rename = "tests", skip_serializing_if = "Option::is_none")]
pub tests: Option<Vec<crate::models::SyntheticsTestDetails>>,
}
impl SyntheticsListTestsResponse {
/// Object containing an array of Synthetic tests configuration.
pub fn new() -> SyntheticsListTestsResponse {
SyntheticsListTestsResponse {
tests: None,
}
}
}
|
use super::super::context::{Context, ParentOrRoot};
use super::super::error::*;
use super::super::traits::WorkType;
use super::super::utils::station_fn_ctx2;
use super::super::work::{WorkBox, WorkOutput};
use conveyor::{futures::prelude::*, into_box, station_fn, Result, Station, WorkStation};
use conveyor_work::package::Package;
use pathutils;
use std::fmt;
use std::sync::Arc;
use vfs::{VPath, WritePath, VFS};
use std::io::Write;
#[derive(Serialize, Deserialize, Clone)]
pub struct WriteDirectory {
pub path: String,
}
impl fmt::Debug for WriteDirectory {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "WriteDirectory")
}
}
#[typetag::serde]
impl WorkType for WriteDirectory {
fn request_station(&self, ctx: &mut Context) -> CrawlResult<WorkBox<Package>> {
let log = ctx.log().new(o!("worktype" => "write-directory"));
info!(log, "request write-directory station");
let mut path = ctx.interpolate(self.path.as_str()).unwrap();
if !pathutils::is_absolute(&path) {
path = pathutils::to_absolute(&path, ctx.root().target().path().to_str().unwrap())
.map_err(|_| CrawlError::new(CrawlErrorKind::Unknown))?;
}
info!(log, "using path"; "path" => &path);
if !std::path::Path::new(&path).exists() {
return Err(CrawlErrorKind::NotFound("path does not exits".to_string()).into());
}
let ctx = Context::new(ParentOrRoot::Parent(Box::new(ctx.clone())), None, Some(log));
Ok(into_box(WorkStation::new(
1,
|mut package: Package, ctx: &mut (vfs::physical::PhysicalFS, Context)| {
let path = ctx.0.path(package.name());
if path.exists() {
return Ok(vec![WorkOutput::Result(Ok(package))]);
}
info!(ctx.1.log(), "writing path"; "path" => format!("{:?}", path));
let buf = conveyor::futures::executor::block_on(package.read_content())?;
let mut file = path.create().unwrap();
file.write(&buf);
file.flush();
Ok(vec![WorkOutput::Result(Ok(package))])
},
move || (vfs::physical::PhysicalFS::new(&path).unwrap(), ctx.clone()),
)))
}
fn box_clone(&self) -> Box<WorkType> {
Box::new(self.clone())
}
}
|
use std::path::{Path, PathBuf};
use crate::{error::TtsError, TtsEngine};
use async_trait::async_trait;
use enum_product::enum_product;
use reqwest::Client;
use tokio::{
fs,
io::{AsyncWriteExt, BufWriter},
};
use yup_oauth2 as oauth;
#[derive(Clone, Debug)]
pub struct GcpToken(String, PathBuf);
impl GcpToken {
pub async fn issue<P: AsRef<Path>>(cert_path: P) -> Result<Self, TtsError> {
let key = oauth::read_service_account_key(cert_path.as_ref()).await?;
let authenticator = oauth::ServiceAccountAuthenticator::builder(key)
.build()
.await?;
let token = authenticator
.token(&["https://www.googleapis.com/auth/cloud-platform"])
.await?;
Ok(Self(
token.as_str().to_string(),
cert_path.as_ref().to_path_buf(),
))
}
pub fn show(&self) -> String {
self.0.clone()
}
pub async fn renew_token(&mut self) -> Result<(), TtsError> {
let key = oauth::read_service_account_key(&self.1).await?;
let authenticator = oauth::ServiceAccountAuthenticator::builder(key)
.build()
.await?;
let token = authenticator
.token(&["https://www.googleapis.com/auth/cloud-platform"])
.await?;
self.0 = token.as_str().to_string();
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct GcpTts {
pub config: GcpConfig,
}
#[async_trait]
impl TtsEngine for GcpTts {
type Config = GcpConfig;
fn from_config(config: Self::Config) -> Result<Self, crate::error::TtsError> {
Ok(Self { config })
}
async fn save(&self, text: &str) -> Result<String, crate::error::TtsError> {
let client = Client::builder().gzip(true).build()?;
let token = if self.config.access_token.trim().starts_with("Bearer ") {
self.config.access_token.replace("Bearer ", "")
} else {
self.config.access_token.clone()
};
let url = "https://texttospeech.googleapis.com/v1/text:synthesize";
let req = GcpRequest {
input: GcpInputRequest {
text: text.to_string(),
},
voice: self.config.voice.clone(),
audio_config: self.config.audio_config.clone(),
};
info!("Request: {:?}", serde_json::to_string(&req));
let buff = client
.post(url)
.bearer_auth(token)
.json(&req)
.send()
.await?
.json::<GcpResponse>()
.await?;
let buff = tokio::spawn(async move { base64::decode(buff.audio_content) }).await??;
let filename: String = uuid::Uuid::new_v4().to_string();
let output_path = format!("{}.mp3", filename);
let mut output_file = BufWriter::new(fs::File::create(&output_path).await?);
output_file.write_all(&buff).await?;
output_file.flush().await?;
Ok(output_path)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GcpResponse {
pub audio_content: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GcpRequest {
pub input: GcpInputRequest,
pub voice: GcpVoiceRequest,
pub audio_config: GcpAudioConfigRequest,
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GcpInputRequest {
pub text: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GcpVoiceRequest {
pub language_code: String,
pub name: String,
pub ssml_gender: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GcpAudioConfigRequest {
pub audio_encoding: String,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub speaking_rate: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub pitch: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub voice_gain_db: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub sample_rate_hertz: Option<u64>,
}
#[derive(Clone, Debug)]
pub struct GcpConfig {
pub access_token: String,
pub voice: GcpVoiceRequest,
pub audio_config: GcpAudioConfigRequest,
}
impl GcpConfig {
pub fn new(
token: &str,
voice: GcpVoiceRequest,
audio_config: GcpAudioConfigRequest,
) -> GcpConfig {
Self {
access_token: token.to_string(),
voice,
audio_config,
}
}
}
enum_product! {
pub enum LanguageCode {
[
"ar-XA", "bn-IN", "yue-HK", "cs-CZ", "da-DK",
"nl-NL", "en-AU", "en-IN", "en-GB", "en-US",
"fil-PH", "fi-FI", "fr-CA", "fr-FR", "de-DE",
"el-GR", "hi-IN", "hu-HU", "id-ID", "it-IT",
"ja-JP", "kn-IN", "ko-KR", "cmn-CN", "cmn-TW",
"nb-NO", "pl-PL", "pt-PT", "ru-RU", "es-ES",
"tr-TR", "vi-VN"
]
}
}
enum_product! {
pub enum VoiceCode {
[
"ar-XA", "bn-IN", "yue-HK", "cs-CZ", "da-DK",
"nl-NL", "en-AU", "en-IN", "en-GB", "en-US",
"fil-PH", "fi-FI", "fr-CA", "fr-FR", "de-DE",
"el-GR", "hi-IN", "hu-HU", "id-ID", "it-IT",
"ja-JP", "kn-IN", "ko-KR", "cmn-CN", "cmn-TW",
"nb-NO", "pl-PL", "pt-PT", "ru-RU", "es-ES",
"tr-TR", "vi-VN"
],
["-Standard-", "-Wavenet-"],
["A", "B", "C", "D", "E"]
}
}
#[derive(Clone, Debug)]
pub enum GenderCode {
Male,
Female,
}
impl std::string::ToString for GenderCode {
fn to_string(&self) -> String {
use GenderCode::*;
match self {
&Male => "MALE",
&Female => "FEMALE",
}
.to_string()
}
}
#[cfg(test)]
mod tests {
#[cfg(all(feature = "tokio_10", not(feature = "tokio_02")))]
use tokio;
#[cfg(all(feature = "tokio_02", not(feature = "tokio_10")))]
use tokio_compat as tokio;
use super::*;
use yup_oauth2 as oauth;
#[tokio::test]
async fn test_gcp() {
dotenv::dotenv().ok();
let cert_path = std::env::var("GCP_SERVICE_ACCOUNT_CREDENTIAL_FILE").unwrap();
let access_token = GcpToken::issue(cert_path).await.unwrap().show();
let voice = GcpVoiceRequest {
language_code: LanguageCode::JaJP.to_string(),
name: VoiceCode::JaJPWavenetA.to_string(),
ssml_gender: GenderCode::Female.to_string(),
};
let audio_config = GcpAudioConfigRequest {
audio_encoding: "MP3".to_string(),
..Default::default()
};
let config = GcpConfig::new(&access_token, voice, audio_config);
let engine = GcpTts::from_config(config).unwrap();
let file = engine
.save("効率的で信頼できるソフトウェアを誰もがつくれる言語")
.await
.unwrap();
println!("{:?}", file);
}
#[tokio::test]
async fn test_oauth() {
dotenv::dotenv().ok();
let cert_path = std::env::var("GCP_SERVICE_ACCOUNT_CREDENTIAL_FILE").unwrap();
let key = oauth::read_service_account_key(cert_path).await.unwrap();
let authenticator = oauth::ServiceAccountAuthenticator::builder(key)
.build()
.await
.unwrap();
let token = authenticator
.token(&["https://www.googleapis.com/auth/cloud-platform"])
.await
.unwrap();
println!("{:?}", token);
}
}
|
use crate::solver::evolution::*;
use crate::solver::hyper::HyperHeuristic;
use crate::solver::{RefinementContext, Telemetry};
use crate::utils::Timer;
/// A simple evolution algorithm which maintains single population.
pub struct RunSimple {}
impl Default for RunSimple {
fn default() -> Self {
Self {}
}
}
impl EvolutionStrategy for RunSimple {
fn run(
&self,
refinement_ctx: RefinementContext,
hyper: Box<dyn HyperHeuristic + Send + Sync>,
termination: &(dyn Termination + Send + Sync),
telemetry: Telemetry,
) -> EvolutionResult {
let mut refinement_ctx = refinement_ctx;
let mut hyper = hyper;
let mut telemetry = telemetry;
while !should_stop(&mut refinement_ctx, termination) {
let generation_time = Timer::start();
let parents = refinement_ctx.population.select().collect();
let offspring = hyper.search(&refinement_ctx, parents);
let is_improved =
if should_add_solution(&refinement_ctx) { refinement_ctx.population.add_all(offspring) } else { false };
on_generation(&mut refinement_ctx, &mut telemetry, termination, generation_time, is_improved);
}
telemetry.on_result(&refinement_ctx);
Ok((refinement_ctx.population, telemetry.get_metrics()))
}
}
|
extern crate minictrl;
use std::env;
use sqlx::postgres::PgPoolOptions;
use minictrl::database::run_migrations;
use minictrl::web::webserver_start;
#[async_std::main]
async fn main() -> anyhow::Result<()> {
// Setup logging
tracing_subscriber::fmt()
// Configure formatting settings.
.with_target(false)
.with_timer(tracing_subscriber::fmt::time::time())
.with_level(true)
// Set the collector as the default.
.init();
// Establish database connection pool
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(env::var("DATABASE_URL")?.as_str())
.await?;
run_migrations(&pool).await?;
webserver_start(pool).await
}
|
use crate::common::did::DidValue;
use crate::ledger::constants;
use crate::ledger::requests::nym::role_to_code;
use crate::tests::utils::crypto::Identity;
use crate::tests::utils::helpers;
use crate::tests::utils::pool::*;
const ALIAS: &str = "alias";
const ROLE: &str = "TRUSTEE";
#[cfg(test)]
mod builder {
use super::*;
use crate::tests::utils::constants::{
MY1_DID, MY1_DID_FQ, MY1_VERKEY, TRUSTEE_DID, TRUSTEE_DID_FQ,
};
mod nym {
use super::*;
#[test]
fn test_pool_build_nym_request() {
let pool = TestPool::new();
let nym_request = pool
.request_builder()
.build_nym_request(
&DidValue(String::from(TRUSTEE_DID)),
&DidValue(String::from(MY1_DID)),
None,
None,
None,
)
.unwrap();
let expected_result = json!({
"type": constants::NYM,
"dest": MY1_DID,
});
helpers::check_request_operation(&nym_request, expected_result);
}
#[test]
fn test_pool_build_nym_request_for_optional_fields() {
let pool = TestPool::new();
let nym_request = pool
.request_builder()
.build_nym_request(
&DidValue(String::from(TRUSTEE_DID)),
&DidValue(String::from(MY1_DID)),
Some(MY1_VERKEY.to_string()),
Some(ALIAS.to_string()),
Some(ROLE.to_string()),
)
.unwrap();
let expected_result = json!({
"type": constants::NYM,
"dest": MY1_DID,
"verkey": MY1_VERKEY,
"alias": ALIAS,
"role": role_to_code(Some(String::from(ROLE))).unwrap(),
});
helpers::check_request_operation(&nym_request, expected_result);
}
#[test]
fn test_pool_build_nym_request_for_empty_role() {
let pool = TestPool::new();
let nym_request = pool
.request_builder()
.build_nym_request(
&DidValue(String::from(TRUSTEE_DID)),
&DidValue(String::from(MY1_DID)),
None,
None,
Some(String::from("")),
)
.unwrap();
let expected_result = json!({
"type": constants::NYM,
"dest": MY1_DID,
"role": serde_json::Value::Null,
});
helpers::check_request_operation(&nym_request, expected_result);
}
#[test]
fn test_pool_build_nym_request_for_fully_qualified_dids() {
let pool = TestPool::new();
let nym_request = pool
.request_builder()
.build_nym_request(
&DidValue(String::from(TRUSTEE_DID_FQ)),
&DidValue(String::from(MY1_DID_FQ)),
None,
None,
None,
)
.unwrap();
let expected_result = json!({
"type": constants::NYM,
"dest": MY1_DID,
});
helpers::check_request_operation(&nym_request, expected_result);
}
#[test]
fn test_build_nym_request_works_for_invalid_role() {
let pool = TestPool::new();
let trustee = Identity::trustee();
let new_identity = Identity::new(None);
let role = "INALID_ROLE_ALIAS";
let _err = pool
.request_builder()
.build_nym_request(
&trustee.did,
&new_identity.did,
Some(new_identity.verkey.to_string()),
None,
Some(role.to_string()),
)
.unwrap_err();
}
}
mod get_nym {
use super::*;
#[test]
fn test_pool_build_get_nym_request() {
let pool = TestPool::new();
let nym_request = pool
.request_builder()
.build_get_nym_request(
Some(&DidValue(String::from(TRUSTEE_DID))),
&DidValue(String::from(MY1_DID)),
)
.unwrap();
let expected_result = json!({
"type": constants::GET_NYM,
"dest": MY1_DID,
});
helpers::check_request_operation(&nym_request, expected_result);
}
#[test]
fn test_pool_build_get_nym_request_for_qualified_dids() {
let pool = TestPool::new();
let nym_request = pool
.request_builder()
.build_get_nym_request(
Some(&DidValue(String::from(TRUSTEE_DID_FQ))),
&DidValue(String::from(MY1_DID_FQ)),
)
.unwrap();
let expected_result = json!({
"type": constants::GET_NYM,
"dest": MY1_DID,
});
helpers::check_request_operation(&nym_request, expected_result);
}
}
}
#[cfg(test)]
mod send_nym {
use super::*;
use crate::ledger::constants::ROLE_REMOVE;
#[test]
fn test_pool_send_nym_request() {
let pool = TestPool::new();
let trustee = Identity::trustee();
let new_identity = Identity::new(None);
// Send NYM
let mut nym_request = pool
.request_builder()
.build_nym_request(
&trustee.did,
&new_identity.did,
Some(new_identity.verkey.to_string()),
None,
None,
)
.unwrap();
trustee.sign_request(&mut nym_request);
let nym_response = pool.send_request(&nym_request).unwrap();
// Get NYM
let get_nym_request = pool
.request_builder()
.build_get_nym_request(None, &new_identity.did)
.unwrap();
let response = pool
.send_request_with_retries(&get_nym_request, &nym_response)
.unwrap();
let expected_data = json!({
"dest": &new_identity.did,
"verkey": &new_identity.verkey,
"role": serde_json::Value::Null
});
assert_eq!(expected_data, parse_get_nym_response(&response));
}
#[test]
fn test_pool_send_nym_request_for_optional_fields() {
let pool = TestPool::new();
let trustee = Identity::trustee();
let new_identity = Identity::new(None);
// Send NYM
let mut nym_request = pool
.request_builder()
.build_nym_request(
&trustee.did,
&new_identity.did,
Some(new_identity.verkey.to_string()),
Some(ALIAS.to_string()),
Some(ROLE.to_string()),
)
.unwrap();
trustee.sign_request(&mut nym_request);
let nym_response = pool.send_request(&nym_request).unwrap();
// Get NYM
let get_nym_request = pool
.request_builder()
.build_get_nym_request(None, &new_identity.did)
.unwrap();
let response = pool
.send_request_with_retries(&get_nym_request, &nym_response)
.unwrap();
let expected_data = json!({
"dest": &new_identity.did,
"verkey": &new_identity.verkey,
"role": role_to_code(Some(String::from(ROLE))).unwrap(),
});
assert_eq!(expected_data, parse_get_nym_response(&response));
}
#[test]
fn test_pool_send_nym_request_for_different_roles() {
let pool = TestPool::new();
let trustee = Identity::trustee();
for role in [
"STEWARD",
"TRUSTEE",
"TRUST_ANCHOR",
"ENDORSER",
"NETWORK_MONITOR",
]
.iter()
{
let new_identity = Identity::new(None);
// Send NYM
let mut nym_request = pool
.request_builder()
.build_nym_request(
&trustee.did,
&new_identity.did,
Some(new_identity.verkey.to_string()),
None,
Some(role.to_string()),
)
.unwrap();
trustee.sign_request(&mut nym_request);
let nym_response = pool.send_request(&nym_request).unwrap();
// Get NYM
let get_nym_request = pool
.request_builder()
.build_get_nym_request(None, &new_identity.did)
.unwrap();
let response = pool
.send_request_with_retries(&get_nym_request, &nym_response)
.unwrap();
let expected_data = json!({
"dest": &new_identity.did,
"verkey": &new_identity.verkey,
"role": role_to_code(Some(role.to_string())).unwrap(),
});
assert_eq!(expected_data, parse_get_nym_response(&response));
}
}
#[test]
fn test_pool_send_nym_request_for_resetting_role() {
let pool = TestPool::new();
let trustee = Identity::trustee();
let new_identity = Identity::new(None);
// Send NYM with TRUSTEE role
let mut nym_request = pool
.request_builder()
.build_nym_request(
&trustee.did,
&new_identity.did,
Some(new_identity.verkey.to_string()),
None,
Some(ROLE.to_string()),
)
.unwrap();
trustee.sign_request(&mut nym_request);
let nym_response = pool.send_request(&nym_request).unwrap();
// Get NYM to ensure role is TRUSTEE
let get_nym_request = pool
.request_builder()
.build_get_nym_request(None, &new_identity.did)
.unwrap();
let response = pool
.send_request_with_retries(&get_nym_request, &nym_response)
.unwrap();
let expected_data = json!({
"dest": &new_identity.did,
"verkey": &new_identity.verkey,
"role": role_to_code(Some(String::from(ROLE))).unwrap(),
});
assert_eq!(expected_data, parse_get_nym_response(&response));
// Send NYM with empty role to reset current
let mut nym_request = pool
.request_builder()
.build_nym_request(
&trustee.did,
&new_identity.did,
None,
None,
Some(ROLE_REMOVE.to_string()),
)
.unwrap();
trustee.sign_request(&mut nym_request);
let nym_response = pool.send_request(&nym_request).unwrap();
// Get NYM to ensure role was reset
let get_nym_request = pool
.request_builder()
.build_get_nym_request(None, &new_identity.did)
.unwrap();
let response = pool
.send_request_with_retries(&get_nym_request, &nym_response)
.unwrap();
let expected_data = json!({
"dest": &new_identity.did,
"verkey": &new_identity.verkey,
"role": serde_json::Value::Null,
});
assert_eq!(expected_data, parse_get_nym_response(&response));
}
#[test]
fn test_pool_send_nym_request_without_signature() {
let pool = TestPool::new();
let trustee = Identity::trustee();
let new_identity = Identity::new(None);
// Send NYM
let nym_request = pool
.request_builder()
.build_nym_request(
&trustee.did,
&new_identity.did,
Some(new_identity.verkey.to_string()),
None,
None,
)
.unwrap();
let err = pool.send_request(&nym_request).unwrap_err();
helpers::check_response_type(&err, "REQNACK");
}
#[test]
fn test_pool_send_nym_request_for_unknown_signer() {
let pool = TestPool::new();
let new_identity = Identity::new(None);
// Send NYM
let mut nym_request = pool
.request_builder()
.build_nym_request(&new_identity.did, &new_identity.did, None, None, None)
.unwrap();
new_identity.sign_request(&mut nym_request);
let err = pool.send_request(&nym_request).unwrap_err();
helpers::check_response_type(&err, "REQNACK");
}
#[test]
fn test_pool_send_get_nym_request_for_unknown_target() {
let pool = TestPool::new();
let new_identity = Identity::new(None);
// Get NYM
let get_nym_request = pool
.request_builder()
.build_get_nym_request(None, &new_identity.did)
.unwrap();
let response = pool.send_request(&get_nym_request).unwrap();
helpers::get_response_data(&response).unwrap_err();
}
fn parse_get_nym_response(response: &str) -> serde_json::Value {
let data = helpers::get_response_data(response).unwrap();
let data: serde_json::Value = serde_json::from_str(&data.as_str().unwrap()).unwrap();
json!({
"dest": data["dest"],
"verkey": data["verkey"],
"role": data["role"],
})
}
}
|
use regex::Regex;
use std::result::Result;
pub enum LineType {
NewGuard,
FallAsleep,
WakeUp,
}
pub fn get_line_data(line: &str) -> Result<(usize, LineType), String> {
if let Some(id) = get_guard_id(line) {
return Ok((id, LineType::NewGuard));
}
if let Some(min) = get_fall_asleep_minute(line) {
return Ok((min, LineType::FallAsleep));
}
if let Some(min) = get_wake_up_minute(line) {
return Ok((min, LineType::WakeUp));
}
Err("Unable to parse line".to_owned())
}
const DATE_SECTION: &'static str =
r"^\[(?P<date>\d{4}-\d{2}-\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2})\]";
fn get_guard_id(line: &str) -> Option<usize> {
lazy_static! {
static ref PARSE_EXPR: Regex =
Regex::new(&(DATE_SECTION.clone().to_owned() + r" Guard #(?P<id>\d+) begins shift$"))
.unwrap();
}
PARSE_EXPR.captures(line).map(|caps| caps["id"].parse::<usize>().unwrap())
}
fn get_fall_asleep_minute(line: &str) -> Option<usize> {
lazy_static! {
static ref PARSE_EXPR: Regex =
Regex::new(&(DATE_SECTION.clone().to_owned() + r" falls asleep$")).unwrap();
}
PARSE_EXPR.captures(line).map(|caps| caps["minute"].parse::<usize>().unwrap())
}
fn get_wake_up_minute(line: &str) -> Option<usize> {
lazy_static! {
static ref PARSE_EXPR: Regex =
Regex::new(&(DATE_SECTION.clone().to_owned() + r" wakes up$")).unwrap();
}
PARSE_EXPR.captures(line).map(|caps| caps["minute"].parse::<usize>().unwrap())
}
#[cfg(test)]
mod get_guard_id_tests {
use super::get_guard_id;
#[test]
fn has_guard_id() {
assert_eq!(
get_guard_id("[1518-11-01 00:00] Guard #10 begins shift"),
Some(10)
);
}
#[test]
fn no_guard_id() {
assert_eq!(get_guard_id("[1518-11-01 00:05] falls asleep"), None);
assert_eq!(get_guard_id("[1518-11-01 00:25] wakes up"), None);
}
}
#[cfg(test)]
mod get_fall_asleep_minute_tests {
use super::get_fall_asleep_minute;
#[test]
fn has_fall_asleep_minute() {
assert_eq!(
get_fall_asleep_minute("[1518-11-01 00:05] falls asleep"),
Some(5)
);
}
#[test]
fn no_fall_asleep_minute() {
assert_eq!(
get_fall_asleep_minute("[1518-11-01 00:00] Guard #10 begins shift"),
None
);
assert_eq!(get_fall_asleep_minute("[1518-11-01 00:25] wakes up"), None);
}
}
#[cfg(test)]
mod get_wake_up_minute_tests {
use super::get_wake_up_minute;
#[test]
fn has_fall_asleep_minute() {
assert_eq!(get_wake_up_minute("[1518-11-01 00:25] wakes up"), Some(25));
}
#[test]
fn no_fall_asleep_minute() {
assert_eq!(
get_wake_up_minute("[1518-11-01 00:00] Guard #10 begins shift"),
None
);
assert_eq!(get_wake_up_minute("[1518-11-01 00:05] falls asleep"), None);
}
} |
pub mod open_dialog;
pub mod save_dialog;
pub use self::open_dialog::OpenDialog;
pub use self::save_dialog::SaveDialog; |
use rustlearn::base_language_demo::{function, tuple_array};
#[macro_use]
extern crate rustlearn;
fn main() {
let value = fmt!(100);
println!("{}", value);
tuple_array::tuple();
tuple_array::array();
let func_result = function::func_mult_return(100, 200);
println!("func result value 1: {}", func_result.0);
println!("func result value 2: {}", func_result.1);
function::for_func();
}
|
pub fn parse(tokens: Scanner) {
for token in &tokens {
println!("Got token {:?}.", token);
}
}
|
pub fn firstn(s: &str, n: usize) -> &str {
let idx = s
.char_indices()
.nth(n)
.map(|(i, _)| i)
.unwrap_or(s.len());
return &s[..idx];
}
pub fn lastn(s: &str, n: usize) -> &str {
let mut new_n = 0;
let mut d = 0; // default
// hacky?
if n == 0 {
return "";
}
if n > s.len() {
return s;
}
//
if n > 0 {
new_n = n - 1;
}
if s.len() > 0 {
d = s.len() - 1;
}
let idx = s
.char_indices()
.rev()
.nth(new_n)
.map(|(i, _)| i)
.unwrap_or(d);
return &s[idx..];
}
pub fn slice(s: &str, start: usize, end: usize) -> &str {
let mut start_byte = s.len();
let mut end_byte = s.len();
if end < start {
return "";
}
for (i, (byte_idx, _)) in s.char_indices().enumerate() {
if i == start {
start_byte = byte_idx;
}
if i == end {
end_byte = byte_idx;
break;
}
}
return unsafe { s.get_unchecked(start_byte..end_byte) };
}
#[cfg(test)]
mod tests {
use crate::{firstn, lastn, slice};
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
fn test_nth() {
assert_eq!("", firstn("test", 0));
assert_eq!("t", firstn("test", 1));
assert_eq!("te", firstn("test", 2));
assert_eq!("tes", firstn("test", 3));
assert_eq!("test", firstn("test", 4));
assert_eq!("test", firstn("test", 10));
assert_eq!("Hello", firstn("Hello, World!", 5));
assert_eq!("", firstn("", 0));
assert_eq!("", firstn("", 1));
assert_eq!("", firstn("", 5));
}
#[test]
fn test_last() {
assert_eq!("", lastn("test", 0));
assert_eq!("t", lastn("test", 1));
assert_eq!("st", lastn("test", 2));
assert_eq!("est", lastn("test", 3));
assert_eq!("test", lastn("test", 4));
assert_eq!("test", lastn("test", 10));
assert_eq!("World!", lastn("Hello, World!", 6));
assert_eq!("", lastn("", 0));
assert_eq!("", lastn("", 1));
assert_eq!("", lastn("", 11));
}
#[test]
fn test_slice() {
assert_eq!("", slice("test", 0, 0));
assert_eq!("", slice("test", 3, 3));
assert_eq!("t", slice("test", 0, 1));
assert_eq!("es", slice("test", 1, 3));
assert_eq!("st", slice("test", 2, 10));
assert_eq!("", slice("test", 10, 15));
assert_eq!("", slice("", 0, 5));
assert_eq!("", slice("test", 3, 1));
}
}
|
use std::io::{Read, Write, Error, ErrorKind};
pub fn read_varint_u64<T: Read>(r: &mut T) -> Result<u64, Error> {
let mut buf = [0u8; 1];
let mut value = 0;
for i in 0..10 {
try!(r.read_exact(&mut buf[..]));
value |= ((buf[0] & 0b01111111) as u64) << (i * 7);
if buf[0] & 0b10000000 == 0 {
break;
} else if i == 9 {
return Err(Error::new(ErrorKind::InvalidData, "varint overflow"));
}
}
Ok(value)
}
pub fn write_varint_u64<T: Write>(w: &mut T, value: u64) -> Result<(), Error> {
let mut value = value;
let mut buf = [0; 1];
while value >= 0b10000000 {
buf[0] = (value | 0b10000000) as u8;
try!(w.write_all(&buf[..]));
value = value >> 7;
}
buf[0] = (value & 0b01111111) as u8;
try!(w.write_all(&buf[..]));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
use std::{u8, u32, u64};
#[test]
fn test_write_read_varint_u64() {
let mut buf = Cursor::new(Vec::new());
assert!(write_varint_u64(&mut buf, 0).is_ok());
assert!(write_varint_u64(&mut buf, 1).is_ok());
assert!(write_varint_u64(&mut buf, 17).is_ok());
assert!(write_varint_u64(&mut buf, 126).is_ok());
assert!(write_varint_u64(&mut buf, 127).is_ok());
assert!(write_varint_u64(&mut buf, u8::MAX as u64).is_ok());
assert!(write_varint_u64(&mut buf, (u8::MAX as u64) + 1).is_ok());
assert!(write_varint_u64(&mut buf, 1024).is_ok());
assert!(write_varint_u64(&mut buf, u32::MAX as u64).is_ok());
assert!(write_varint_u64(&mut buf, (u32::MAX as u64) + 1).is_ok());
assert!(write_varint_u64(&mut buf, u64::MAX).is_ok());
assert!(write_varint_u64(&mut buf, 0).is_ok());
buf.set_position(0);
assert_eq!(read_varint_u64(&mut buf).unwrap(), 0);
assert_eq!(read_varint_u64(&mut buf).unwrap(), 1);
assert_eq!(read_varint_u64(&mut buf).unwrap(), 17);
assert_eq!(read_varint_u64(&mut buf).unwrap(), 126);
assert_eq!(read_varint_u64(&mut buf).unwrap(), 127);
assert_eq!(read_varint_u64(&mut buf).unwrap(), u8::MAX as u64);
assert_eq!(read_varint_u64(&mut buf).unwrap(), (u8::MAX as u64) + 1);
assert_eq!(read_varint_u64(&mut buf).unwrap(), 1024);
assert_eq!(read_varint_u64(&mut buf).unwrap(), u32::MAX as u64);
assert_eq!(read_varint_u64(&mut buf).unwrap(), (u32::MAX as u64) + 1);
assert_eq!(read_varint_u64(&mut buf).unwrap(), u64::MAX);
assert_eq!(read_varint_u64(&mut buf).unwrap(), 0);
}
#[test]
fn test_detects_overflow() {
let mut buf = Cursor::new(vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF]);
assert!(read_varint_u64(&mut buf).is_err());
}
}
|
fn check_question(message: &str) -> bool {
message.trim().ends_with("?")
}
fn check_silence(message: &str) -> bool {
message.trim().is_empty()
}
fn check_yell(message: &str) -> bool {
message.chars().any(char::is_alphabetic) && !message.chars().any(char::is_lowercase)
}
pub fn reply(message: &str) -> &str {
match (
check_question(message),
check_yell(message),
check_silence(message),
) {
(_, _, true) => return "Fine. Be that way!",
(true, true, _) => return "Calm down, I know what I'm doing!",
(true, false, _) => return "Sure.",
(false, true, _) => return "Whoa, chill out!",
(_, _, _) => return "Whatever.",
}
}
|
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn bubble_sort(data: Vec<i32>)-> Vec <i32> {
let mut copy = data.to_vec();
let mut temp: i32;
for i in 0.. copy.len() {
for j in 0.. copy.len(){
if copy[j] > copy[i] {
temp = copy[j];
copy[j] = copy[i];
copy[i] = temp;
}
}
}
return copy;
}
#[wasm_bindgen]
pub fn bubble_sort_no_ret(data: Vec<i32>){
let mut copy = data.to_vec();
let mut temp: i32;
for i in 0.. copy.len() {
for j in 0.. copy.len(){
if copy[j] > copy[i] {
temp = copy[j];
copy[j] = copy[i];
copy[i] = temp;
}
}
}
}
|
#[doc = "Register `RCC_MP_APB2LPENCLRR` reader"]
pub type R = crate::R<RCC_MP_APB2LPENCLRR_SPEC>;
#[doc = "Register `RCC_MP_APB2LPENCLRR` writer"]
pub type W = crate::W<RCC_MP_APB2LPENCLRR_SPEC>;
#[doc = "Field `TIM1LPEN` reader - TIM1LPEN"]
pub type TIM1LPEN_R = crate::BitReader;
#[doc = "Field `TIM1LPEN` writer - TIM1LPEN"]
pub type TIM1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM8LPEN` reader - TIM8LPEN"]
pub type TIM8LPEN_R = crate::BitReader;
#[doc = "Field `TIM8LPEN` writer - TIM8LPEN"]
pub type TIM8LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM15LPEN` reader - TIM15LPEN"]
pub type TIM15LPEN_R = crate::BitReader;
#[doc = "Field `TIM15LPEN` writer - TIM15LPEN"]
pub type TIM15LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM16LPEN` reader - TIM16LPEN"]
pub type TIM16LPEN_R = crate::BitReader;
#[doc = "Field `TIM16LPEN` writer - TIM16LPEN"]
pub type TIM16LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `TIM17LPEN` reader - TIM17LPEN"]
pub type TIM17LPEN_R = crate::BitReader;
#[doc = "Field `TIM17LPEN` writer - TIM17LPEN"]
pub type TIM17LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI1LPEN` reader - SPI1LPEN"]
pub type SPI1LPEN_R = crate::BitReader;
#[doc = "Field `SPI1LPEN` writer - SPI1LPEN"]
pub type SPI1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI4LPEN` reader - SPI4LPEN"]
pub type SPI4LPEN_R = crate::BitReader;
#[doc = "Field `SPI4LPEN` writer - SPI4LPEN"]
pub type SPI4LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SPI5LPEN` reader - SPI5LPEN"]
pub type SPI5LPEN_R = crate::BitReader;
#[doc = "Field `SPI5LPEN` writer - SPI5LPEN"]
pub type SPI5LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `USART6LPEN` reader - USART6LPEN"]
pub type USART6LPEN_R = crate::BitReader;
#[doc = "Field `USART6LPEN` writer - USART6LPEN"]
pub type USART6LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SAI1LPEN` reader - SAI1LPEN"]
pub type SAI1LPEN_R = crate::BitReader;
#[doc = "Field `SAI1LPEN` writer - SAI1LPEN"]
pub type SAI1LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SAI2LPEN` reader - SAI2LPEN"]
pub type SAI2LPEN_R = crate::BitReader;
#[doc = "Field `SAI2LPEN` writer - SAI2LPEN"]
pub type SAI2LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SAI3LPEN` reader - SAI3LPEN"]
pub type SAI3LPEN_R = crate::BitReader;
#[doc = "Field `SAI3LPEN` writer - SAI3LPEN"]
pub type SAI3LPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `DFSDMLPEN` reader - DFSDMLPEN"]
pub type DFSDMLPEN_R = crate::BitReader;
#[doc = "Field `DFSDMLPEN` writer - DFSDMLPEN"]
pub type DFSDMLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `ADFSDMLPEN` reader - ADFSDMLPEN"]
pub type ADFSDMLPEN_R = crate::BitReader;
#[doc = "Field `ADFSDMLPEN` writer - ADFSDMLPEN"]
pub type ADFSDMLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `FDCANLPEN` reader - FDCANLPEN"]
pub type FDCANLPEN_R = crate::BitReader;
#[doc = "Field `FDCANLPEN` writer - FDCANLPEN"]
pub type FDCANLPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - TIM1LPEN"]
#[inline(always)]
pub fn tim1lpen(&self) -> TIM1LPEN_R {
TIM1LPEN_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - TIM8LPEN"]
#[inline(always)]
pub fn tim8lpen(&self) -> TIM8LPEN_R {
TIM8LPEN_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - TIM15LPEN"]
#[inline(always)]
pub fn tim15lpen(&self) -> TIM15LPEN_R {
TIM15LPEN_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - TIM16LPEN"]
#[inline(always)]
pub fn tim16lpen(&self) -> TIM16LPEN_R {
TIM16LPEN_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - TIM17LPEN"]
#[inline(always)]
pub fn tim17lpen(&self) -> TIM17LPEN_R {
TIM17LPEN_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 8 - SPI1LPEN"]
#[inline(always)]
pub fn spi1lpen(&self) -> SPI1LPEN_R {
SPI1LPEN_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - SPI4LPEN"]
#[inline(always)]
pub fn spi4lpen(&self) -> SPI4LPEN_R {
SPI4LPEN_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - SPI5LPEN"]
#[inline(always)]
pub fn spi5lpen(&self) -> SPI5LPEN_R {
SPI5LPEN_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 13 - USART6LPEN"]
#[inline(always)]
pub fn usart6lpen(&self) -> USART6LPEN_R {
USART6LPEN_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 16 - SAI1LPEN"]
#[inline(always)]
pub fn sai1lpen(&self) -> SAI1LPEN_R {
SAI1LPEN_R::new(((self.bits >> 16) & 1) != 0)
}
#[doc = "Bit 17 - SAI2LPEN"]
#[inline(always)]
pub fn sai2lpen(&self) -> SAI2LPEN_R {
SAI2LPEN_R::new(((self.bits >> 17) & 1) != 0)
}
#[doc = "Bit 18 - SAI3LPEN"]
#[inline(always)]
pub fn sai3lpen(&self) -> SAI3LPEN_R {
SAI3LPEN_R::new(((self.bits >> 18) & 1) != 0)
}
#[doc = "Bit 20 - DFSDMLPEN"]
#[inline(always)]
pub fn dfsdmlpen(&self) -> DFSDMLPEN_R {
DFSDMLPEN_R::new(((self.bits >> 20) & 1) != 0)
}
#[doc = "Bit 21 - ADFSDMLPEN"]
#[inline(always)]
pub fn adfsdmlpen(&self) -> ADFSDMLPEN_R {
ADFSDMLPEN_R::new(((self.bits >> 21) & 1) != 0)
}
#[doc = "Bit 24 - FDCANLPEN"]
#[inline(always)]
pub fn fdcanlpen(&self) -> FDCANLPEN_R {
FDCANLPEN_R::new(((self.bits >> 24) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM1LPEN"]
#[inline(always)]
#[must_use]
pub fn tim1lpen(&mut self) -> TIM1LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 0> {
TIM1LPEN_W::new(self)
}
#[doc = "Bit 1 - TIM8LPEN"]
#[inline(always)]
#[must_use]
pub fn tim8lpen(&mut self) -> TIM8LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 1> {
TIM8LPEN_W::new(self)
}
#[doc = "Bit 2 - TIM15LPEN"]
#[inline(always)]
#[must_use]
pub fn tim15lpen(&mut self) -> TIM15LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 2> {
TIM15LPEN_W::new(self)
}
#[doc = "Bit 3 - TIM16LPEN"]
#[inline(always)]
#[must_use]
pub fn tim16lpen(&mut self) -> TIM16LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 3> {
TIM16LPEN_W::new(self)
}
#[doc = "Bit 4 - TIM17LPEN"]
#[inline(always)]
#[must_use]
pub fn tim17lpen(&mut self) -> TIM17LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 4> {
TIM17LPEN_W::new(self)
}
#[doc = "Bit 8 - SPI1LPEN"]
#[inline(always)]
#[must_use]
pub fn spi1lpen(&mut self) -> SPI1LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 8> {
SPI1LPEN_W::new(self)
}
#[doc = "Bit 9 - SPI4LPEN"]
#[inline(always)]
#[must_use]
pub fn spi4lpen(&mut self) -> SPI4LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 9> {
SPI4LPEN_W::new(self)
}
#[doc = "Bit 10 - SPI5LPEN"]
#[inline(always)]
#[must_use]
pub fn spi5lpen(&mut self) -> SPI5LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 10> {
SPI5LPEN_W::new(self)
}
#[doc = "Bit 13 - USART6LPEN"]
#[inline(always)]
#[must_use]
pub fn usart6lpen(&mut self) -> USART6LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 13> {
USART6LPEN_W::new(self)
}
#[doc = "Bit 16 - SAI1LPEN"]
#[inline(always)]
#[must_use]
pub fn sai1lpen(&mut self) -> SAI1LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 16> {
SAI1LPEN_W::new(self)
}
#[doc = "Bit 17 - SAI2LPEN"]
#[inline(always)]
#[must_use]
pub fn sai2lpen(&mut self) -> SAI2LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 17> {
SAI2LPEN_W::new(self)
}
#[doc = "Bit 18 - SAI3LPEN"]
#[inline(always)]
#[must_use]
pub fn sai3lpen(&mut self) -> SAI3LPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 18> {
SAI3LPEN_W::new(self)
}
#[doc = "Bit 20 - DFSDMLPEN"]
#[inline(always)]
#[must_use]
pub fn dfsdmlpen(&mut self) -> DFSDMLPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 20> {
DFSDMLPEN_W::new(self)
}
#[doc = "Bit 21 - ADFSDMLPEN"]
#[inline(always)]
#[must_use]
pub fn adfsdmlpen(&mut self) -> ADFSDMLPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 21> {
ADFSDMLPEN_W::new(self)
}
#[doc = "Bit 24 - FDCANLPEN"]
#[inline(always)]
#[must_use]
pub fn fdcanlpen(&mut self) -> FDCANLPEN_W<RCC_MP_APB2LPENCLRR_SPEC, 24> {
FDCANLPEN_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "This register is used by the MCU in order to clear the PERxLPEN bits\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcc_mp_apb2lpenclrr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcc_mp_apb2lpenclrr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct RCC_MP_APB2LPENCLRR_SPEC;
impl crate::RegisterSpec for RCC_MP_APB2LPENCLRR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`rcc_mp_apb2lpenclrr::R`](R) reader structure"]
impl crate::Readable for RCC_MP_APB2LPENCLRR_SPEC {}
#[doc = "`write(|w| ..)` method takes [`rcc_mp_apb2lpenclrr::W`](W) writer structure"]
impl crate::Writable for RCC_MP_APB2LPENCLRR_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets RCC_MP_APB2LPENCLRR to value 0x0137_271f"]
impl crate::Resettable for RCC_MP_APB2LPENCLRR_SPEC {
const RESET_VALUE: Self::Ux = 0x0137_271f;
}
|
// Copyright 2019, 2020 Wingchain
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::errors::ErrorKind;
use crate::protocol::{
ConsensusMessage, MessageType, Node, Proposal, RequestId, RequestProposalReq,
RequestProposalRes, QC,
};
use crate::stream::{get_address, sign, verify, verify_qc, HotStuffStream, InternalMessage};
use futures::prelude::*;
use log::{trace, warn};
use node_consensus_base::scheduler::{ScheduleInfo, Scheduler};
use node_consensus_base::support::ConsensusSupport;
use node_consensus_base::PeerId;
use node_executor::module::hotstuff::Authorities;
use primitives::errors::CommonResult;
use primitives::{codec, BuildBlockParams, FullTransaction, Transaction};
use primitives::{Address, Hash};
use rand::{thread_rng, Rng};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::time::sleep_until;
#[derive(PartialEq, Debug)]
pub enum State {
Leader,
Replica,
Observer,
}
pub struct LeaderState<'a, S>
where
S: ConsensusSupport,
{
stream: &'a mut HotStuffStream<S>,
new_view_collector: ConsensusMessageCollector,
prepare_collector: ConsensusMessageCollector,
pre_commit_collector: ConsensusMessageCollector,
commit_collector: ConsensusMessageCollector,
work_schedule_signal: Option<ScheduleInfo>,
work_new_view_signal: Option<QC>,
pending_remote_proposal: Option<Hash>,
prepare_message: Option<ConsensusMessage>,
pre_commit_message: Option<ConsensusMessage>,
commit_message: Option<ConsensusMessage>,
decide_message: Option<ConsensusMessage>,
}
impl<'a, S> LeaderState<'a, S>
where
S: ConsensusSupport,
{
pub fn new(stream: &'a mut HotStuffStream<S>) -> Self {
Self {
stream,
new_view_collector: ConsensusMessageCollector::new(),
prepare_collector: ConsensusMessageCollector::new(),
pre_commit_collector: ConsensusMessageCollector::new(),
commit_collector: ConsensusMessageCollector::new(),
work_schedule_signal: None,
work_new_view_signal: None,
pending_remote_proposal: None,
prepare_message: None,
pre_commit_message: None,
commit_message: None,
decide_message: None,
}
}
pub async fn start(mut self) -> CommonResult<()> {
let current_view = self.stream.storage.get_view();
self.process_pending_new_view()?;
self.send_new_view_to_self()?;
let mut scheduler = Scheduler::new(self.stream.hotstuff_meta.block_interval);
loop {
if self.stream.shutdown {
return Ok(());
}
if self.stream.storage.get_view() != current_view {
return Ok(());
}
let next_timeout = sleep_until(self.stream.next_timeout_instant());
tokio::select! {
_ = next_timeout => {
self.stream.on_timeout()?;
},
Some(schedule_info) = scheduler.next() => {
self.try_work(Some(schedule_info), None)
.unwrap_or_else(|e| warn!("HotStuff stream handle work error: {}", e));
}
Some(internal_message) = self.stream.internal_rx.next() => {
match internal_message {
InternalMessage::ValidatorRegistered { address, peer_id } => {
self.on_validator_registered(address, peer_id)
.unwrap_or_else(|e| warn!("HotStuff stream handle validator registered message error: {}", e));
},
InternalMessage::Proposal { address, proposal } => {
self.on_remote_proposal(address, proposal)
.unwrap_or_else(|e| warn!("HotStuff stream handle proposal message error: {}", e));
},
InternalMessage::ConsensusMessage {message, peer_id } => {
self.on_consensus_message(message, peer_id)
.unwrap_or_else(|e| warn!("HotStuff stream handle consensus message error: {}", e));
}
}
},
in_message = self.stream.in_rx.next() => {
match in_message {
Some(in_message) => {
self.stream.on_in_message(in_message)
.unwrap_or_else(|e| warn!("HotStuff stream handle in message error: {}", e));
},
// in tx has been dropped
None => {
self.stream.shutdown = true;
},
}
},
}
}
}
fn try_work(
&mut self,
work_schedule_signal: Option<ScheduleInfo>,
work_new_view_signal: Option<QC>,
) -> CommonResult<()> {
if let Some(work_schedule_signal) = work_schedule_signal {
self.work_schedule_signal = Some(work_schedule_signal);
}
if let Some(work_new_view_signal) = work_new_view_signal {
self.work_new_view_signal = Some(work_new_view_signal);
}
if self.work_new_view_signal.is_some()
&& self.work_schedule_signal.is_some()
&& self.prepare_message.is_none()
&& self.pending_remote_proposal.is_none()
{
self.work()?;
}
Ok(())
}
fn work(&mut self) -> CommonResult<()> {
let high_qc = self.work_new_view_signal.clone().expect("qed");
let base_commit_qc = self.stream.storage.get_base_commit_qc();
if high_qc.node.block_hash == base_commit_qc.node.block_hash {
let schedule_info = self.work_schedule_signal.clone().expect("qed");
self.create_proposal(schedule_info)?;
} else if high_qc.node.parent_hash == base_commit_qc.node.block_hash {
self.reuse_proposal(&high_qc)?;
}
Ok(())
}
fn create_proposal(&mut self, schedule_info: ScheduleInfo) -> CommonResult<()> {
trace!("Create proposal: {:?}", schedule_info);
let build_block_params = self.stream.support.prepare_block(schedule_info)?;
let mut proposal = Proposal {
parent_hash: Hash(vec![]),
block_hash: Hash(vec![]),
number: build_block_params.number,
timestamp: build_block_params.timestamp,
meta_txs: build_block_params
.meta_txs
.iter()
.map(|x| x.tx.clone())
.collect(),
payload_txs: build_block_params
.payload_txs
.iter()
.map(|x| x.tx.clone())
.collect(),
execution_number: build_block_params.execution_number,
};
let commit_block_params = self.stream.support.build_block(build_block_params)?;
proposal.parent_hash = commit_block_params.header.parent_hash.clone();
proposal.block_hash = commit_block_params.block_hash.clone();
self.stream.commit_block_params = Some(commit_block_params);
self.stream.storage.put_proposal(proposal.clone())?;
self.on_proposal(proposal)?;
Ok(())
}
fn reuse_proposal(&mut self, high_qc: &QC) -> CommonResult<()> {
trace!("Reuse proposal: {:?}", high_qc);
let proposal = self.stream.storage.get_proposal(&high_qc.node.block_hash)?;
match proposal {
Some(proposal) => {
self.on_local_proposal(proposal)?;
}
None => {
let addresses = self.new_view_collector.get_high_qc_addresses(high_qc);
let remote_addresses = addresses
.iter()
.filter(|x| *x != &self.stream.address)
.collect::<Vec<_>>();
let rand = thread_rng().gen_range(0, remote_addresses.len());
let target_address = remote_addresses[rand];
trace!("Request proposal from remote: {}", target_address);
let req = RequestProposalReq {
request_id: RequestId(0),
block_hash: high_qc.node.block_hash.clone(),
};
self.stream.request_proposal(target_address.clone(), req)?;
self.pending_remote_proposal = Some(high_qc.node.block_hash.clone());
}
}
Ok(())
}
fn on_remote_proposal(&mut self, _address: Address, proposal: Proposal) -> CommonResult<()> {
if let Some(pending_remote_proposal) = self.pending_remote_proposal.take() {
if pending_remote_proposal != proposal.block_hash {
self.pending_remote_proposal = Some(pending_remote_proposal);
return Ok(());
}
self.on_local_proposal(proposal)?;
}
Ok(())
}
fn on_local_proposal(&mut self, proposal: Proposal) -> CommonResult<()> {
// prepare commit_block_params if needed
if self
.stream
.commit_block_params
.as_ref()
.map(|x| &x.block_hash)
!= Some(&proposal.block_hash)
{
let get_txs = |txs: &Vec<Transaction>| -> CommonResult<Vec<Arc<FullTransaction>>> {
let mut result = Vec::with_capacity(txs.len());
for tx in txs {
let tx_hash = self.stream.support.hash_transaction(&tx)?;
let tx = Arc::new(FullTransaction {
tx_hash,
tx: tx.clone(),
});
result.push(tx);
}
Ok(result)
};
let build_block_params = BuildBlockParams {
number: proposal.number,
timestamp: proposal.timestamp,
meta_txs: get_txs(&proposal.meta_txs)?,
payload_txs: get_txs(&proposal.payload_txs)?,
execution_number: proposal.execution_number,
};
let commit_block_params = self.stream.support.build_block(build_block_params)?;
self.stream.commit_block_params = Some(commit_block_params);
}
self.on_proposal(proposal)?;
Ok(())
}
fn on_validator_registered(&mut self, address: Address, peer_id: PeerId) -> CommonResult<()> {
if let Some(messages) = self.stream.pending_consensus_messages.remove(&peer_id) {
for message in messages {
self.on_validator_consensus_message(message, address.clone())?;
}
}
Ok(())
}
fn on_consensus_message(
&mut self,
message: ConsensusMessage,
peer_id: PeerId,
) -> CommonResult<()> {
if let Some(address) = self.stream.get_peer_address(&peer_id) {
if self
.stream
.authorities
.members
.iter()
.any(|(addr, _)| addr == &address)
{
self.on_validator_consensus_message(message, address)?;
}
} else {
let messages = self
.stream
.pending_consensus_messages
.entry(peer_id)
.or_insert_with(Vec::new);
messages.push(message);
}
Ok(())
}
fn on_validator_consensus_message(
&mut self,
message: ConsensusMessage,
address: Address,
) -> CommonResult<()> {
if message.view != self.stream.storage.get_view() {
return Ok(());
}
match &message.message_type {
MessageType::NewView => self.on_new_view(message, address)?,
MessageType::Prepare => self.on_prepare(message, address)?,
MessageType::PreCommit => self.on_pre_commit(message, address)?,
MessageType::Commit => self.on_commit(message, address)?,
_ => {}
}
Ok(())
}
fn on_new_view(&mut self, message: ConsensusMessage, address: Address) -> CommonResult<()> {
let justify = match &message.justify {
Some(justify) => justify,
None => return Ok(()),
};
let authorities = if justify.view == self.stream.storage.get_base_commit_qc().view {
&self.stream.last_authorities
} else {
&self.stream.authorities
};
match verify_qc(&justify, None, &authorities, &self.stream.support) {
Err(e) => {
println!(
"on_new_view verify qc failed: {}, view: {}, base_commit_qc_view: {}",
e,
justify.view,
self.stream.storage.get_base_commit_qc().view
);
return Ok(());
}
_ => {}
}
self.new_view_collector.add(address, message);
let mut high_qc = self
.new_view_collector
.get_high_qc(&self.stream.authorities);
if let Some(high_qc) = high_qc.take() {
if self.work_new_view_signal.is_none() {
trace!("New view collected high qc: {:?}", high_qc);
self.try_work(None, Some(high_qc))?;
}
}
Ok(())
}
fn on_proposal(&mut self, proposal: Proposal) -> CommonResult<()> {
trace!(
"Proposal: number: {}, execution_number: {}, block_hash: {}",
proposal.number,
proposal.execution_number,
proposal.block_hash
);
let node = Node {
block_hash: proposal.block_hash.clone(),
parent_hash: proposal.parent_hash.clone(),
};
let high_qc = self.work_new_view_signal.clone().expect("qed");
let prepare_message = ConsensusMessage {
request_id: RequestId(0),
message_type: MessageType::Prepare,
view: self.stream.storage.get_view(),
node: Some(node),
justify: Some(high_qc),
sig: None,
};
self.prepare_message = Some(prepare_message.clone());
self.on_prepare(prepare_message.clone(), self.stream.address.clone())?;
let addresses = self
.stream
.authorities
.members
.iter()
.map(|x| x.0.clone())
.collect::<Vec<_>>();
let res = RequestProposalRes {
request_id: RequestId(0),
proposal: Some(proposal),
};
for address in addresses {
if address != self.stream.address {
// send proposal
if let Some(peer_id) = self.stream.known_validators.get(&address) {
self.stream.response(peer_id.clone(), res.clone())?;
}
// send prepare message
self.stream
.consensus_message(address, prepare_message.clone())?;
}
}
Ok(())
}
fn on_prepare(&mut self, mut message: ConsensusMessage, address: Address) -> CommonResult<()> {
match self.verify_message(&mut message, &address) {
Err(_e) => return Ok(()),
_ => {}
}
self.prepare_collector.add(address, message);
let mut prepare_qc = self
.prepare_collector
.get_qc(&self.stream.authorities, self.stream.address.clone());
if let Some(prepare_qc) = prepare_qc.take() {
if self.pre_commit_message.is_none() {
trace!("Prepare collected qc: {:?}", prepare_qc);
self.stream.storage.update_prepare_qc(prepare_qc.clone())?;
let pre_commit_message = ConsensusMessage {
request_id: RequestId(0),
message_type: MessageType::PreCommit,
view: self.stream.storage.get_view(),
node: None,
justify: Some(prepare_qc),
sig: None,
};
self.pre_commit_message = Some(pre_commit_message.clone());
self.on_pre_commit(pre_commit_message.clone(), self.stream.address.clone())?;
self.broadcast_message(pre_commit_message)?;
}
}
Ok(())
}
fn on_pre_commit(
&mut self,
mut message: ConsensusMessage,
address: Address,
) -> CommonResult<()> {
match self.verify_message(&mut message, &address) {
Err(_e) => return Ok(()),
_ => {}
}
self.pre_commit_collector.add(address, message);
let mut pre_commit_qc = self
.pre_commit_collector
.get_qc(&self.stream.authorities, self.stream.address.clone());
if let Some(pre_commit_qc) = pre_commit_qc.take() {
if self.commit_message.is_none() {
trace!("PreCommit collected qc: {:?}", pre_commit_qc);
self.stream
.storage
.update_locked_qc(pre_commit_qc.clone())?;
let commit_message = ConsensusMessage {
request_id: RequestId(0),
message_type: MessageType::Commit,
view: self.stream.storage.get_view(),
node: None,
justify: Some(pre_commit_qc),
sig: None,
};
self.commit_message = Some(commit_message.clone());
self.on_commit(commit_message.clone(), self.stream.address.clone())?;
self.broadcast_message(commit_message)?;
}
}
Ok(())
}
fn on_commit(&mut self, mut message: ConsensusMessage, address: Address) -> CommonResult<()> {
match self.verify_message(&mut message, &address) {
Err(_e) => return Ok(()),
_ => {}
}
self.commit_collector.add(address, message);
let mut commit_qc = self
.commit_collector
.get_qc(&self.stream.authorities, self.stream.address.clone());
if let Some(commit_qc) = commit_qc.take() {
if self.decide_message.is_none() {
trace!("Commit collected qc: {:?}", commit_qc);
let decide_message = ConsensusMessage {
request_id: RequestId(0),
message_type: MessageType::Decide,
view: self.stream.storage.get_view(),
node: None,
justify: Some(commit_qc.clone()),
sig: None,
};
self.decide_message = Some(decide_message.clone());
self.on_decide(commit_qc)?;
self.broadcast_message(decide_message)?;
}
}
Ok(())
}
fn on_decide(&mut self, commit_qc: QC) -> CommonResult<()> {
let block_hash = &commit_qc.node.block_hash;
let proposal = self.stream.storage.get_proposal(block_hash)?;
let proposal = match proposal {
Some(proposal) => proposal,
None => return Ok(()),
};
let commit_block_params = match self.stream.commit_block_params.take() {
Some(v) => {
if v.block_hash == proposal.block_hash {
v
} else {
return Ok(());
}
}
None => return Ok(()),
};
self.stream.on_decide(commit_block_params, commit_qc)?;
Ok(())
}
fn process_pending_new_view(&mut self) -> CommonResult<()> {
let messages = self
.stream
.pending_new_view_messages
.drain(..)
.collect::<Vec<_>>();
for (message, address) in messages {
self.on_new_view(message, address)?;
}
Ok(())
}
fn send_new_view_to_self(&mut self) -> CommonResult<()> {
let message = ConsensusMessage {
request_id: RequestId(0),
message_type: MessageType::NewView,
view: self.stream.storage.get_view(),
node: None,
justify: Some(self.stream.storage.get_prepare_qc()),
sig: None,
};
self.on_new_view(message, self.stream.address.clone())?;
Ok(())
}
fn sign_message(&self, message: &mut ConsensusMessage) -> CommonResult<()> {
let leader_address = self.stream.current_leader.clone().expect("qed");
let sig_message = codec::encode(&(
&message.message_type,
&message.view,
&message.node,
&leader_address,
))?;
let sig = sign(&sig_message, &self.stream.secret_key, &self.stream.support)?;
message.sig = Some((self.stream.public_key.clone(), sig));
Ok(())
}
fn verify_message(
&self,
message: &mut ConsensusMessage,
address: &Address,
) -> CommonResult<()> {
if &self.stream.address == address {
message.node = self.prepare_message.as_ref().expect("qed").node.clone();
message.justify = None;
self.sign_message(message)?;
return Ok(());
}
// verify sig
let (public_key, signature) = match message.sig {
Some(ref sig) => sig,
None => return Err(ErrorKind::MessageError("Missing sig".to_string()).into()),
};
let expected_address = get_address(&public_key, &self.stream.support)?;
if &expected_address != address {
return Err(ErrorKind::MessageError("Unexpected address".to_string()).into());
}
let sig_message = codec::encode(&(
&message.message_type,
&message.view,
&message.node,
&self.stream.address,
))?;
verify(&sig_message, &public_key, &signature, &self.stream.support)?;
// verify node
if message.node != self.prepare_message.as_ref().expect("qed").node {
return Err(ErrorKind::MessageError("Unexpected node".to_string()).into());
}
Ok(())
}
fn broadcast_message(&mut self, message: ConsensusMessage) -> CommonResult<()> {
let addresses = self
.stream
.authorities
.members
.iter()
.map(|x| x.0.clone())
.collect::<Vec<_>>();
for address in addresses {
if address != self.stream.address {
self.stream.consensus_message(address, message.clone())?;
}
}
Ok(())
}
}
pub struct ReplicaState<'a, S>
where
S: ConsensusSupport,
{
stream: &'a mut HotStuffStream<S>,
}
impl<'a, S> ReplicaState<'a, S>
where
S: ConsensusSupport,
{
pub fn new(stream: &'a mut HotStuffStream<S>) -> Self {
Self { stream }
}
pub async fn start(mut self) -> CommonResult<()> {
let current_view = self.stream.storage.get_view();
self.send_new_view()?;
loop {
if self.stream.shutdown {
return Ok(());
}
if self.stream.storage.get_view() != current_view {
return Ok(());
}
let next_timeout = sleep_until(self.stream.next_timeout_instant());
tokio::select! {
_ = next_timeout => {
self.stream.on_timeout()?;
},
Some(internal_message) = self.stream.internal_rx.next() => {
match internal_message {
InternalMessage::ValidatorRegistered { address, peer_id } => {
self.on_validator_registered(address, peer_id)
.unwrap_or_else(|e| warn!("HotStuff stream handle validator registered message error: {}", e));
},
InternalMessage::ConsensusMessage {message, peer_id } => {
self.on_consensus_message(message, peer_id)
.unwrap_or_else(|e| warn!("HotStuff stream handle consensus message error: {}", e));
}
_ => {
self.stream.on_internal_message(internal_message)
.unwrap_or_else(|e| warn!("HotStuff stream handle internal message error: {}", e));
}
}
},
in_message = self.stream.in_rx.next() => {
match in_message {
Some(in_message) => {
self.stream.on_in_message(in_message)
.unwrap_or_else(|e| warn!("HotStuff stream handle in message error: {}", e));
},
// in tx has been dropped
None => {
self.stream.shutdown = true;
},
}
},
}
}
}
fn on_validator_registered(&mut self, address: Address, peer_id: PeerId) -> CommonResult<()> {
if self.stream.current_leader.as_ref() == Some(&address) {
self.send_new_view()?;
}
if let Some(messages) = self.stream.pending_consensus_messages.remove(&peer_id) {
for message in messages {
self.on_validator_consensus_message(message, address.clone())?;
}
}
Ok(())
}
fn on_consensus_message(
&mut self,
message: ConsensusMessage,
peer_id: PeerId,
) -> CommonResult<()> {
if let Some(address) = self.stream.get_peer_address(&peer_id) {
if self
.stream
.authorities
.members
.iter()
.any(|(addr, _)| addr == &address)
{
self.on_validator_consensus_message(message, address)?;
}
} else {
let messages = self
.stream
.pending_consensus_messages
.entry(peer_id)
.or_insert_with(Vec::new);
messages.push(message);
}
Ok(())
}
fn on_validator_consensus_message(
&mut self,
message: ConsensusMessage,
address: Address,
) -> CommonResult<()> {
if let MessageType::NewView = &message.message_type {
self.on_new_view(message.clone(), address.clone())?
}
if message.view != self.stream.storage.get_view() {
return Ok(());
}
match &message.message_type {
MessageType::Prepare => self.on_prepare(message, address)?,
MessageType::PreCommit => self.on_pre_commit(message, address)?,
MessageType::Commit => self.on_commit(message, address)?,
MessageType::Decide => self.on_decide(message, address)?,
_ => {}
}
Ok(())
}
fn on_new_view(&mut self, message: ConsensusMessage, address: Address) -> CommonResult<()> {
self.stream
.pending_new_view_messages
.push((message, address));
Ok(())
}
fn on_prepare(&mut self, message: ConsensusMessage, _address: Address) -> CommonResult<()> {
let justify = match message.justify {
Some(justify) => justify,
None => return Ok(()),
};
let authorities = if justify.view == self.stream.storage.get_base_commit_qc().view {
&self.stream.last_authorities
} else {
&self.stream.authorities
};
match verify_qc(&justify, None, &authorities, &self.stream.support) {
Err(_e) => return Ok(()),
_ => {}
}
let node = match &message.node {
Some(node) => node,
None => return Ok(()),
};
let block_hash = &node.block_hash;
let proposal = self.stream.storage.get_proposal(block_hash)?;
let proposal = match proposal {
Some(proposal) => proposal,
None => return Ok(()),
};
// check safe node
if node.parent_hash != proposal.parent_hash {
return Ok(());
}
let base_commit_qc = self.stream.storage.get_base_commit_qc();
let locked_qc = self.stream.storage.get_locked_qc();
let extend_from_justify_node = if justify.node.block_hash == base_commit_qc.node.block_hash
{
node.parent_hash == base_commit_qc.node.block_hash
} else {
node.block_hash == justify.node.block_hash
};
let extend_from_locked_qc_node =
if locked_qc.node.block_hash == base_commit_qc.node.block_hash {
node.parent_hash == base_commit_qc.node.block_hash
} else {
node.block_hash == locked_qc.node.block_hash
};
let higher_view = justify.view > locked_qc.view;
let safe_node = extend_from_justify_node && (extend_from_locked_qc_node || higher_view);
if !safe_node {
warn!("Not safe node: {:?}", node);
return Ok(());
}
let mut vote_message = ConsensusMessage {
request_id: RequestId(0),
message_type: message.message_type,
view: message.view,
node: message.node,
justify: None,
sig: None,
};
self.sign_message(&mut vote_message)?;
let leader_address = self.stream.current_leader.clone().expect("qed");
self.stream
.consensus_message(leader_address, vote_message)?;
Ok(())
}
fn on_pre_commit(&mut self, message: ConsensusMessage, _address: Address) -> CommonResult<()> {
let justify = match message.justify {
Some(justify) => justify,
None => return Ok(()),
};
match verify_qc(
&justify,
Some(MessageType::Prepare),
&self.stream.authorities,
&self.stream.support,
) {
Err(_e) => return Ok(()),
_ => {}
}
self.stream.storage.update_prepare_qc(justify.clone())?;
let mut vote_message = ConsensusMessage {
request_id: RequestId(0),
message_type: message.message_type,
view: message.view,
node: Some(justify.node),
justify: None,
sig: None,
};
self.sign_message(&mut vote_message)?;
let leader_address = self.stream.current_leader.clone().expect("qed");
self.stream
.consensus_message(leader_address, vote_message)?;
Ok(())
}
fn on_commit(&mut self, message: ConsensusMessage, _address: Address) -> CommonResult<()> {
let justify = match message.justify {
Some(justify) => justify,
None => return Ok(()),
};
match verify_qc(
&justify,
Some(MessageType::PreCommit),
&self.stream.authorities,
&self.stream.support,
) {
Err(_e) => return Ok(()),
_ => {}
}
self.stream.storage.update_locked_qc(justify.clone())?;
let mut vote_message = ConsensusMessage {
request_id: RequestId(0),
message_type: message.message_type,
view: message.view,
node: Some(justify.node),
justify: None,
sig: None,
};
self.sign_message(&mut vote_message)?;
let leader_address = self.stream.current_leader.clone().expect("qed");
self.stream
.consensus_message(leader_address, vote_message)?;
Ok(())
}
fn on_decide(&mut self, message: ConsensusMessage, _address: Address) -> CommonResult<()> {
let justify = match message.justify {
Some(justify) => justify,
None => return Ok(()),
};
match verify_qc(
&justify,
Some(MessageType::Commit),
&self.stream.authorities,
&self.stream.support,
) {
Err(_e) => return Ok(()),
_ => {}
}
let block_hash = &justify.node.block_hash;
let proposal = self.stream.storage.get_proposal(block_hash)?;
let proposal = match proposal {
Some(proposal) => proposal,
None => return Ok(()),
};
let commit_block_params = match self.stream.commit_block_params.take() {
Some(v) => {
if v.block_hash == proposal.block_hash {
v
} else {
return Ok(());
}
}
None => return Ok(()),
};
self.stream.on_decide(commit_block_params, justify)?;
Ok(())
}
fn send_new_view(&mut self) -> CommonResult<()> {
let leader_address = self.stream.current_leader.clone().expect("qed");
let message = ConsensusMessage {
request_id: RequestId(0),
message_type: MessageType::NewView,
view: self.stream.storage.get_view(),
node: None,
justify: Some(self.stream.storage.get_prepare_qc()),
sig: None,
};
self.stream.consensus_message(leader_address, message)?;
Ok(())
}
fn sign_message(&self, message: &mut ConsensusMessage) -> CommonResult<()> {
let leader_address = self.stream.current_leader.clone().expect("qed");
let sig_message = codec::encode(&(
&message.message_type,
&message.view,
&message.node,
&leader_address,
))?;
let sig = sign(&sig_message, &self.stream.secret_key, &self.stream.support)?;
message.sig = Some((self.stream.public_key.clone(), sig));
Ok(())
}
}
pub struct ObserverState<'a, S>
where
S: ConsensusSupport,
{
stream: &'a mut HotStuffStream<S>,
}
impl<'a, S> ObserverState<'a, S>
where
S: ConsensusSupport,
{
pub fn new(stream: &'a mut HotStuffStream<S>) -> Self {
Self { stream }
}
pub async fn start(mut self) -> CommonResult<()> {
let current_view = self.stream.storage.get_view();
loop {
if self.stream.shutdown {
return Ok(());
}
if self.stream.storage.get_view() != current_view {
return Ok(());
}
tokio::select! {
Some(internal_message) = self.stream.internal_rx.next() => {
match internal_message {
InternalMessage::ValidatorRegistered { address, peer_id } => {
self.on_validator_registered(address, peer_id)
.unwrap_or_else(|e| warn!("HotStuff stream handle validator registered message error: {}", e));
},
InternalMessage::ConsensusMessage {message, peer_id } => {
self.on_consensus_message(message, peer_id)
.unwrap_or_else(|e| warn!("HotStuff stream handle consensus message error: {}", e));
}
_ => {
self.stream.on_internal_message(internal_message)
.unwrap_or_else(|e| warn!("HotStuff stream handle internal message error: {}", e));
}
}
},
in_message = self.stream.in_rx.next() => {
match in_message {
Some(in_message) => {
self.stream.on_in_message(in_message)
.unwrap_or_else(|e| warn!("HotStuff stream handle in message error: {}", e));
},
// in tx has been dropped
None => {
self.stream.shutdown = true;
},
}
},
}
}
}
fn on_validator_registered(&mut self, address: Address, peer_id: PeerId) -> CommonResult<()> {
if let Some(messages) = self.stream.pending_consensus_messages.remove(&peer_id) {
for message in messages {
self.on_validator_consensus_message(message, address.clone())?;
}
}
Ok(())
}
fn on_consensus_message(
&mut self,
message: ConsensusMessage,
peer_id: PeerId,
) -> CommonResult<()> {
if let Some(address) = self.stream.get_peer_address(&peer_id) {
if self
.stream
.authorities
.members
.iter()
.any(|(addr, _)| addr == &address)
{
self.on_validator_consensus_message(message, address)?;
}
} else {
let messages = self
.stream
.pending_consensus_messages
.entry(peer_id)
.or_insert_with(Vec::new);
messages.push(message);
}
Ok(())
}
fn on_validator_consensus_message(
&mut self,
message: ConsensusMessage,
address: Address,
) -> CommonResult<()> {
if let MessageType::NewView = &message.message_type {
self.on_new_view(message, address)?
}
Ok(())
}
fn on_new_view(&mut self, message: ConsensusMessage, address: Address) -> CommonResult<()> {
self.stream
.pending_new_view_messages
.push((message, address));
Ok(())
}
}
struct ConsensusMessageCollector {
messages: HashMap<Address, ConsensusMessage>,
}
impl ConsensusMessageCollector {
fn new() -> Self {
Self {
messages: Default::default(),
}
}
fn add(&mut self, address: Address, message: ConsensusMessage) {
self.messages.insert(address, message);
}
fn get_high_qc(&self, authorities: &Authorities) -> Option<QC> {
let n = authorities.members.iter().fold(0u32, |sum, x| sum + x.1);
let f = (n - 1) / 3;
let member_weight = authorities
.members
.iter()
.map(|x| (&x.0, x.1))
.collect::<HashMap<_, _>>();
let mut total_weight = 0;
let mut high_qc = None;
for (address, message) in &self.messages {
let justify = message.justify.as_ref().expect("qed");
if let Some(weight) = member_weight.get(address) {
total_weight += weight;
high_qc = match high_qc {
None => Some(justify.clone()),
Some(high_qc) => {
if justify.view > high_qc.view {
Some(justify.clone())
} else {
Some(high_qc)
}
}
}
}
if total_weight >= n - f {
return high_qc;
}
}
None
}
fn get_high_qc_addresses(&self, qc: &QC) -> Vec<Address> {
self.messages
.iter()
.filter_map(|(address, message)| {
if message.justify.as_ref() == Some(qc) {
Some(address.clone())
} else {
None
}
})
.collect()
}
fn get_qc(&self, authorities: &Authorities, leader_address: Address) -> Option<QC> {
let n = authorities.members.iter().fold(0u32, |sum, x| sum + x.1);
let f = (n - 1) / 3;
let member_weight = authorities
.members
.iter()
.map(|x| (&x.0, x.1))
.collect::<HashMap<_, _>>();
let mut total_weight = 0;
let mut qc_sig = vec![];
for (address, message) in &self.messages {
if let Some(weight) = member_weight.get(address) {
total_weight += weight;
qc_sig.push(message.sig.clone().expect("qed"));
}
if total_weight >= n - f {
let qc = QC {
message_type: message.message_type.clone(),
view: message.view,
node: message.node.clone().expect("qed"),
leader_address,
sig: qc_sig,
};
return Some(qc);
}
}
None
}
}
|
use hyper::header;
use hyper::Uri;
use websub_sub::hub;
use crate::feed::{self, RawFeed};
use crate::websub::Connection;
#[derive(clap::Args)]
pub struct Opt {
callback: Uri,
hub: Option<String>,
topic: String,
}
pub async fn main(opt: Opt) -> anyhow::Result<()> {
let client = crate::common::http_client();
let mut conn = Connection::new(crate::common::open_database()?);
if let Some(hub) = opt.hub {
hub::subscribe(&opt.callback, hub, opt.topic, &client, &mut conn)?.await?;
} else {
let res = client.get((&opt.topic[..]).try_into()?).await?;
if res.status() != hyper::StatusCode::OK {
anyhow::bail!("Bad status: {}", res.status());
}
let mime = res
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse().ok())
.unwrap_or(feed::MediaType::Xml);
let body = hyper::body::to_bytes(res.into_body()).await?;
let feed::Meta { topic, hubs, .. } = RawFeed::parse(mime, &body).unwrap().take_meta();
let topic = topic.as_deref().unwrap_or(&opt.topic);
for hub in hubs {
hub::subscribe(
&opt.callback,
hub.to_string(),
topic.to_owned(),
&client,
&mut conn,
)?
.await?;
}
}
Ok(())
}
|
#![deny(warnings)]
#![no_main]
#![no_std]
extern crate panic_semihosting;
use maple_mini::{
gpio::{Output, PushPull},
pins::*,
prelude::*,
timer,
};
use rtfm::app;
#[app(device = maple_mini::device)]
const APP: () = {
static mut LED: LedPin<Output<PushPull>> = ();
#[init]
fn init() {
let mut rcc = device.RCC.constrain();
let mut flash = device.FLASH.constrain();
let clocks = rcc.cfgr.freeze(&mut flash.acr);
let mut gpiob = device.GPIOB.split(&mut rcc.apb2);
timer::Timer::syst(core.SYST, 1.hz(), clocks).listen(timer::Event::Update);
LED = gpiob.pb1.into_push_pull_output(&mut gpiob.crl);
}
#[exception(resources = [LED], binds=SysTick)]
fn toggle_led() {
if resources.LED.is_set_high() {
resources.LED.set_low();
} else {
resources.LED.set_high();
}
}
};
|
mod json;
mod package_key;
mod target;
pub use json::{JsonMarshaler, JsonRefMarshaler};
pub use package_key::PackageKeyMarshaler;
pub use target::TargetMarshaler;
|
#!/usr/local/bin/rust run
fn main(){
let mut sum = 0;
let mut term0;
let mut term1 = 0;
let mut term2 = 1;
loop{
term0 = term1 + term2;
if term0 >= 4000000{
break;
}else if term0 % 2 == 0{
sum += term0
}
term2 = term1;
term1 = term0;
}
println(fmt!("The total sum is %u", sum))
} |
mod blake2b;
mod blake2s;
use crate::consts::{IV32, IV64, SIGMA};
pub use blake2b::Blake2b;
pub use blake2s::Blake2s;
struct Blake2<T> {
f: bool, // finalization flag
l: usize, // 未処理のバイト数
h: [T; 8],
t: [T; 2], // counter: 処理したバイト数(と次に処理をするブロックのバイト数?)
n: usize, // 出力バイト数
v: [T; 16], // state
}
impl Blake2<u32> {
fn new(n: usize) -> Self {
if !(1..=32).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
Self {
f: false,
l: 0,
h: [
IV32[0] ^ (0x0101_0000 | n as u32),
IV32[1],
IV32[2],
IV32[3],
IV32[4],
IV32[5],
IV32[6],
IV32[7],
],
t: [0; 2],
n,
v: [0; 16],
}
}
fn with_key(n: usize, k: usize, salt: [u32; 2], personal: [u32; 2]) -> Self {
if !(1..=32).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
if k > 32 {
panic!("{} is not a valid number. k must be between 0 and 32.", k)
}
if k == 0 {
return Self::new(n);
}
Self {
f: false,
l: 0,
h: [
IV32[0] ^ (0x0101_0000 | (k << 8) as u32 | n as u32),
IV32[1],
IV32[2],
IV32[3],
IV32[4] ^ salt[0].swap_bytes(),
IV32[5] ^ salt[1].swap_bytes(),
IV32[6] ^ personal[0].swap_bytes(),
IV32[7] ^ personal[1].swap_bytes(),
],
t: [0; 2],
n,
v: [0; 16],
}
}
#[inline(always)]
#[allow(clippy::too_many_arguments, clippy::many_single_char_names)]
fn g(&mut self, block: &[u32; 16], i: usize, r: usize, a: usize, b: usize, c: usize, d: usize) {
self.v[a] = self.v[a]
.wrapping_add(self.v[b])
.wrapping_add(block[SIGMA[r][2 * i]]);
self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(16);
self.v[c] = self.v[c].wrapping_add(self.v[d]);
self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(12);
self.v[a] = self.v[a]
.wrapping_add(self.v[b])
.wrapping_add(block[SIGMA[r][2 * i + 1]]);
self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(8);
self.v[c] = self.v[c].wrapping_add(self.v[d]);
self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(7);
}
#[inline(always)]
fn compress(&mut self, block: &[u32; 16]) {
// update counter
if self.l > 64 {
self.t[0] += 64;
self.l -= 64;
} else {
self.t[0] += self.l as u32;
self.l = 0;
self.f = true;
}
// initialize state
self.v[0] = self.h[0];
self.v[1] = self.h[1];
self.v[2] = self.h[2];
self.v[3] = self.h[3];
self.v[4] = self.h[4];
self.v[5] = self.h[5];
self.v[6] = self.h[6];
self.v[7] = self.h[7];
self.v[8] = IV32[0];
self.v[9] = IV32[1];
self.v[10] = IV32[2];
self.v[11] = IV32[3];
self.v[12] = IV32[4] ^ self.t[0];
self.v[13] = IV32[5] ^ self.t[1];
if self.f {
self.v[14] = IV32[6] ^ u32::MAX;
self.v[15] = IV32[7] ^ u32::MIN;
} else {
self.v[14] = IV32[6];
self.v[15] = IV32[7];
}
// round
for r in 0..10 {
self.g(block, 0, r, 0, 4, 8, 12);
self.g(block, 1, r, 1, 5, 9, 13);
self.g(block, 2, r, 2, 6, 10, 14);
self.g(block, 3, r, 3, 7, 11, 15);
self.g(block, 4, r, 0, 5, 10, 15);
self.g(block, 5, r, 1, 6, 11, 12);
self.g(block, 6, r, 2, 7, 8, 13);
self.g(block, 7, r, 3, 4, 9, 14);
}
// finalize
for i in 0..8 {
self.h[i] = self.h[i] ^ self.v[i] ^ self.v[i + 8];
}
}
}
impl Blake2<u64> {
fn new(n: usize) -> Self {
if !(1..=64).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
Self {
f: false,
l: 0,
h: [
IV64[0] ^ (0x0101_0000 | n as u64),
IV64[1],
IV64[2],
IV64[3],
IV64[4],
IV64[5],
IV64[6],
IV64[7],
],
t: [0; 2],
n,
v: [0; 16],
}
}
fn with_key(n: usize, k: usize, salt: [u64; 2], personal: [u64; 2]) -> Self {
if !(1..=64).contains(&n) {
panic!("{} is not a valid number. n must be between 1 and 32.", n);
}
if k > 64 {
panic!("{} is not a valid number. k must be between 0 and 64.", k)
}
if k == 0 {
return Self::new(n);
}
Self {
f: false,
l: 0,
h: [
IV64[0] ^ (0x0101_0000 | (k << 8) as u64 | n as u64),
IV64[1],
IV64[2],
IV64[3],
IV64[4] ^ salt[0].swap_bytes(),
IV64[5] ^ salt[1].swap_bytes(),
IV64[6] ^ personal[0].swap_bytes(),
IV64[7] ^ personal[1].swap_bytes(),
],
t: [0; 2],
n,
v: [0; 16],
}
}
#[inline(always)]
#[allow(clippy::too_many_arguments, clippy::many_single_char_names)]
fn g(&mut self, block: &[u64; 16], i: usize, r: usize, a: usize, b: usize, c: usize, d: usize) {
// a,b,c,d: index of self.v
// i: number of function G
// r: round count
self.v[a] = self.v[a]
.wrapping_add(self.v[b])
.wrapping_add(block[SIGMA[r % 10][2 * i]]);
self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(32);
self.v[c] = self.v[c].wrapping_add(self.v[d]);
self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(24);
self.v[a] = self.v[a]
.wrapping_add(self.v[b])
.wrapping_add(block[SIGMA[r % 10][2 * i + 1]]);
self.v[d] = (self.v[d] ^ self.v[a]).rotate_right(16);
self.v[c] = self.v[c].wrapping_add(self.v[d]);
self.v[b] = (self.v[b] ^ self.v[c]).rotate_right(63);
}
#[inline(always)]
fn compress(&mut self, block: &[u64; 16]) {
// update counter
if self.l > 128 {
self.t[0] += 128;
self.l -= 128;
} else {
self.t[0] += self.l as u64;
self.l = 0;
self.f = true;
}
// initialize state
self.v[0] = self.h[0];
self.v[1] = self.h[1];
self.v[2] = self.h[2];
self.v[3] = self.h[3];
self.v[4] = self.h[4];
self.v[5] = self.h[5];
self.v[6] = self.h[6];
self.v[7] = self.h[7];
self.v[8] = IV64[0];
self.v[9] = IV64[1];
self.v[10] = IV64[2];
self.v[11] = IV64[3];
self.v[12] = IV64[4] ^ self.t[0];
self.v[13] = IV64[5] ^ self.t[1];
if self.f {
self.v[14] = IV64[6] ^ u64::MAX;
self.v[15] = IV64[7] ^ u64::MIN;
} else {
self.v[14] = IV64[6];
self.v[15] = IV64[7];
}
// round
for r in 0..12 {
self.g(block, 0, r, 0, 4, 8, 12);
self.g(block, 1, r, 1, 5, 9, 13);
self.g(block, 2, r, 2, 6, 10, 14);
self.g(block, 3, r, 3, 7, 11, 15);
self.g(block, 4, r, 0, 5, 10, 15);
self.g(block, 5, r, 1, 6, 11, 12);
self.g(block, 6, r, 2, 7, 8, 13);
self.g(block, 7, r, 3, 4, 9, 14);
}
// finalize
for i in 0..8 {
self.h[i] = self.h[i] ^ self.v[i] ^ self.v[i + 8];
}
}
}
|
use crate::models::{Company, WorkerTypes, Department, GroupTypes, Contract, EqGroupList, EquipmentType, Project, Worker, ConstrAttr, EngAttr, LabAttr, MechAttr, Equipment, GroupsBind, WorkingCompany, DepartmentHead, EqGroup, Groups, PcBind};
use diesel::{PgConnection, QueryDsl, ExpressionMethods, AppearsOnTable, RunQueryDsl};
use diesel::query_builder::QueryFragment;
use diesel::pg::Pg;
use crate::pagination::Paginate;
#[derive(Debug, Deserialize)]
pub struct Params {
pub page: Option<i64>,
pub page_size: Option<i64>,
}
impl Company{
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::company;
let column = match column_name.as_str(){
"company_name"=>{company::company_name}
_=>{company::company_name}
};
let mut query = company::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let res = match order.as_str(){
"ASC"=>{
match query.order_by(column.asc()).paginate(page).load::<(Company, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
"DESC" | _=>{
match query.order_by(column.desc()).paginate(page).load::<(Company, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl WorkerTypes{
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::worker_types;
let column = match column_name.as_str(){
"worker_type"=>{worker_types::worker_type}
_=>{worker_types::worker_type}
};
let mut query = worker_types::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let res = match order.as_str(){
"ASC"=>{
match query.order_by(column.asc()).paginate(page).load::<(WorkerTypes, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
"DESC" | _=>{
match query.order_by(column.desc()).paginate(page).load::<(WorkerTypes, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl Department{
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::department;
let column = match column_name.as_str(){
"department_name"=>{department::department_name}
_=>{department::department_name}
};
let mut query = department::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let res = match order.as_str(){
"ASC"=>{
match query.order_by(column.asc()).paginate(page).load::<(Department, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
"DESC" | _=>{
match query.order_by(column.desc()).paginate(page).load::<(Department, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl GroupTypes{
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::group_types;
let column = match column_name.as_str(){
"group_type"=>{group_types::group_type}
_=>{group_types::group_type}
};
let mut query = group_types::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let res = match order.as_str(){
"ASC"=>{
match query.order_by(column.asc()).paginate(page).load::<(GroupTypes, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
"DESC" | _=>{
match query.order_by(column.desc()).paginate(page).load::<(GroupTypes, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
}
}
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl Contract{
fn sort_by_column<U: 'static>(mut query: crate::schema::contract::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::contract::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::contract::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::contract;
let mut query = contract::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"contract_id" => Contract::sort_by_column(query, contract::contract_id, order),
"contract_start" => Contract::sort_by_column(query, contract::contract_start, order),
"contract_end" => Contract::sort_by_column(query, contract::contract_end, order),
"cost" => Contract::sort_by_column(query, contract::cost, order),
_ => Contract::sort_by_column(query, contract::contract_id, order)
};
let res =match query_res.paginate(page).load::<(Contract, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl EqGroupList{
fn sort_by_column<U: 'static>(mut query: crate::schema::eq_group_list::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::eq_group_list::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::eq_group_list::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::eq_group_list;
let mut query = eq_group_list::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"eq_list_id" => EqGroupList::sort_by_column(query, eq_group_list::eq_list_id, order),
_ => EqGroupList::sort_by_column(query, eq_group_list::eq_list_id, order)
};
let res =match query_res.paginate(page).load::<(EqGroupList, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl EquipmentType{
fn sort_by_column<U: 'static>(mut query: crate::schema::equipment_type::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::equipment_type::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::equipment_type::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::equipment_type;
let mut query = equipment_type::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"type" => EquipmentType::sort_by_column(query, equipment_type::type_, order),
_ => EquipmentType::sort_by_column(query, equipment_type::type_, order)
};
let res =match query_res.paginate(page).load::<(EquipmentType, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl Project{
fn sort_by_column<U: 'static>(mut query: crate::schema::project::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::project::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::project::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::project;
let mut query = project::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"project_id" => Project::sort_by_column(query, project::project_id, order),
"cost" => Project::sort_by_column(query, project::cost, order),
"data" => Project::sort_by_column(query, project::data, order),
_ => Project::sort_by_column(query, project::project_id, order)
};
let res =match query_res.paginate(page).load::<(Project, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl Worker{
fn sort_by_column<U: 'static>(mut query: crate::schema::worker::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::worker::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::worker::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::worker;
let mut query = worker::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"worker_id" => Worker::sort_by_column(query, worker::worker_id, order),
"firstname" => Worker::sort_by_column(query, worker::firstname, order),
"secondname" => Worker::sort_by_column(query, worker::secondname, order),
"familyname" => Worker::sort_by_column(query, worker::familyname, order),
"worker_type" => Worker::sort_by_column(query, worker::worker_type, order),
"department_name" => Worker::sort_by_column(query, worker::department_name, order),
"age" => Worker::sort_by_column(query, worker::age, order),
"salary" => Worker::sort_by_column(query, worker::salary, order),
_ => Worker::sort_by_column(query, worker::worker_id, order)
};
let res =match query_res.paginate(page).load::<(Worker, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl ConstrAttr{
fn sort_by_column<U: 'static>(mut query: crate::schema::constr_attr::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::constr_attr::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::constr_attr::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::constr_attr;
let mut query = constr_attr::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"worker_id" => ConstrAttr::sort_by_column(query, constr_attr::worker_id, order),
"cert_number" => ConstrAttr::sort_by_column(query, constr_attr::cert_number, order),
_ => ConstrAttr::sort_by_column(query, constr_attr::worker_id, order)
};
let res =match query_res.paginate(page).load::<(ConstrAttr, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl EngAttr{
fn sort_by_column<U: 'static>(mut query: crate::schema::eng_attr::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::eng_attr::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::eng_attr::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::eng_attr;
let mut query = eng_attr::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"worker_id" => EngAttr::sort_by_column(query, eng_attr::worker_id, order),
"category" => EngAttr::sort_by_column(query, eng_attr::category, order),
_ => EngAttr::sort_by_column(query, eng_attr::worker_id, order)
};
let res =match query_res.paginate(page).load::<(EngAttr, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl LabAttr{
fn sort_by_column<U: 'static>(mut query: crate::schema::lab_attr::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::lab_attr::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::lab_attr::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::lab_attr;
let mut query = lab_attr::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"worker_id" => LabAttr::sort_by_column(query, lab_attr::worker_id, order),
"lab_number" => LabAttr::sort_by_column(query, lab_attr::lab_number, order),
_ => LabAttr::sort_by_column(query, lab_attr::worker_id, order)
};
let res =match query_res.paginate(page).load::<(LabAttr, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl MechAttr{
fn sort_by_column<U: 'static>(mut query: crate::schema::mech_attr::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::mech_attr::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::mech_attr::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::mech_attr;
let mut query = mech_attr::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"worker_id" => MechAttr::sort_by_column(query, mech_attr::worker_id, order),
"repair_type" => MechAttr::sort_by_column(query, mech_attr::repair_type, order),
_ => MechAttr::sort_by_column(query, mech_attr::worker_id, order)
};
let res =match query_res.paginate(page).load::<(MechAttr, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl Equipment{
fn sort_by_column<U: 'static>(mut query: crate::schema::equipment::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::equipment::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::equipment::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::equipment;
let mut query = equipment::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"eq_id" => Equipment::sort_by_column(query, equipment::eq_id, order),
"name" => Equipment::sort_by_column(query, equipment::name, order),
"type" => Equipment::sort_by_column(query, equipment::type_, order),
"department_name" => Equipment::sort_by_column(query, equipment::department_name, order),
_ => Equipment::sort_by_column(query, equipment::eq_id, order)
};
let res =match query_res.paginate(page).load::<(Equipment, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl GroupsBind{
fn sort_by_column<U: 'static>(mut query: crate::schema::groups_bind::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::groups_bind::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::groups_bind::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::groups_bind;
let mut query = groups_bind::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"group_id" => GroupsBind::sort_by_column(query, groups_bind::group_id, order),
"cost" => GroupsBind::sort_by_column(query, groups_bind::cost, order),
"group_type" => GroupsBind::sort_by_column(query, groups_bind::group_type, order),
_ => GroupsBind::sort_by_column(query, groups_bind::group_id, order)
};
let res =match query_res.paginate(page).load::<(GroupsBind, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl WorkingCompany{
fn sort_by_column<U: 'static>(mut query: crate::schema::working_company::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::working_company::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::working_company::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::working_company;
let mut query = working_company::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"group_id" => WorkingCompany::sort_by_column(query, working_company::group_id, order),
"company_name" => WorkingCompany::sort_by_column(query, working_company::company_name, order),
_ => WorkingCompany::sort_by_column(query, working_company::group_id, order)
};
let res =match query_res.paginate(page).load::<(WorkingCompany, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl DepartmentHead{
fn sort_by_column<U: 'static>(mut query: crate::schema::department_head::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::department_head::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::department_head::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::department_head;
let mut query = department_head::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"department_name" => DepartmentHead::sort_by_column(query, department_head::department_name, order),
"worker_id" => DepartmentHead::sort_by_column(query, department_head::worker_id, order),
_ => DepartmentHead::sort_by_column(query, department_head::department_name, order)
};
let res =match query_res.paginate(page).load::<(DepartmentHead, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl EqGroup{
fn sort_by_column<U: 'static>(mut query: crate::schema::eq_group::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::eq_group::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::eq_group::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::eq_group;
let mut query = eq_group::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"id" => EqGroup::sort_by_column(query, eq_group::id, order),
"eq_list_id" => EqGroup::sort_by_column(query, eq_group::eq_list_id, order),
"eq_id" => EqGroup::sort_by_column(query, eq_group::eq_id, order),
_ => EqGroup::sort_by_column(query, eq_group::eq_list_id, order)
};
let res =match query_res.paginate(page).load::<(EqGroup, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl Groups{
fn sort_by_column<U: 'static>(mut query: crate::schema::groups::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::groups::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::groups::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::groups;
let mut query = groups::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"id" => Groups::sort_by_column(query, groups::id, order),
"group_id" => Groups::sort_by_column(query, groups::group_id, order),
"worker_id" => Groups::sort_by_column(query, groups::worker_id, order),
_ => Groups::sort_by_column(query, groups::group_id, order)
};
let res =match query_res.paginate(page).load::<(Groups, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
}
impl PcBind{
fn sort_by_column<U: 'static>(mut query: crate::schema::pc_bind::BoxedQuery<'static, Pg>,
column: U,
sort_dir: String) -> crate::schema::pc_bind::BoxedQuery<'static, Pg>
where U: ExpressionMethods + QueryFragment<Pg> + AppearsOnTable<crate::schema::pc_bind::table>{
match sort_dir.as_str() {
"ASC" => query.order_by(column.asc()),
"DESC" => query.order_by(column.desc()),
_ => query.order_by(column.desc())
}
}
pub fn get_page(params: Params, connection: &PgConnection,column_name:String,order:String)->Result<(Vec<Self>, i64),&'static str>{
use crate::schema::pc_bind;
let mut query = pc_bind::table.into_boxed();
let (values,total_pages) = match params.page{
None => { (
match query.load(connection) {
Ok(res)=>{res}
Err(_)=>{return Err("Error at loading table")}
},
1)}
Some(page) => {
let query_res = match column_name.as_str() {
"contract_id" => PcBind::sort_by_column(query, pc_bind::contract_id, order),
"project_id" => PcBind::sort_by_column(query, pc_bind::project_id, order),
"head_id" => PcBind::sort_by_column(query, pc_bind::group_id, order),
"group_id" => PcBind::sort_by_column(query, pc_bind::head_id, order),
"project_start" => PcBind::sort_by_column(query, pc_bind::project_start, order),
"project_end" => PcBind::sort_by_column(query, pc_bind::project_end, order),
"eq_list_id" => PcBind::sort_by_column(query, pc_bind::eq_list_id, order),
_ => PcBind::sort_by_column(query, pc_bind::contract_id, order)
};
let res =match query_res.paginate(page).load::<(PcBind, i64)>(connection) {
Ok(sub_res)=>{sub_res},
Err(_)=>{return Err("Error at loading page")},
};
let total = res.get(0).map(|x| x.1).unwrap_or(0);
let values = res.into_iter().map(|x| x.0).collect();
let total_pages = (total as f64 / 10 as f64).ceil() as i64;
(values, total_pages)
}
};
Ok((values,total_pages))
}
} |
// This file is part of Substrate.
// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use futures::{
channel::{mpsc, oneshot},
compat::*,
future::{ok, ready, select},
prelude::*,
};
use futures01::sync::mpsc as mpsc01;
use libp2p_wasm_ext::{ffi, ExtTransport};
use log::{debug, info};
use sc_chain_spec::Extension;
use sc_network::config::TransportConfig;
use sc_service::{
config::{DatabaseConfig, KeystoreConfig, NetworkConfiguration},
Configuration, GenericChainSpec, Role, RpcHandlers, RpcSession, RuntimeGenesis, TaskManager,
};
use std::pin::Pin;
use wasm_bindgen::prelude::*;
pub use console_error_panic_hook::set_once as set_console_error_panic_hook;
pub use console_log::init_with_level as init_console_log;
/// Create a service configuration from a chain spec.
///
/// This configuration contains good defaults for a browser light client.
pub async fn browser_configuration<G, E>(
chain_spec: GenericChainSpec<G, E>,
) -> Result<Configuration, Box<dyn std::error::Error>>
where
G: RuntimeGenesis + 'static,
E: Extension + 'static + Send,
{
let name = chain_spec.name().to_string();
let transport = ExtTransport::new(ffi::websocket_transport());
let mut network = NetworkConfiguration::new(
format!("{} (Browser)", name),
"unknown",
Default::default(),
None,
);
network.boot_nodes = chain_spec.boot_nodes().to_vec();
network.transport = TransportConfig::Normal {
wasm_external_transport: Some(transport.clone()),
allow_private_ipv4: true,
enable_mdns: false,
use_yamux_flow_control: true,
};
let config = Configuration {
network,
telemetry_endpoints: chain_spec.telemetry_endpoints().clone(),
chain_spec: Box::new(chain_spec),
task_executor: (|fut, _| {
wasm_bindgen_futures::spawn_local(fut);
async {}
})
.into(),
telemetry_external_transport: Some(transport),
role: Role::Light,
database: {
info!("Opening Indexed DB database '{}'...", name);
let db = kvdb_web::Database::open(name, 10).await?;
DatabaseConfig::Custom(sp_database::as_database(db))
},
keystore: KeystoreConfig::InMemory,
default_heap_pages: Default::default(),
dev_key_seed: Default::default(),
disable_grandpa: Default::default(),
execution_strategies: Default::default(),
force_authoring: Default::default(),
impl_name: String::from("parity-substrate"),
impl_version: String::from("0.0.0"),
offchain_worker: Default::default(),
prometheus_config: Default::default(),
pruning: Default::default(),
rpc_cors: Default::default(),
rpc_http: Default::default(),
rpc_ipc: Default::default(),
rpc_ws: Default::default(),
rpc_ws_max_connections: Default::default(),
rpc_methods: Default::default(),
state_cache_child_ratio: Default::default(),
state_cache_size: Default::default(),
tracing_receiver: Default::default(),
tracing_targets: Default::default(),
transaction_pool: Default::default(),
wasm_method: Default::default(),
max_runtime_instances: 8,
announce_block: true,
base_path: None,
informant_output_format: sc_informant::OutputFormat {
enable_color: false,
prefix: String::new(),
},
};
Ok(config)
}
/// A running client.
#[wasm_bindgen]
pub struct Client {
rpc_send_tx: mpsc::UnboundedSender<RpcMessage>,
}
struct RpcMessage {
rpc_json: String,
session: RpcSession,
send_back: oneshot::Sender<Pin<Box<dyn futures::Future<Output = Option<String>> + Send>>>,
}
/// Create a Client object that connects to a service.
pub fn start_client(mut task_manager: TaskManager, rpc_handlers: RpcHandlers) -> Client {
// We dispatch a background task responsible for processing the service.
//
// The main action performed by the code below consists in polling the service with
// `service.poll()`.
// The rest consists in handling RPC requests.
let (rpc_send_tx, rpc_send_rx) = mpsc::unbounded::<RpcMessage>();
wasm_bindgen_futures::spawn_local(
select(
rpc_send_rx.for_each(move |message| {
let fut = rpc_handlers.rpc_query(&message.session, &message.rpc_json);
let _ = message.send_back.send(fut);
ready(())
}),
Box::pin(async move {
let _ = task_manager.future().await;
}),
)
.map(drop),
);
Client { rpc_send_tx }
}
#[wasm_bindgen]
impl Client {
/// Allows starting an RPC request. Returns a `Promise` containing the result of that request.
#[wasm_bindgen(js_name = "rpcSend")]
pub fn rpc_send(&mut self, rpc: &str) -> js_sys::Promise {
let rpc_session = RpcSession::new(mpsc01::channel(1).0);
let (tx, rx) = oneshot::channel();
let _ = self.rpc_send_tx.unbounded_send(RpcMessage {
rpc_json: rpc.to_owned(),
session: rpc_session,
send_back: tx,
});
wasm_bindgen_futures::future_to_promise(async {
match rx.await {
Ok(fut) => fut.await.map(|s| JsValue::from_str(&s)).ok_or_else(|| JsValue::NULL),
Err(_) => Err(JsValue::NULL),
}
})
}
/// Subscribes to an RPC pubsub endpoint.
#[wasm_bindgen(js_name = "rpcSubscribe")]
pub fn rpc_subscribe(&mut self, rpc: &str, callback: js_sys::Function) {
let (tx, rx) = mpsc01::channel(4);
let rpc_session = RpcSession::new(tx);
let (fut_tx, fut_rx) = oneshot::channel();
let _ = self.rpc_send_tx.unbounded_send(RpcMessage {
rpc_json: rpc.to_owned(),
session: rpc_session.clone(),
send_back: fut_tx,
});
wasm_bindgen_futures::spawn_local(async {
if let Ok(fut) = fut_rx.await {
fut.await;
}
});
wasm_bindgen_futures::spawn_local(async move {
let _ = rx
.compat()
.try_for_each(|s| {
let _ = callback.call1(&callback, &JsValue::from_str(&s));
ok(())
})
.await;
// We need to keep `rpc_session` alive.
debug!("RPC subscription has ended");
drop(rpc_session);
});
}
}
|
use super::blockid::BlockId;
use super::filemanager::FileMgr;
use super::logmanager::LogMgr;
use super::page::Page;
use std::cell::RefCell;
use std::fmt;
use std::sync::Arc;
use anyhow::Result;
#[derive(Debug)]
enum BufferError {
BlockNotFound,
}
impl std::error::Error for BufferError {}
impl fmt::Display for BufferError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
BufferError::BlockNotFound => {
write!(f, "block not found")
}
}
}
}
pub struct Buffer {
fm: Arc<RefCell<FileMgr>>,
lm: Arc<RefCell<LogMgr>>,
contents: Page,
blk: Option<BlockId>, // reference to the block assigned to its page
pins: u64, // the number of times the page is pinned
txnum: i32, // an integer indicating if the page has been modified. The integer indentifies the transaction that make the change
lsn: i32, // log information. if the page has been modified, the buffer holds the LSN of the most recent log record.
}
impl Buffer {
pub fn new(fm: Arc<RefCell<FileMgr>>, lm: Arc<RefCell<LogMgr>>) -> Buffer {
let blksize = fm.borrow().blocksize() as usize;
Buffer {
fm,
lm,
contents: Page::new_from_size(blksize),
blk: None,
pins: 0,
txnum: -1,
lsn: -1,
}
}
pub fn contents(&mut self) -> &mut Page {
&mut self.contents
}
pub fn block(&self) -> Option<&BlockId> {
self.blk.as_ref()
}
pub fn set_modified(&mut self, txnum: i32, lsn: i32) {
self.txnum = txnum;
if lsn >= 0 {
self.lsn = lsn;
}
}
pub fn is_pinned(&self) -> bool {
self.pins > 0
}
pub fn modifying_tx(&self) -> i32 {
self.txnum
}
// associate the buffer with the specific block, reading its content from disk
pub fn assign_to_block(&mut self, b: BlockId) -> Result<()> {
self.flush()?;
self.fm.borrow_mut().read(&b, &mut self.contents)?;
self.blk = Some(b);
self.pins = 0;
Ok(())
}
// ensure the buffer's assigned disk block has the same values as its page
pub fn flush(&mut self) -> Result<()> {
// page has been changed
if self.txnum >= 0 {
self.lm.borrow_mut().flush_from_lsn(self.lsn as u64)?;
if let Some(br) = self.blk.as_ref() {
self.fm.borrow_mut().write(br, &mut self.contents)?;
// need not flush again
self.txnum = -1;
} else {
return Err(From::from(BufferError::BlockNotFound));
}
}
Ok(())
}
pub fn pin(&mut self) {
self.pins += 1;
}
pub fn unpin(&mut self) {
self.pins -= 1;
}
}
|
#![feature(test)]
extern crate fnv;
extern crate hashbrown;
extern crate test;
#[cfg(test)]
use fnv::FnvHashSet;
#[cfg(test)]
use hashbrown::HashSet as HashbrownSet;
#[cfg(test)]
use std::collections::BTreeSet;
#[cfg(test)]
use std::collections::HashSet;
macro_rules! bench_set {
($name: ident, $type: ident, $size: expr) => {
#[bench]
pub fn $name(b: &mut test::Bencher) {
// setup
let s: $type<i32> = (0..$size).collect();
assert_eq!(s.len(), $size);
// measure
b.iter(|| {
let set = test::black_box(&s);
let elt = *set.iter().next().unwrap();
test::black_box(elt);
})
}
};
}
bench_set!(peek_btreeset_1, BTreeSet, 1);
bench_set!(peek_btreeset_100, BTreeSet, 100);
bench_set!(peek_btreeset_10k, BTreeSet, 10_000);
bench_set!(peek_btreeset_1kk, BTreeSet, 1_000_000);
bench_set!(peek_hashset_1, HashSet, 1);
bench_set!(peek_hashset_100, HashSet, 100);
bench_set!(peek_hashset_10k, HashSet, 10_000);
bench_set!(peek_hashset_1kk, HashSet, 1_000_000);
bench_set!(peek_fnvhashtreeset_1, FnvHashSet, 1);
bench_set!(peek_fnvhashtreeset_100, FnvHashSet, 100);
bench_set!(peek_fnvhashtreeset_10k, FnvHashSet, 10_000);
bench_set!(peek_fnvhashtreeset_1kk, FnvHashSet, 1_000_000);
bench_set!(peek_hashbrownset_1, HashbrownSet, 1);
bench_set!(peek_hashbrownset_100, HashbrownSet, 100);
bench_set!(peek_hashbrownset_10k, HashbrownSet, 10_000);
bench_set!(peek_hashbrownset_1kk, HashbrownSet, 1_000_000);
|
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
#![cfg(feature = "serde_tests")]
use crypto::Signature;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct SignatureVector {
#[serde(alias = "Type")]
sig_type: u8,
#[serde(alias = "Data")]
data: String,
}
impl From<SignatureVector> for Signature {
fn from(v: SignatureVector) -> Self {
match v.sig_type {
1 => Signature::new_secp256k1(base64::decode(&v.data).unwrap()),
2 => Signature::new_bls(base64::decode(&v.data).unwrap()),
_ => panic!("unsupported signature type"),
}
}
}
|
use hlua::{self, Lua};
use std::fs::File;
use std::io::Read;
pub fn hello_world() {
let mut script = String::new();
File::open("scripts/hello.lua").unwrap()
.read_to_string(&mut script).unwrap();
let mut lua = Lua::new();
lua.openlibs(); // Load standard lua libraries
lua.set("log", hlua::function1(log)); // Add log capability
lua.execute(&script).unwrap()
}
fn log(text: String) {
println!("{}", text);
}
|
//! This sub-mod provides some facilities about memory performance profiling.
//! # Memory usage of current process
//! There's a platform-related function called `get_process_memory_info` available on MacOS and Windows.
//! # Memory usage of ALL Rust allocations
//! We provide a `CountingAllocator` that wraps the system allocator but tracks the bytes used by rust allocations.
//! This crate DOES NOT replace the global allocator by default. You need to make it as a `global_allocator` or enable the `allocation_counter` feature.
//! ```ignore
//! #[global_allocator]
//! static _COUNTER: perf_monitor::mem::CountingAllocator = perf_monitor:mem::CountingAllocator;
//! ```
mod allocation_counter;
pub use allocation_counter::CountingAllocator;
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod process_memory_info;
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub use process_memory_info::{get_process_memory_info, ProcessMemoryInfo, ProcessMemoryInfoError};
#[cfg(target_os = "macos")]
#[cfg_attr(doc, doc(cfg(macos)))]
pub mod apple;
|
use num_bigint::{BigUint, RandBigInt};
use num_integer::Integer;
use num_traits::{One, Zero};
use once_cell::sync::Lazy;
use rand::{CryptoRng, Rng};
static DH_GENERATOR: Lazy<BigUint> = Lazy::new(|| BigUint::from_bytes_be(&[0x02]));
static DH_PRIME: Lazy<BigUint> = Lazy::new(|| {
BigUint::from_bytes_be(&[
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2,
0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67,
0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e,
0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d,
0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5,
0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x3a, 0x36, 0x20, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
])
});
fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
let mut base = base.clone();
let mut exp = exp.clone();
let mut result: BigUint = One::one();
while !exp.is_zero() {
if exp.is_odd() {
result = (result * &base) % modulus;
}
exp >>= 1;
base = (&base * &base) % modulus;
}
result
}
pub struct DhLocalKeys {
private_key: BigUint,
public_key: BigUint,
}
impl DhLocalKeys {
pub fn random<R: Rng + CryptoRng>(rng: &mut R) -> DhLocalKeys {
let private_key = rng.gen_biguint(95 * 8);
let public_key = powm(&DH_GENERATOR, &private_key, &DH_PRIME);
DhLocalKeys {
private_key,
public_key,
}
}
pub fn public_key(&self) -> Vec<u8> {
self.public_key.to_bytes_be()
}
pub fn shared_secret(&self, remote_key: &[u8]) -> Vec<u8> {
let shared_key = powm(
&BigUint::from_bytes_be(remote_key),
&self.private_key,
&DH_PRIME,
);
shared_key.to_bytes_be()
}
}
|
use log::Level;
pub fn output_log() {
// env_logger::init();
log::debug!("{}", "this is a log msg only shown on debug mode");
eprintln!("this is a log from std lib");
log::error!("{}", "this is a log msg on staout");
use env_logger::{Builder, Target};
Builder::new().target(Target::Stdout).init();
log::debug!("ssssssss");
}
pub fn customed_logger() {
use log::{Metadata, Record};
struct ConsoleLogger;
impl log::Log for ConsoleLogger {
// Determines if a log message with the specified metadata would be logged.
fn enabled(&self, metadata: &Metadata) -> bool {
println!(
"{} ? {} => {}",
metadata.level(),
Level::Info,
metadata.level() <= Level::Info
);
metadata.level() <= Level::Info
}
// Logs the `Record`.
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
println!("Rust says: {} - {}", record.level(), record.args());
}
}
// Flushes any buffered records.
fn flush(&self) {}
}
static CONSOLE_LOGGER: ConsoleLogger = ConsoleLogger;
log::set_logger(&CONSOLE_LOGGER).unwrap();
log::set_max_level(log::LevelFilter::Info);
log::debug!("debug");
log::warn!("warn");
log::error!("error");
log::info!("info");
log::trace!("trace");
}
pub fn log_to_sys() {
// use syslog::
}
pub fn customed_env() {
use env_logger::Builder;
use std::env;
Builder::new()
// .parse_env(env::var("MY_APP_LOG").unwrap())
.init();
for argument in env::args() {
println!("=================={}", argument);
}
}
pub fn env_test() {
use std::env;
println!("{:?}", env::current_dir());
for argument in env::args() {
println!("=================={}", argument);
}
for argument in env::args_os() {
println!("*******************8{:?}", argument);
}
}
use error_chain::error_chain;
error_chain! {
foreign_links {
Io(std::io::Error);
SetLogger(log::SetLoggerError);
LogConfig(log4rs::config::runtime::ConfigErrors);
}
}
pub fn customed_log_path() -> Result<()> {
use log::LevelFilter;
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Root};
use log4rs::encode::pattern::PatternEncoder;
let logfile = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new("{l} - {m}\n")))
.build("log/output.log")?;
let config = Config::builder()
.appender(Appender::builder().build("logfile", Box::new(logfile)))
.build(Root::builder().appender("logfile").build(LevelFilter::Info))?;
log4rs::init_config(config)?;
log::info!("Hello, world!");
log::debug!("debug");
log::warn!("warn");
log::error!("error");
log::info!("info");
log::trace!("trace");
Ok(())
}
#[test]
fn test() {
// output_log();
// customed_logger();
// env_test();
// customed_env();
customed_log_path();
}
|
#[doc = "Reader of register DDRCTRL_PCCFG"]
pub type R = crate::R<u32, super::DDRCTRL_PCCFG>;
#[doc = "Writer for register DDRCTRL_PCCFG"]
pub type W = crate::W<u32, super::DDRCTRL_PCCFG>;
#[doc = "Register DDRCTRL_PCCFG `reset()`'s with value 0"]
impl crate::ResetValue for super::DDRCTRL_PCCFG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `GO2CRITICAL_EN`"]
pub type GO2CRITICAL_EN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `GO2CRITICAL_EN`"]
pub struct GO2CRITICAL_EN_W<'a> {
w: &'a mut W,
}
impl<'a> GO2CRITICAL_EN_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 `PAGEMATCH_LIMIT`"]
pub type PAGEMATCH_LIMIT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PAGEMATCH_LIMIT`"]
pub struct PAGEMATCH_LIMIT_W<'a> {
w: &'a mut W,
}
impl<'a> PAGEMATCH_LIMIT_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 `BL_EXP_MODE`"]
pub type BL_EXP_MODE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `BL_EXP_MODE`"]
pub struct BL_EXP_MODE_W<'a> {
w: &'a mut W,
}
impl<'a> BL_EXP_MODE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
impl R {
#[doc = "Bit 0 - GO2CRITICAL_EN"]
#[inline(always)]
pub fn go2critical_en(&self) -> GO2CRITICAL_EN_R {
GO2CRITICAL_EN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 4 - PAGEMATCH_LIMIT"]
#[inline(always)]
pub fn pagematch_limit(&self) -> PAGEMATCH_LIMIT_R {
PAGEMATCH_LIMIT_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 8 - BL_EXP_MODE"]
#[inline(always)]
pub fn bl_exp_mode(&self) -> BL_EXP_MODE_R {
BL_EXP_MODE_R::new(((self.bits >> 8) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - GO2CRITICAL_EN"]
#[inline(always)]
pub fn go2critical_en(&mut self) -> GO2CRITICAL_EN_W {
GO2CRITICAL_EN_W { w: self }
}
#[doc = "Bit 4 - PAGEMATCH_LIMIT"]
#[inline(always)]
pub fn pagematch_limit(&mut self) -> PAGEMATCH_LIMIT_W {
PAGEMATCH_LIMIT_W { w: self }
}
#[doc = "Bit 8 - BL_EXP_MODE"]
#[inline(always)]
pub fn bl_exp_mode(&mut self) -> BL_EXP_MODE_W {
BL_EXP_MODE_W { w: self }
}
}
|
//! Tests auto-converted from "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex"
#[allow(unused)]
use super::rsass;
// From "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex/01_inline.hrx"
#[test]
fn t01_inline() {
assert_eq!(
rsass(
".result {\
\n output: gamma, \"\'\"delta\"\'\";\
\n output: #{gamma, \"\'\"delta\"\'\"};\
\n output: \"[#{gamma, \"\'\"delta\"\'\"}]\";\
\n output: \"#{gamma, \"\'\"delta\"\'\"}\";\
\n output: \'#{gamma, \"\'\"delta\"\'\"}\';\
\n output: \"[\'#{gamma, \"\'\"delta\"\'\"}\']\";\
\n}\
\n"
)
.unwrap(),
".result {\
\n output: gamma, \"\'\" delta \"\'\";\
\n output: gamma, \' delta \';\
\n output: \"[gamma, \' delta \']\";\
\n output: \"gamma, \' delta \'\";\
\n output: \"gamma, \' delta \'\";\
\n output: \"[\'gamma, \' delta \'\']\";\
\n}\
\n"
);
}
// From "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex/02_variable.hrx"
#[test]
fn t02_variable() {
assert_eq!(
rsass(
"$input: gamma, \"\'\"delta\"\'\";\
\n.result {\
\n output: $input;\
\n output: #{$input};\
\n output: \"[#{$input}]\";\
\n output: \"#{$input}\";\
\n output: \'#{$input}\';\
\n output: \"[\'#{$input}\']\";\
\n}\
\n"
)
.unwrap(),
".result {\
\n output: gamma, \"\'\" delta \"\'\";\
\n output: gamma, \' delta \';\
\n output: \"[gamma, \' delta \']\";\
\n output: \"gamma, \' delta \'\";\
\n output: \"gamma, \' delta \'\";\
\n output: \"[\'gamma, \' delta \'\']\";\
\n}\
\n"
);
}
// From "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex/03_inline_double.hrx"
#[test]
fn t03_inline_double() {
assert_eq!(
rsass(
".result {\
\n output: #{#{gamma, \"\'\"delta\"\'\"}};\
\n output: #{\"[#{gamma, \"\'\"delta\"\'\"}]\"};\
\n output: #{\"#{gamma, \"\'\"delta\"\'\"}\"};\
\n output: #{\'#{gamma, \"\'\"delta\"\'\"}\'};\
\n output: #{\"[\'#{gamma, \"\'\"delta\"\'\"}\']\"};\
\n}\
\n"
)
.unwrap(),
".result {\
\n output: gamma, \' delta \';\
\n output: [gamma, \' delta \'];\
\n output: gamma, \' delta \';\
\n output: gamma, \' delta \';\
\n output: [\'gamma, \' delta \'\'];\
\n}\
\n"
);
}
// From "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex/04_variable_double.hrx"
#[test]
fn t04_variable_double() {
assert_eq!(
rsass(
"$input: gamma, \"\'\"delta\"\'\";\
\n.result {\
\n output: #{#{$input}};\
\n output: #{\"[#{$input}]\"};\
\n output: #{\"#{$input}\"};\
\n output: #{\'#{$input}\'};\
\n output: #{\"[\'#{$input}\']\"};\
\n}\
\n"
)
.unwrap(),
".result {\
\n output: gamma, \' delta \';\
\n output: [gamma, \' delta \'];\
\n output: gamma, \' delta \';\
\n output: gamma, \' delta \';\
\n output: [\'gamma, \' delta \'\'];\
\n}\
\n"
);
}
// From "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex/05_variable_quoted_double.hrx"
#[test]
fn t05_variable_quoted_double() {
assert_eq!(
rsass(
"$input: gamma, \"\'\"delta\"\'\";\
\n.result {\
\n dquoted: \"#{#{$input}}\";\
\n dquoted: \"#{\"[#{$input}]\"}\";\
\n dquoted: \"#{\"#{$input}\"}\";\
\n dquoted: \"#{\'#{$input}\'}\";\
\n dquoted: \"#{\"[\'#{$input}\']\"}\";\
\n squoted: \'#{#{$input}}\';\
\n squoted: \'#{\"[#{$input}]\"}\';\
\n squoted: \'#{\"#{$input}\"}\';\
\n squoted: \'#{\'#{$input}\'}\';\
\n squoted: \'#{\"[\'#{$input}\']\"}\';\
\n}\
\n"
)
.unwrap(),
".result {\
\n dquoted: \"gamma, \' delta \'\";\
\n dquoted: \"[gamma, \' delta \']\";\
\n dquoted: \"gamma, \' delta \'\";\
\n dquoted: \"gamma, \' delta \'\";\
\n dquoted: \"[\'gamma, \' delta \'\']\";\
\n squoted: \"gamma, \' delta \'\";\
\n squoted: \"[gamma, \' delta \']\";\
\n squoted: \"gamma, \' delta \'\";\
\n squoted: \"gamma, \' delta \'\";\
\n squoted: \"[\'gamma, \' delta \'\']\";\
\n}\
\n"
);
}
// From "sass-spec/spec/non_conformant/parser/interpolate/07_comma_list_complex/06_escape_interpolation.hrx"
#[test]
fn t06_escape_interpolation() {
assert_eq!(
rsass(
"$input: gamma, \"\'\"delta\"\'\";\
\n.result {\
\n output: \"[\\#{gamma, \"\'\"delta\"\'\"}]\";\
\n output: \"\\#{gamma, \"\'\"delta\"\'\"}\";\
\n output: \'\\#{gamma, \"\'\"delta\"\'\"}\';\
\n output: \"[\'\\#{gamma, \"\'\"delta\"\'\"}\']\";\
\n}\
\n"
)
.unwrap(),
".result {\
\n output: \"[#{gamma, \" \'\"delta\"\' \"}]\";\
\n output: \"#{gamma, \" \'\"delta\"\' \"}\";\
\n output: \'#{gamma, \"\' \"delta\" \'\"}\';\
\n output: \"[\'#{gamma, \" \'\"delta\"\' \"}\']\";\
\n}\
\n"
);
}
|
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_json;
pub mod utils;
pub mod api;
use utils::block::Block;
use utils::{Conf, BotUser};
use rocket_contrib::json::{Json};
use rocket_contrib::serve::{StaticFiles, Options};
use rocket::config::{Config, Environment};
use rocket::State;
use log::{info, warn};
use rocket::request::Form;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct BotMessenger {
conf: Conf,
blocks: Vec<Block>,
block_default: Block,
static_file: Option<String>,
}
impl Drop for BotMessenger {
fn drop(&mut self) {
println!("> Dropping BotMessenger");
}
}
impl BotMessenger {
// New BotMessenger struct
pub fn new() -> Self {
BotMessenger {
conf: Conf::default(),
blocks: Vec::new(),
block_default: Block::default(),
static_file: None,
}
}
// Add conf struct
pub fn block(mut self, value: Block) -> Self {
let mut block = value;
block.set_token(self.get_conf().get_token_fb_page());
self.add_block(block);
self
}
pub fn block_default(mut self, value: Block) -> Self {
let mut block = value;
block.set_token(self.get_conf().get_token_fb_page());
self.block_default = block;
self
}
// Add user connection
pub fn add_user(&mut self, user: BotUser) -> &mut Self {
let block_match = self.blocks.iter_mut().find(|x| {
x.get_name() == user.get_message().message()
});
if let Some(i) = block_match {
info!("Message match with block");
i.remove_child(&user);
i.root(&user);
}
else {
match self.blocks.iter_mut().enumerate().find(|x| {
x.1.find(&user)})
{
Some(u) => {
info!("Find a user match in block");
u.1.root(&user);
},
None => {
warn!("Don't match with any of blocks");
self.block_default.root(&user);
}
}
}
self
}
pub fn with_conf(mut self, conf: Conf) -> Self {
self.conf = conf;
self
}
pub fn with_token_fb(mut self, token: &str) -> Self {
self.conf.set_token_fb_page(token);
self.blocks.iter_mut().for_each(|x| x.set_token(token));
self.block_default.set_token(token);
self
}
pub fn with_token_wh(mut self, token: &str) -> Self {
self.conf.set_token_webhook(token);
self
}
pub fn with_port(mut self, port: u16) -> Self {
self.conf.set_port(port);
self
}
pub fn with_static_file(mut self, file: &str) -> Self{
self.static_file = Some(file.to_string());
self
}
pub fn rooting_user(&self, user: &BotUser) {
}
// Launch server rocket
pub fn launch(&self) {
//let bot = self.clone();
let config = Config::build(Environment::Development)
.address(self.get_conf().get_ip())
.port(*self.get_conf().get_port())
.workers(*self.get_conf().get_workers())
.finalize();
let selfy = Arc::new(Mutex::new(self.clone()));
//println!("Token {}",selfy.get_conf().get_token_fb_page());
match config {
Ok(e) => {
let route = format!("/{}",self.get_conf().get_uri());
let mut rocket = rocket::custom(e).manage(selfy).mount(&route,routes![root_connection, root_message])
.mount("/", routes![get_basic]);
if self.static_file.is_some() {
let s = self.static_file.clone().unwrap();
rocket = rocket.mount("/static", StaticFiles::from(s.as_str()));
}
rocket.launch();
}
Err(e) => panic!("Failed init config : {}", e)
}
}
pub fn get_conf(&self) -> &Conf {
&self.conf
}
pub fn get_conf_mut(&mut self) -> &mut Conf {
&mut self.conf
}
pub fn add_block(&mut self, block: Block){
self.blocks.push(block);
}
}
#[derive(FromForm)]
struct FbForm {
#[form(field = "hub.verify_token")]
verify_token: String,
#[form(field = "hub.challenge")]
challenge: String,
#[form(field = "hub.mode")]
mode: String,
}
// routes
#[get("/?<hub..>")]
fn root_connection(bot: State<Arc<Mutex<BotMessenger>>>, hub: Form<FbForm>) -> String {
let bot = bot.clone();
let bot = bot.lock().unwrap();
if hub.mode == "subscribe" && hub.verify_token == bot.get_conf().get_token_webhook() {
let s = hub.challenge.clone();
s
}
else {
"Sorry I don't understand".to_string()
}
}
#[post("/" ,format = "json", data = "<user>")]
fn root_message(bot: State<Arc<Mutex<BotMessenger>>> ,user: Json<BotUser>) -> &'static str {
let bot = bot.clone();
let bot = &mut bot.lock();
if let Ok(b) = bot {
info!("New user: {}",*user);
b.add_user(user.clone());
"ok"
}
else {
"Don't understand ?"
}
}
#[get("/")]
fn get_basic() -> &'static str {
"ok"
}
#[cfg(test)]
mod tests {
use crate::BotMessenger;
use crate::utils;
use crate::api;
use utils::block::Block;
use utils::block::CartBox;
use api::card::Card;
use api::card::DefaultAction;
use api::card::CardGeneric;
use api::card::CardButtons;
use api::button::Button;
#[test]
fn it_works() {
BotMessenger::new()
.block_default(Block::new("default")
.cartBox(CartBox::new()
.text("Sorry I don't understand 🐻")))
.block(Block::new("Hello")
.cartBox(CartBox::new()
.text("Hello new user"))
.cartBox(CartBox::new()
.text("Hello new user 2"))
.cartBox(CartBox::new()
.text("Hello new user 3"))
.cartBox(CartBox::new()
.text("It's a new day")
.button_postback("Push", "Hello"))
.cartBox(CartBox::new()
.card(CardGeneric::new("Hello")
.button(Button::new_button_pb("Welcom back Mr potter", "Hello"))
.image("https://images.ladepeche.fr/api/v1/images/view/5c34fb833e454650457f60ce/large/image.jpg")
.subtitle("Bouyah"))
.card(CardGeneric::new("Hello")
.button(Button::new_button_pb("Welcom back Mr potter", "Hello"))
.image("https://images.ladepeche.fr/api/v1/images/view/5c34fb833e454650457f60ce/large/image.jpg")
.subtitle("Bouyah")))
.cartBox(CartBox::new()
.card(CardButtons::new("Can you choose !")
.button(Button::new_button_url("wake me up", "www.google.fr"))
.button(Button::new_button_pb("not me !", "Hello")))))
.block(Block::new("#Start")
.cartBox(CartBox::new()
.text("New start user")))
.with_token_fb(&std::env::var("TOKEN_FB").unwrap())
.with_token_wh("MamaGuriba")
.launch();
}
}
|
use crate::{
datastructures::{
AtomSpatial,
AtomSpatial::{PointsTo, LS},
Entailment, Expr,
Expr::{Nil, Var},
Formula, Op,
Op::{AtomEq, AtomNeq},
Pure,
Pure::{And, True},
Rule, Spatial,
Spatial::{Emp, SepConj},
},
misc::find_and_remove,
};
/// Π[E/x] | Σ[E/x] |- Π'[E/x] | Σ'[E/x] ==> Π ∧ x=E | Σ |- Π' | Σ'
pub struct Substitution;
impl Substitution {
fn subst_impl(subst: &(String, Expr), x: &Expr) -> Expr {
match x {
Var(v) => {
if v.0 == subst.0 {
subst.1.clone()
} else {
Var(v.clone())
}
}
Nil => Nil,
}
}
fn subst_pure(subst: &(String, Expr), p: &mut Pure) -> Pure {
match p {
And(pure_sub) => {
let pure_vec: Vec<Op> = pure_sub
.iter_mut()
.map(|x| match x {
AtomEq(l, r) => {
AtomEq(Self::subst_impl(&subst, l), Self::subst_impl(&subst, r))
}
AtomNeq(l, r) => {
AtomNeq(Self::subst_impl(&subst, l), Self::subst_impl(&subst, r))
}
})
.collect();
And(pure_vec)
}
True => True,
}
}
fn subst_atom_spatial(subst: &(String, Expr), sp: &mut AtomSpatial) -> AtomSpatial {
match sp {
PointsTo(v, e) => PointsTo(Self::subst_impl(subst, v), Self::subst_impl(subst, e)),
LS(v, e) => LS(Self::subst_impl(subst, v), Self::subst_impl(subst, e)),
}
}
fn subst_spatial(subst: &(String, Expr), sp: &mut Spatial) -> Spatial {
match sp {
SepConj(atom_spatials) => SepConj(
atom_spatials
.iter_mut()
.map(move |asp| Self::subst_atom_spatial(subst, asp))
.collect::<Vec<AtomSpatial>>(),
),
Emp => Emp,
}
}
fn substitute(subst: (String, Expr), goal: Entailment) -> Entailment {
let (mut antecedent, mut consequent) = goal.destroy();
let new_pure_ant = Self::subst_pure(&subst, antecedent.get_pure_mut());
let new_spatial_ant = Self::subst_spatial(&subst, antecedent.get_spatial_mut());
let new_pure_cons = Self::subst_pure(&subst, consequent.get_pure_mut());
let new_spatial_cons = Self::subst_spatial(&subst, consequent.get_spatial_mut());
Entailment {
antecedent: Formula(new_pure_ant, new_spatial_ant),
consequent: Formula(new_pure_cons, new_spatial_cons),
}
}
}
impl Rule for Substitution {
fn predicate(&self, _goal: &Entailment) -> bool {
true
}
fn premisses(&self, mut goal: Entailment) -> Option<Vec<Entailment>> {
if let And(pure_sub) = goal.antecedent.get_pure_mut() {
if let Some(elem) = find_and_remove(pure_sub, move |x| x.is_eq()) {
let mut subst = ("".to_string(), Nil);
if let AtomEq(l, r) = elem {
if let Var(v) = l {
subst = (v.0, r.clone());
} else if let Var(v) = r {
subst = (v.0, l.clone());
}
return Some(vec![Self::substitute(subst, goal)]);
}
}
}
None
}
}
#[cfg(test)]
mod test {
use super::Substitution;
use crate::datastructures::{
AtomSpatial::{PointsTo, LS},
Entailment, Expr,
Expr::Nil,
Formula,
Op::{AtomEq, AtomNeq},
Pure::And,
Rule,
Spatial::SepConj,
};
#[test]
pub fn test_substitute() -> Result<(), String> {
let goal = Entailment {
antecedent: Formula(
And(vec![
AtomEq(Expr::new_var("x"), Nil),
AtomNeq(Expr::new_var("y"), Expr::new_var("x")),
]),
SepConj(vec![PointsTo(Expr::new_var("y"), Expr::new_var("x"))]),
),
consequent: Formula(
And(vec![AtomNeq(Expr::new_var("z"), Expr::new_var("x"))]),
SepConj(vec![LS(Expr::new_var("x"), Nil)]),
),
};
let goal_expected = Entailment {
antecedent: Formula(
And(vec![AtomNeq(Expr::new_var("y"), Nil)]),
SepConj(vec![PointsTo(Expr::new_var("y"), Nil)]),
),
consequent: Formula(
And(vec![AtomNeq(Expr::new_var("z"), Nil)]),
SepConj(vec![LS(Nil, Nil)]),
),
};
let premisses = Substitution.premisses(goal);
if let Some(prem) = premisses {
assert_eq!(1, prem.len());
assert_eq!(goal_expected, prem[0]);
Ok(())
} else {
Err("Expected third test to succeed!".to_string())
}
}
}
|
use std::any::Any;
use std::ffi::CString;
use std::fs::File;
use std::os::raw::{c_char, c_int};
use rustc::middle::cstore::EncodedMetadata;
use rustc::mir::mono::{Linkage as RLinkage, Visibility};
use rustc::session::config::{DebugInfo, OutputType};
use rustc_codegen_ssa::back::linker::LinkerInfo;
use rustc_codegen_ssa::CrateInfo;
use cranelift_faerie::*;
use crate::prelude::*;
pub fn codegen_crate(
tcx: TyCtxt<'_>,
metadata: EncodedMetadata,
need_metadata_module: bool,
) -> Box<dyn Any> {
tcx.sess.abort_if_errors();
let mut log = if cfg!(debug_assertions) {
Some(File::create(concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/log.txt")).unwrap())
} else {
None
};
if std::env::var("SHOULD_RUN").is_ok()
&& tcx.sess.crate_types.get().contains(&CrateType::Executable)
{
#[cfg(not(target_arch = "wasm32"))]
let _: ! = run_jit(tcx, &mut log);
#[cfg(target_arch = "wasm32")]
panic!("jit not supported on wasm");
}
run_aot(tcx, metadata, need_metadata_module, &mut log)
}
#[cfg(not(target_arch = "wasm32"))]
fn run_jit(tcx: TyCtxt<'_>, log: &mut Option<File>) -> ! {
use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
let imported_symbols = load_imported_symbols_for_jit(tcx);
let mut jit_builder = SimpleJITBuilder::with_isa(
crate::build_isa(tcx.sess, false),
cranelift_module::default_libcall_names(),
);
jit_builder.symbols(imported_symbols);
let mut jit_module: Module<SimpleJITBackend> = Module::new(jit_builder);
assert_eq!(pointer_ty(tcx), jit_module.target_config().pointer_type());
let sig = Signature {
params: vec![
AbiParam::new(jit_module.target_config().pointer_type()),
AbiParam::new(jit_module.target_config().pointer_type()),
],
returns: vec![AbiParam::new(
jit_module.target_config().pointer_type(), /*isize*/
)],
call_conv: CallConv::SystemV,
};
let main_func_id = jit_module
.declare_function("main", Linkage::Import, &sig)
.unwrap();
codegen_cgus(tcx, &mut jit_module, &mut None, log);
crate::allocator::codegen(tcx.sess, &mut jit_module);
jit_module.finalize_definitions();
tcx.sess.abort_if_errors();
let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
unsafe { ::std::mem::transmute(finalized_main) };
let args = ::std::env::var("JIT_ARGS").unwrap_or_else(|_| String::new());
let args = args
.split(" ")
.chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
.map(|arg| CString::new(arg).unwrap())
.collect::<Vec<_>>();
let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
// TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
let ret = f(args.len() as c_int, argv.as_ptr());
jit_module.finish();
std::process::exit(ret);
}
fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
use rustc::middle::dependency_format::Linkage;
let mut dylib_paths = Vec::new();
let crate_info = CrateInfo::new(tcx);
let formats = tcx.sess.dependency_formats.borrow();
let data = formats.get(&CrateType::Executable).unwrap();
for &(cnum, _) in &crate_info.used_crates_dynamic {
let src = &crate_info.used_crate_source[&cnum];
match data[cnum.as_usize() - 1] {
Linkage::NotLinked | Linkage::IncludedFromDylib => {}
Linkage::Static => {
let name = tcx.crate_name(cnum);
let mut err = tcx
.sess
.struct_err(&format!("Can't load static lib {}", name.as_str()));
err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
err.emit();
}
Linkage::Dynamic => {
dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
}
}
}
let mut imported_symbols = Vec::new();
for path in dylib_paths {
use object::Object;
let lib = libloading::Library::new(&path).unwrap();
let obj = std::fs::read(path).unwrap();
let obj = object::File::parse(&obj).unwrap();
imported_symbols.extend(obj.dynamic_symbols().filter_map(|(_idx, symbol)| {
let name = symbol.name().unwrap().to_string();
if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
return None;
}
let symbol: libloading::Symbol<*const u8> =
unsafe { lib.get(name.as_bytes()) }.unwrap();
Some((name, *symbol))
}));
std::mem::forget(lib)
}
tcx.sess.abort_if_errors();
imported_symbols
}
fn run_aot(
tcx: TyCtxt<'_>,
metadata: EncodedMetadata,
need_metadata_module: bool,
log: &mut Option<File>,
) -> Box<CodegenResults> {
let new_module = |name: String| {
let module: Module<FaerieBackend> = Module::new(
FaerieBuilder::new(
crate::build_isa(tcx.sess, true),
name + ".o",
FaerieTrapCollection::Disabled,
cranelift_module::default_libcall_names(),
)
.unwrap(),
);
assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
module
};
let emit_module = |kind: ModuleKind,
mut module: Module<FaerieBackend>,
debug: Option<DebugContext>| {
module.finalize_definitions();
let mut artifact = module.finish().artifact;
if let Some(mut debug) = debug {
debug.emit(&mut artifact);
}
let tmp_file = tcx
.output_filenames(LOCAL_CRATE)
.temp_path(OutputType::Object, Some(&artifact.name));
let obj = artifact.emit().unwrap();
std::fs::write(&tmp_file, obj).unwrap();
CompiledModule {
name: artifact.name,
kind,
object: Some(tmp_file),
bytecode: None,
bytecode_compressed: None,
}
};
let mut faerie_module = new_module("some_file".to_string());
let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None
// macOS debuginfo doesn't work yet (see #303)
&& !tcx.sess.target.target.options.is_like_osx
{
let debug = DebugContext::new(
tcx,
faerie_module.target_config().pointer_type().bytes() as u8,
);
Some(debug)
} else {
None
};
codegen_cgus(tcx, &mut faerie_module, &mut debug, log);
tcx.sess.abort_if_errors();
let mut allocator_module = new_module("allocator_shim".to_string());
let created_alloc_shim = crate::allocator::codegen(tcx.sess, &mut allocator_module);
rustc_incremental::assert_dep_graph(tcx);
rustc_incremental::save_dep_graph(tcx);
rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE));
let metadata_module = if need_metadata_module {
use rustc::mir::mono::CodegenUnitNameBuilder;
let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
let metadata_cgu_name = cgu_name_builder
.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
.as_str()
.to_string();
let mut metadata_artifact = faerie::Artifact::new(
crate::build_isa(tcx.sess, true).triple().clone(),
metadata_cgu_name.clone(),
);
crate::metadata::write_metadata(tcx, &mut metadata_artifact);
let tmp_file = tcx
.output_filenames(LOCAL_CRATE)
.temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
let obj = metadata_artifact.emit().unwrap();
std::fs::write(&tmp_file, obj).unwrap();
Some(CompiledModule {
name: metadata_cgu_name,
kind: ModuleKind::Metadata,
object: Some(tmp_file),
bytecode: None,
bytecode_compressed: None,
})
} else {
None
};
Box::new(CodegenResults {
crate_name: tcx.crate_name(LOCAL_CRATE),
modules: vec![emit_module(
ModuleKind::Regular,
faerie_module,
debug,
)],
allocator_module: if created_alloc_shim {
Some(emit_module(
ModuleKind::Allocator,
allocator_module,
None,
))
} else {
None
},
metadata_module,
crate_hash: tcx.crate_hash(LOCAL_CRATE),
metadata,
windows_subsystem: None, // Windows is not yet supported
linker_info: LinkerInfo::new(tcx),
crate_info: CrateInfo::new(tcx),
})
}
fn codegen_cgus<'tcx>(
tcx: TyCtxt<'tcx>,
module: &mut Module<impl Backend + 'static>,
debug: &mut Option<DebugContext<'tcx>>,
log: &mut Option<File>,
) {
let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
let mono_items = cgus
.iter()
.map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
.flatten()
.collect::<FxHashMap<_, (_, _)>>();
codegen_mono_items(tcx, module, debug.as_mut(), log, mono_items);
crate::main_shim::maybe_create_entry_wrapper(tcx, module);
}
fn codegen_mono_items<'tcx>(
tcx: TyCtxt<'tcx>,
module: &mut Module<impl Backend + 'static>,
debug_context: Option<&mut DebugContext<'tcx>>,
log: &mut Option<File>,
mono_items: FxHashMap<MonoItem<'tcx>, (RLinkage, Visibility)>,
) {
let mut cx = CodegenCx::new(tcx, module, debug_context);
time("codegen mono items", move || {
for (mono_item, (linkage, visibility)) in mono_items {
crate::unimpl::try_unimpl(tcx, log, || {
let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
trans_mono_item(&mut cx, mono_item, linkage);
});
}
cx.finalize();
});
}
fn trans_mono_item<'clif, 'tcx, B: Backend + 'static>(
cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
mono_item: MonoItem<'tcx>,
linkage: Linkage,
) {
let tcx = cx.tcx;
match mono_item {
MonoItem::Fn(inst) => {
let _inst_guard =
PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).name.as_str()));
debug_assert!(!inst.substs.needs_infer());
let _mir_guard = PrintOnPanic(|| {
match inst.def {
InstanceDef::Item(_)
| InstanceDef::DropGlue(_, _)
| InstanceDef::Virtual(_, _) => {
let mut mir = ::std::io::Cursor::new(Vec::new());
crate::rustc_mir::util::write_mir_pretty(
tcx,
Some(inst.def_id()),
&mut mir,
)
.unwrap();
String::from_utf8(mir.into_inner()).unwrap()
}
_ => {
// FIXME fix write_mir_pretty for these instances
format!("{:#?}", tcx.instance_mir(inst.def))
}
}
});
crate::base::trans_fn(cx, inst, linkage);
}
MonoItem::Static(def_id) => {
crate::constant::codegen_static(&mut cx.constants_cx, def_id);
}
MonoItem::GlobalAsm(node_id) => tcx
.sess
.fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
}
}
fn time<R>(name: &str, f: impl FnOnce() -> R) -> R {
println!("[{}] start", name);
let before = std::time::Instant::now();
let res = f();
let after = std::time::Instant::now();
println!("[{}] end time: {:?}", name, after - before);
res
}
|
use core::future::Future;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Error {
Failed,
AddressMisaligned,
BufferMisaligned,
}
pub trait Flash {
type ReadFuture<'a>: Future<Output = Result<(), Error>>
where
Self: 'a;
type WriteFuture<'a>: Future<Output = Result<(), Error>>
where
Self: 'a;
type ErasePageFuture<'a>: Future<Output = Result<(), Error>>
where
Self: 'a;
/// Reads data from the flash device.
///
/// address must be a multiple of self.read_size().
/// buf.len() must be a multiple of self.read_size().
fn read<'a>(&'a mut self, address: usize, buf: &'a mut [u8]) -> Self::ReadFuture<'a>;
/// Writes data to the flash device.
///
/// address must be a multiple of self.write_size().
/// buf.len() must be a multiple of self.write_size().
fn write<'a>(&'a mut self, address: usize, buf: &'a [u8]) -> Self::WriteFuture<'a>;
/// Erases a single page from the flash device.
///
/// address must be a multiple of self.erase_size().
fn erase<'a>(&'a mut self, address: usize) -> Self::ErasePageFuture<'a>;
/// Returns the total size, in bytes.
/// This is not guaranteed to be a power of 2.
fn size(&self) -> usize;
/// Returns the read size in bytes.
/// This is guaranteed to be a power of 2.
fn read_size(&self) -> usize;
/// Returns the write size in bytes.
/// This is guaranteed to be a power of 2.
fn write_size(&self) -> usize;
/// Returns the erase size in bytes.
/// This is guaranteed to be a power of 2.
fn erase_size(&self) -> usize;
}
|
use rusqlite::{params, Connection, Result};
#[derive(Debug)]
struct User {
id: i32,
name: String,
age: i32,
}
fn main1() -> Result<()> {
// インメモリーデータベースの作成
let cn = Connection::open_in_memory()?;
// テーブル作成とデータ挿入
cn.execute_batch(
"
CREATE TABLE users (id INTEGER, name TEXT, age INTEGER) ;
INSERT INTO users (id, name, age) VALUES (1, 'Kongo', 20) ;
INSERT INTO users (id, name, age) VALUES (2, 'Hieai', 20) ;
INSERT INTO users (id, name, age) VALUES (3, 'Haruna', 18) ;
INSERT INTO users (id, name, age) VALUES (4, 'Kirishima', 15) ;
"
)? ;
// クエリの作成
let mut stmt = cn.prepare("SELECT * FROM users WHERE age > 15")? ;
let iter = stmt.query_map(params![], |row| {
Ok(User{
id: row.get(0)?,
name: row.get(1)?,
age: row.get(2)?,
})
})?;
// データを取得
for it in iter {
println!("user is {:?}", it.unwrap());
}
Ok(())
}
fn main() -> Result<()> {
// インメモリーデータベースの作成
let cn = Connection::open_in_memory()?;
// テーブル作成とデータ挿入
cn.execute_batch(
"
CREATE TABLE users (id INTEGER, name TEXT, age INTEGER) ;
INSERT INTO users (id, name, age) VALUES (1, 'Kongo', 20) ;
INSERT INTO users (id, name, age) VALUES (2, 'Hieai', 20) ;
INSERT INTO users (id, name, age) VALUES (3, 'Haruna', 18) ;
INSERT INTO users (id, name, age) VALUES (4, 'Kirishima', 15) ;
"
)? ;
// クエリの作成
let mut stmt = cn.prepare("SELECT * FROM users WHERE age > 15")? ;
let mut rows = stmt.query(params![])?;
while let Some(row) = rows.next()? {
let it = User {
id: row.get(0)?,
name: row.get(1)?,
age: row.get(2)?,
};
println!("it is {:?}", it );
}
Ok(())
}
fn main3() -> Result<()> {
// インメモリーデータベースの作成
let cn = Connection::open_in_memory()?;
// テーブル作成
cn.execute("CREATE TABLE users (id INTEGER, name TEXT, age INTEGER)", params![] )?;
// データ挿入
let mut stmt = cn.prepare("INSERT INTO users (id, name, age) VALUES (?1, ?2, ?3)")?;
stmt.execute(params![1, "Kongo", 20 ])?;
stmt.execute(params![2, "Hieai", 20 ])?;
stmt.execute(params![3, "Haruna", 18 ])?;
stmt.execute(params![4, "Kirishima", 15 ])?;
// クエリの作成
let mut stmt = cn.prepare("SELECT * FROM users WHERE age > ?")? ;
let iter = stmt.query_map(params![15], |row| {
Ok(User{
id: row.get(0)?,
name: row.get(1)?,
age: row.get(2)?,
})
})?;
// データを取得
for it in iter {
println!("user is {:?}", it.unwrap());
}
Ok(())
}
|
// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Parsing of decl_storage input.
use frame_support_procedural_tools::{syn_ext as ext, Parse, ToTokens};
use syn::{spanned::Spanned, Ident, Token};
mod keyword {
syn::custom_keyword!(hiddencrate);
syn::custom_keyword!(add_extra_genesis);
syn::custom_keyword!(extra_genesis_skip_phantom_data_field);
syn::custom_keyword!(config);
syn::custom_keyword!(build);
syn::custom_keyword!(get);
syn::custom_keyword!(map);
syn::custom_keyword!(double_map);
syn::custom_keyword!(opaque_blake2_256);
syn::custom_keyword!(opaque_blake2_128);
syn::custom_keyword!(blake2_128_concat);
syn::custom_keyword!(opaque_twox_256);
syn::custom_keyword!(opaque_twox_128);
syn::custom_keyword!(twox_64_concat);
syn::custom_keyword!(identity);
syn::custom_keyword!(hasher);
syn::custom_keyword!(tainted);
syn::custom_keyword!(natural);
syn::custom_keyword!(prehashed);
}
/// Specific `Opt` to implement structure with optional parsing
#[derive(Debug, Clone)]
pub struct Opt<P> {
pub inner: Option<P>,
}
impl<P: syn::export::ToTokens> syn::export::ToTokens for Opt<P> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
if let Some(ref p) = self.inner {
p.to_tokens(tokens);
}
}
}
macro_rules! impl_parse_for_opt {
($struct:ident => $token:path) => {
impl syn::parse::Parse for Opt<$struct> {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
if input.peek($token) {
input.parse().map(|p| Opt { inner: Some(p) })
} else {
Ok(Opt { inner: None })
}
}
}
};
}
/// Parsing usage only
#[derive(Parse, ToTokens, Debug)]
struct StorageDefinition {
pub hidden_crate: Opt<SpecificHiddenCrate>,
pub visibility: syn::Visibility,
pub trait_token: Token![trait],
pub ident: Ident,
pub for_token: Token![for],
pub module_ident: Ident,
pub mod_lt_token: Token![<],
pub mod_param_generic: syn::Ident,
pub mod_param_bound_token: Option<Token![:]>,
pub mod_param_bound: syn::Path,
pub mod_instance_param_token: Option<Token![,]>,
pub mod_instance: Option<syn::Ident>,
pub mod_instantiable_token: Option<Token![:]>,
pub mod_instantiable: Option<syn::Ident>,
pub mod_default_instance_token: Option<Token![=]>,
pub mod_default_instance: Option<syn::Ident>,
pub mod_gt_token: Token![>],
pub as_token: Token![as],
pub crate_ident: Ident,
pub where_clause: Option<syn::WhereClause>,
pub content: ext::Braces<ext::Punctuated<DeclStorageLine, Token![;]>>,
pub extra_genesis: Opt<AddExtraGenesis>,
}
#[derive(Parse, ToTokens, Debug)]
struct SpecificHiddenCrate {
pub keyword: keyword::hiddencrate,
pub ident: ext::Parens<Ident>,
}
impl_parse_for_opt!(SpecificHiddenCrate => keyword::hiddencrate);
#[derive(Parse, ToTokens, Debug)]
struct AddExtraGenesis {
pub extragenesis_keyword: keyword::add_extra_genesis,
pub content: ext::Braces<AddExtraGenesisContent>,
}
impl_parse_for_opt!(AddExtraGenesis => keyword::add_extra_genesis);
#[derive(Parse, ToTokens, Debug)]
struct AddExtraGenesisContent {
pub lines: ext::Punctuated<AddExtraGenesisLineEnum, Token![;]>,
}
#[derive(ToTokens, Debug)]
enum AddExtraGenesisLineEnum {
AddExtraGenesisLine(AddExtraGenesisLine),
AddExtraGenesisBuild(DeclStorageBuild),
}
impl syn::parse::Parse for AddExtraGenesisLineEnum {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let input_fork = input.fork();
// OuterAttributes are forbidden for build variant,
// However to have better documentation we match against the keyword after those attributes.
let _: ext::OuterAttributes = input_fork.parse()?;
let lookahead = input_fork.lookahead1();
if lookahead.peek(keyword::build) {
Ok(Self::AddExtraGenesisBuild(input.parse()?))
} else if lookahead.peek(keyword::config) {
Ok(Self::AddExtraGenesisLine(input.parse()?))
} else {
Err(lookahead.error())
}
}
}
#[derive(Parse, ToTokens, Debug)]
struct AddExtraGenesisLine {
pub attrs: ext::OuterAttributes,
pub config_keyword: keyword::config,
pub extra_field: ext::Parens<Ident>,
pub coldot_token: Token![:],
pub extra_type: syn::Type,
pub default_value: Opt<DeclStorageDefault>,
}
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageLine {
// attrs (main use case is doc)
pub attrs: ext::OuterAttributes,
// visibility (no need to make optional
pub visibility: syn::Visibility,
// name
pub name: Ident,
pub getter: Opt<DeclStorageGetter>,
pub config: Opt<DeclStorageConfig>,
pub build: Opt<DeclStorageBuild>,
pub coldot_token: Token![:],
pub storage_type: DeclStorageType,
pub default_value: Opt<DeclStorageDefault>,
}
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageGetterBody {
fn_keyword: Token![fn],
ident: Ident,
}
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageGetter {
pub getter_keyword: keyword::get,
pub getfn: ext::Parens<DeclStorageGetterBody>,
}
impl_parse_for_opt!(DeclStorageGetter => keyword::get);
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageConfig {
pub config_keyword: keyword::config,
pub expr: ext::Parens<Option<syn::Ident>>,
}
impl_parse_for_opt!(DeclStorageConfig => keyword::config);
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageBuild {
pub build_keyword: keyword::build,
pub expr: ext::Parens<syn::Expr>,
}
impl_parse_for_opt!(DeclStorageBuild => keyword::build);
#[derive(ToTokens, Debug)]
enum DeclStorageType {
Map(DeclStorageMap),
DoubleMap(Box<DeclStorageDoubleMap>),
Simple(syn::Type),
}
impl syn::parse::Parse for DeclStorageType {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
if input.peek(keyword::map) {
Ok(Self::Map(input.parse()?))
} else if input.peek(keyword::double_map) {
Ok(Self::DoubleMap(input.parse()?))
} else {
Ok(Self::Simple(input.parse()?))
}
}
}
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageMap {
pub map_keyword: keyword::map,
pub hasher: Opt<SetHasher>,
pub key: syn::Type,
pub ass_keyword: Token![=>],
pub value: syn::Type,
}
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageDoubleMap {
pub map_keyword: keyword::double_map,
pub hasher1: Opt<SetHasher>,
pub key1: syn::Type,
pub comma_keyword: Token![,],
pub hasher2: Opt<SetHasher>,
pub key2: syn::Type,
pub ass_keyword: Token![=>],
pub value: syn::Type,
}
#[derive(ToTokens, Debug)]
enum Hasher {
Blake2_256(keyword::opaque_blake2_256),
Blake2_128(keyword::opaque_blake2_128),
Blake2_128Concat(keyword::blake2_128_concat),
Twox256(keyword::opaque_twox_256),
Twox128(keyword::opaque_twox_128),
Twox64Concat(keyword::twox_64_concat),
Identity(keyword::identity),
}
impl syn::parse::Parse for Hasher {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(keyword::opaque_blake2_256) {
Ok(Self::Blake2_256(input.parse()?))
} else if lookahead.peek(keyword::opaque_blake2_128) {
Ok(Self::Blake2_128(input.parse()?))
} else if lookahead.peek(keyword::blake2_128_concat) {
Ok(Self::Blake2_128Concat(input.parse()?))
} else if lookahead.peek(keyword::opaque_twox_256) {
Ok(Self::Twox256(input.parse()?))
} else if lookahead.peek(keyword::opaque_twox_128) {
Ok(Self::Twox128(input.parse()?))
} else if lookahead.peek(keyword::twox_64_concat) {
Ok(Self::Twox64Concat(input.parse()?))
} else if lookahead.peek(keyword::identity) {
Ok(Self::Identity(input.parse()?))
} else if lookahead.peek(keyword::tainted) {
Ok(Self::Blake2_128Concat(input.parse()?))
} else if lookahead.peek(keyword::natural) {
Ok(Self::Twox64Concat(input.parse()?))
} else if lookahead.peek(keyword::prehashed) {
Ok(Self::Identity(input.parse()?))
} else {
Err(lookahead.error())
}
}
}
#[derive(Parse, ToTokens, Debug)]
struct DeclStorageDefault {
pub equal_token: Token![=],
pub expr: syn::Expr,
}
impl syn::parse::Parse for Opt<DeclStorageDefault> {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
if input.peek(Token![=]) {
input.parse().map(|p| Opt { inner: Some(p) })
} else {
Ok(Opt { inner: None })
}
}
}
#[derive(Parse, ToTokens, Debug)]
struct SetHasher {
pub hasher_keyword: keyword::hasher,
pub inner: ext::Parens<Hasher>,
}
impl_parse_for_opt!(SetHasher => keyword::hasher);
impl From<SetHasher> for super::HasherKind {
fn from(set_hasher: SetHasher) -> Self {
set_hasher.inner.content.into()
}
}
impl From<Hasher> for super::HasherKind {
fn from(hasher: Hasher) -> Self {
match hasher {
Hasher::Blake2_256(_) => super::HasherKind::Blake2_256,
Hasher::Blake2_128(_) => super::HasherKind::Blake2_128,
Hasher::Blake2_128Concat(_) => super::HasherKind::Blake2_128Concat,
Hasher::Twox256(_) => super::HasherKind::Twox256,
Hasher::Twox128(_) => super::HasherKind::Twox128,
Hasher::Twox64Concat(_) => super::HasherKind::Twox64Concat,
Hasher::Identity(_) => super::HasherKind::Identity,
}
}
}
fn get_module_instance(
instance: Option<syn::Ident>,
instantiable: Option<syn::Ident>,
default_instance: Option<syn::Ident>,
) -> syn::Result<Option<super::ModuleInstanceDef>> {
let right_syntax = "Should be $I: $Instance = $DefaultInstance";
if instantiable.as_ref().map_or(false, |i| i != "Instance") {
let msg = format!(
"Instance trait must be named `Instance`, other names are no longer supported, because \
it is now defined at frame_support::traits::Instance. Expect `Instance` found `{}`",
instantiable.as_ref().unwrap(),
);
return Err(syn::Error::new(instantiable.span(), msg))
}
match (instance, instantiable, default_instance) {
(Some(instance), Some(instantiable), default_instance) =>
Ok(Some(super::ModuleInstanceDef {
instance_generic: instance,
instance_trait: instantiable,
instance_default: default_instance,
})),
(None, None, None) => Ok(None),
(Some(instance), None, _) => Err(syn::Error::new(
instance.span(),
format!("Expect instantiable trait bound for instance: {}. {}", instance, right_syntax,),
)),
(None, Some(instantiable), _) => Err(syn::Error::new(
instantiable.span(),
format!(
"Expect instance generic for bound instantiable: {}. {}",
instantiable, right_syntax,
),
)),
(None, _, Some(default_instance)) => Err(syn::Error::new(
default_instance.span(),
format!(
"Expect instance generic for default instance: {}. {}",
default_instance, right_syntax,
),
)),
}
}
pub fn parse(input: syn::parse::ParseStream) -> syn::Result<super::DeclStorageDef> {
use syn::parse::Parse;
let def = StorageDefinition::parse(input)?;
let module_instance =
get_module_instance(def.mod_instance, def.mod_instantiable, def.mod_default_instance)?;
let mut extra_genesis_config_lines = vec![];
let mut extra_genesis_build = None;
for line in
def.extra_genesis.inner.into_iter().flat_map(|o| o.content.content.lines.inner.into_iter())
{
match line {
AddExtraGenesisLineEnum::AddExtraGenesisLine(def) => {
extra_genesis_config_lines.push(super::ExtraGenesisLineDef {
attrs: def.attrs.inner,
name: def.extra_field.content,
typ: def.extra_type,
default: def.default_value.inner.map(|o| o.expr),
});
},
AddExtraGenesisLineEnum::AddExtraGenesisBuild(def) => {
if extra_genesis_build.is_some() {
return Err(syn::Error::new(
def.span(),
"Only one build expression allowed for extra genesis",
))
}
extra_genesis_build = Some(def.expr.content);
},
}
}
let storage_lines = parse_storage_line_defs(def.content.content.inner.into_iter())?;
Ok(super::DeclStorageDef {
hidden_crate: def.hidden_crate.inner.map(|i| i.ident.content),
visibility: def.visibility,
module_name: def.module_ident,
store_trait: def.ident,
module_runtime_generic: def.mod_param_generic,
module_runtime_trait: def.mod_param_bound,
where_clause: def.where_clause,
crate_name: def.crate_ident,
module_instance,
extra_genesis_build,
extra_genesis_config_lines,
storage_lines,
})
}
/// Parse the `DeclStorageLine` into `StorageLineDef`.
fn parse_storage_line_defs(
defs: impl Iterator<Item = DeclStorageLine>,
) -> syn::Result<Vec<super::StorageLineDef>> {
let mut storage_lines = Vec::<super::StorageLineDef>::new();
for line in defs {
let getter = line.getter.inner.map(|o| o.getfn.content.ident);
let config = if let Some(config) = line.config.inner {
if let Some(ident) = config.expr.content {
Some(ident)
} else if let Some(ref ident) = getter {
Some(ident.clone())
} else {
return Err(syn::Error::new(
config.span(),
"Invalid storage definition, couldn't find config identifier: storage must \
either have a get identifier `get(fn ident)` or a defined config identifier \
`config(ident)`",
))
}
} else {
None
};
if let Some(ref config) = config {
storage_lines.iter().filter_map(|sl| sl.config.as_ref()).try_for_each(
|other_config| {
if other_config == config {
Err(syn::Error::new(
config.span(),
"`config()`/`get()` with the same name already defined.",
))
} else {
Ok(())
}
},
)?;
}
let span = line.storage_type.span();
let no_hasher_error = || {
syn::Error::new(
span,
"Default hasher has been removed, use explicit hasher(blake2_128_concat) instead.",
)
};
let storage_type = match line.storage_type {
DeclStorageType::Map(map) => super::StorageLineTypeDef::Map(super::MapDef {
hasher: map.hasher.inner.ok_or_else(no_hasher_error)?.into(),
key: map.key,
value: map.value,
}),
DeclStorageType::DoubleMap(map) =>
super::StorageLineTypeDef::DoubleMap(Box::new(super::DoubleMapDef {
hasher1: map.hasher1.inner.ok_or_else(no_hasher_error)?.into(),
hasher2: map.hasher2.inner.ok_or_else(no_hasher_error)?.into(),
key1: map.key1,
key2: map.key2,
value: map.value,
})),
DeclStorageType::Simple(expr) => super::StorageLineTypeDef::Simple(expr),
};
storage_lines.push(super::StorageLineDef {
attrs: line.attrs.inner,
visibility: line.visibility,
name: line.name,
getter,
config,
build: line.build.inner.map(|o| o.expr.content),
default_value: line.default_value.inner.map(|o| o.expr),
storage_type,
})
}
Ok(storage_lines)
}
|
extern crate rand;
extern crate sha2;
extern crate ed25519_dalek as dalek;
extern crate pbp;
use rand::OsRng;
use sha2::{Sha256, Sha512};
use dalek::Keypair;
use pbp::{PgpKey, KeyFlags};
fn main() {
let mut cspring = OsRng::new().unwrap();
let keypair = Keypair::generate::<Sha512>(&mut cspring);
let key = PgpKey::from_dalek::<Sha256, Sha512>(&keypair, KeyFlags::NONE, "withoutboats");
println!("{}", key);
}
|
//! Leetcode-cil plugins
//!
//! + chrome cookie parser
//! + leetcode API
//!
//! ## login to `leetcode.com`
//! Leetcode-cli use chrome cookie directly, do not need to login, please make sure you have loggined in `leetcode.com` before usnig `leetcode-cli`
//!
// FIXME: Read cookies from local storage. (issue #122)
mod chrome;
mod leetcode;
pub use leetcode::LeetCode;
|
//! The Styx [`Visitor`] trait, and implementations.
use prelude::*;
use expr::BuiltIns;
use typesystem::TyParameters;
/// A structure that can go through an expression tree in order to visit it immutably,
/// or mutably.
pub trait Visitor<T> {
/// Visits the given expression, returning an object of type `T`.
fn visit(&mut self, expr: &Expr) -> T;
/// Mutably visits the given expression, optionally rewriting it and its children,
/// and returning an object of type `T`.
fn rewrite(&mut self, expr: &mut Expr) -> T;
/// Visits the children of the given expression.
fn visit_children(&mut self, expr: &Expr) -> Vec<T> {
let childc = expr.child_count();
let mut vec = Vec::with_capacity(childc);
for i in 0..childc {
vec.push(self.visit(expr.child(i).unwrap()))
}
vec
}
/// Rewrites the children of the given expression.
fn rewrite_children(&mut self, expr: &mut Expr) -> Vec<T> {
let childc = expr.child_count();
let mut vec = Vec::with_capacity(childc);
for i in 0..childc {
vec.push(self.rewrite(expr.mut_child(i).unwrap()))
}
vec
}
}
/// A `Visitor` that verifies that an expression tree can be emitted.
pub struct Verifier<'a, 'cx: 'a> {
#[allow(dead_code)]
diagnostics: Diags<'a>,
#[allow(dead_code)]
parameters: &'a TyParameters<'a, 'cx>,
invalid: bool
}
impl<'a, 'cx> Verifier<'a, 'cx> {
/// Creates a new verifying visitor, given the generic parameters used in this context.
pub fn new(diagnostics: Diags<'a>, parameters: &'a TyParameters<'a, 'cx>) -> Self {
Verifier { diagnostics, parameters, invalid: false }
}
/// Returns whether the visited expression was valid, and can thus be compiled.
pub fn is_valid(&self) -> bool {
!self.invalid
}
}
impl<'a, 'cx> Visitor<()> for Verifier<'a, 'cx> {
fn visit(&mut self, _expr: &Expr) -> () {
}
fn rewrite(&mut self, expr: &mut Expr) -> () {
self.visit(expr)
}
}
/// A [`Visitor`] that inlines method calls in an expression tree.
///
/// # Note
/// This type only inlines calls at the *expression* level, but not at the IR level.
///
/// # Panics
/// This type assumes that the given expressions have been verified and are valid.
/// If an invalid expression is encountered, a panic will take place.
///
/// Additionally, expression trees can only be mutably visited (using [`Visitor::rewrite`]).
pub struct Inliner<'a, 'cx: 'a> {
#[allow(dead_code)]
parameters: &'a TyParameters<'a, 'cx>
}
impl<'a, 'cx> Inliner<'a, 'cx> {
/// Creates a new inlining visitor, given the generic parameters used in this context.
pub fn new(parameters: &'a TyParameters<'a, 'cx>) -> Self {
Inliner { parameters }
}
}
impl<'a, 'cx> Visitor<()> for Inliner<'a, 'cx> {
fn visit(&mut self, _: &Expr) -> () {
panic!("Inliner cannot visit immutable expressions.")
}
fn rewrite(&mut self, expr: &mut Expr) -> () {
if expr.expr_ty() != BuiltIns::call() {
return
}
}
}
/// A closure-invoking [`Visitor`].
pub struct ClosureVisitor<'a, T: 'a> {
closure: &'a Fn(&mut ClosureVisitor<'a, T>, &Expr) -> T
}
impl<'a, T> ClosureVisitor<'a, T> {
/// Creates a new closure-based visitor, given the closure to invoke on all expressions.
pub fn new(visit: &'a Fn(&mut Self, &Expr) -> T) -> Self {
ClosureVisitor { closure: visit }
}
}
impl<'a, T> Visitor<T> for ClosureVisitor<'a, T> {
fn visit(&mut self, expr: &Expr) -> T {
(self.closure)(self, expr)
}
fn rewrite(&mut self, expr: &mut Expr) -> T {
(self.closure)(self, expr)
}
}
|
use serde::{Deserialize, Serialize};
use super::{data, extended_identifiers::ExtendedIdentifiers, geo::Geo};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct User {
id: Option<String>,
buyeruid: Option<String>,
yob: Option<u32>,
gender: Option<String>,
keywords: Option<String>,
consent: Option<String>,
geo: Option<Geo>,
data: Option<data::Data>,
eids: Option<ExtendedIdentifiers>,
ext: Option<UserExt>,
}
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct UserExt {}
|
use spirv_builder::{MemoryModel, SpirvBuilder};
fn main() -> anyhow::Result<()> {
let result = SpirvBuilder::new("shader")
.spirv_version(1, 0)
.memory_model(MemoryModel::GLSL450)
.print_metadata(false)
.build_multimodule()?;
let directory = result
.values()
.next()
.and_then(|path| path.parent())
.unwrap();
println!("cargo:rustc-env=spv={}", directory.to_str().unwrap());
Ok(())
}
|
fn main() {
let mut number = 12;
println!("{}", number);
number = 53;
println!("{}", number);
}
|
#[macro_use]
extern crate raui_core;
mod app;
mod ui;
use crate::app::App;
use ggez::{event, ContextBuilder};
fn main() {
let resource_dir = if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
let mut path = std::path::PathBuf::from(manifest_dir);
path.push("resources");
path
} else {
std::path::PathBuf::from("./resources")
};
let (mut ctx, mut event_loop) = ContextBuilder::new("In-Game Demo", "Cool Game Author")
.add_resource_path(resource_dir)
.window_mode(
ggez::conf::WindowMode::default()
.resizable(true)
.maximized(false),
)
.build()
.expect("Could not create GGEZ context");
let mut app = App::new(&mut ctx);
if let Err(error) = event::run(&mut ctx, &mut event_loop, &mut app) {
println!("Error: {}", error);
}
}
|
//! # Line
use derive_getters::Getters;
use cgmath::{Point3, Vector3, BaseFloat};
/// Line stored as the line equation.
#[derive(Debug, Clone, Getters)]
pub struct Line<S: BaseFloat> {
point: Point3<S>,
vector: Vector3<S>,
}
impl<S: BaseFloat> Line<S> {
pub fn new(point: Point3<S>, vector: Vector3<S>) -> Self {
Line { point, vector }
}
}
/*
impl<S: BaseFloat> From<(Point3<S>, Point3<S>)> for Line<S> {
fn from(t: (Point3<S>, Point3<S>)) -> Self {
Line::new(t.0, t.1)
}
}
*/
|
//
// Copyright 2021 The Project Oak 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.
//
//! Test utilities to help with unit testing of Oak-Functions SDK code.
use anyhow::Context;
use log::info;
use std::{path::PathBuf, process::Command};
// TODO(#1965): Move this and the similar function in `oak/sdk` to a common crate.
/// Uses cargo to compile a Rust manifest to Wasm bytes.
pub fn compile_rust_wasm(
manifest_path: &str,
module_wasm_file_name: &str,
) -> anyhow::Result<Vec<u8>> {
let mut module_path = PathBuf::from(manifest_path);
module_path.pop();
module_path.push("bin");
let args = vec![
// `--out-dir` is unstable and requires `-Zunstable-options`.
"-Zunstable-options".to_string(),
"build".to_string(),
"--release".to_string(),
"--target=wasm32-unknown-unknown".to_string(),
format!("--manifest-path={}", manifest_path),
// Use a fixed target directory, because `--target-dir` influences SHA256 hash
// of Wasm module. Target directory should also be synchronized with
// `--target-dir` used in [`oak_tests::compile_rust_wasm`] in order to have
// same SHA256 hashes.
format!("--target-dir={}", {
let mut target_dir = PathBuf::from(manifest_path);
target_dir.pop();
target_dir.push("target");
target_dir.to_str().expect("Invalid target dir").to_string()
}),
format!(
"--out-dir={}",
module_path
.to_str()
.expect("Invalid target dir")
.to_string()
),
];
Command::new("cargo")
.args(args)
.env_remove("RUSTFLAGS")
.spawn()
.context("Couldn't spawn cargo build")?
.wait()
.context("Couldn't wait for cargo build to finish")?;
module_path.push(module_wasm_file_name);
info!("Compiled Wasm module path: {:?}", module_path);
std::fs::read(module_path).context("Couldn't read compiled module")
}
|
mod decoder;
mod values;
mod types;
mod instructions;
pub mod modules; |
use crate::error::{ViuError, ViuResult};
use crate::printer::Printer;
use crate::Config;
use image::DynamicImage;
use image::GenericImageView;
use lazy_static::lazy_static;
use std::env;
use std::io::{Read, Write};
pub struct SixelPrinter {}
impl Printer for SixelPrinter {
fn print(&self, img: &DynamicImage, _config: &Config) -> ViuResult<(u32, u32)> {
print_sixel(img)
}
}
fn print_sixel(img: &image::DynamicImage) -> ViuResult<(u32, u32)> {
use sixel::encoder::{Encoder, QuickFrameBuilder};
use sixel::optflags::EncodePolicy;
let (x_pixles, y_pixels) = img.dimensions();
let rgba = img.to_rgba8();
let raw = rgba.as_raw();
let encoder = Encoder::new()?;
encoder.set_encode_policy(EncodePolicy::Fast)?;
let frame = QuickFrameBuilder::new()
.width(x_pixles as usize)
.height(y_pixels as usize)
.format(sixel_sys::PixelFormat::RGBA8888)
.pixels(raw.to_vec());
encoder.encode_bytes(frame)?;
// No end of line printed by encoder
let mut stdout = std::io::stdout();
stdout.flush()?;
let y_pixel_size = get_pixel_size();
let small_y_pixels = y_pixels as u16;
Ok((
x_pixles,
if y_pixel_size <= 0 {
5000
} else {
(small_y_pixels / y_pixel_size + 1) as u32
},
))
}
#[cfg(windows)]
fn get_pixel_size() -> u16 {
0
}
#[cfg(unix)]
#[derive(Debug)]
#[repr(C)]
struct winsize {
ws_row: libc::c_ushort,
ws_col: libc::c_ushort,
ws_xpixel: libc::c_ushort,
ws_ypixel: libc::c_ushort,
}
#[cfg(unix)]
fn get_pixel_size() -> u16 {
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
const TIOCGWINSZ: libc::c_ulong = 0x40087468;
#[cfg(any(target_os = "linux", target_os = "android"))]
const TIOCGWINSZ: libc::c_ulong = 0x5413;
let size_out = winsize {
ws_row: 0,
ws_col: 0,
ws_xpixel: 0,
ws_ypixel: 0,
};
unsafe {
if libc::ioctl(1, TIOCGWINSZ, &size_out) != 0 {
return 0;
}
}
if size_out.ws_ypixel <= 0 || size_out.ws_row <= 0 {
return 0;
}
size_out.ws_ypixel / size_out.ws_row
}
impl std::convert::From<sixel::status::Error> for crate::error::ViuError {
fn from(e: sixel::status::Error) -> Self {
ViuError::SixelError(e)
}
}
lazy_static! {
static ref SIXEL_SUPPORT: SixelSupport = check_sixel_support();
}
/// Returns the terminal's support for the Kitty graphics protocol.
pub fn get_sixel_support() -> SixelSupport {
*SIXEL_SUPPORT
}
#[derive(PartialEq, Copy, Clone)]
/// The extend to which the Kitty graphics protocol can be used.
pub enum SixelSupport {
/// The Sixel graphics protocol is not supported.
None,
/// The Sixel graphics protocol is supported.
Supported,
}
///TODO check for sixel support on windows
#[cfg(windows)]
fn xterm_check_sixel_support() -> Result<SixelSupport, std::io::Error> {
SixelSupport::None
}
// Parsing the escape code sequence
// see
// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
// section 5.4.2
// about parsing Parameter string format
// and section
// and 8.3.16 for the definition of CSI (spoiler alert, it's Escape [)
// Note: In ECMA-048 docs, 05/11 is the same as 0x5B which is the hex ascii code for [
// And see
// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
// CSI Ps c Send Device Attributes (Primary DA).
enum XTERMSupportParserState {
ExpectCSIESC,
ExpectCSIOpenBracket,
ExpectQuestionMark,
ParseParameter,
ParseParameterNotFour,
ParseParameterMightBeFour,
InvalidState,
FoundFour,
}
#[cfg(unix)]
fn xterm_check_sixel_support() -> Result<SixelSupport, std::io::Error> {
use std::fs::write;
use std::io::stdin;
use termios::*;
//STDOUT_FILENO
let file_descriptor = 1;
let mut term_info = Termios::from_fd(file_descriptor)?;
let old_iflag = term_info.c_iflag;
let old_lflag = term_info.c_lflag;
//setup the terminal so that it will send the device attributes
//to stdin rather than writing them to the screen
term_info.c_iflag &= !(ISTRIP);
term_info.c_iflag &= !(INLCR);
term_info.c_iflag &= !(ICRNL);
term_info.c_iflag &= !(IGNCR);
term_info.c_iflag &= !(IXOFF);
term_info.c_lflag &= !(ECHO);
term_info.c_lflag &= !(ICANON);
tcsetattr(file_descriptor, TCSANOW, &mut term_info)?;
//Send Device Attributes
// see https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
write("/dev/tty", "\x1b[0c")?;
let mut std_in_buffer: [u8; 256] = [0; 256];
let size_read = stdin().read(&mut std_in_buffer)?;
let mut state = XTERMSupportParserState::ExpectCSIESC;
for i in 0..size_read {
let current_char = std_in_buffer[i];
use XTERMSupportParserState::{
ExpectCSIESC, ExpectCSIOpenBracket, ExpectQuestionMark, FoundFour, InvalidState,
ParseParameter, ParseParameterMightBeFour, ParseParameterNotFour,
};
match state {
ExpectCSIESC => {
//ascii for ESC
if current_char != 27 {
state = InvalidState;
break;
}
state = ExpectCSIOpenBracket;
}
ExpectCSIOpenBracket => {
//ascii for [
if current_char != 91 {
state = InvalidState;
break;
}
state = ExpectQuestionMark;
}
ExpectQuestionMark => {
//ascii for ?
if current_char != 63 {
state = InvalidState;
break;
}
state = ParseParameter;
}
//ascii for 4
ParseParameter => {
state = if current_char != 52 {
ParseParameterNotFour
} else {
ParseParameterMightBeFour
}
}
//ascii for ; which is the separator
ParseParameterNotFour => {
state = if current_char != 59 {
ParseParameterNotFour
} else {
ParseParameter
}
}
//59 is ascii for ; which is the separator and
// 99 is ascii for c which marks the end of the phrase
ParseParameterMightBeFour => {
if current_char == 59 || current_char == 99 {
state = FoundFour;
break;
}
state = ParseParameterNotFour;
}
InvalidState => break,
FoundFour => break,
}
}
term_info.c_iflag = old_iflag;
term_info.c_lflag = old_lflag;
tcsetattr(file_descriptor, TCSANOW, &mut term_info)?;
Ok(if let XTERMSupportParserState::FoundFour = state {
SixelSupport::Supported
} else {
SixelSupport::None
})
}
// // Check if Sixel protocol can be used
fn check_sixel_support() -> SixelSupport {
use SixelSupport::{None, Supported};
match env::var("TERM").unwrap_or(String::from("None")).as_str() {
"mlterm" => Supported,
"yaft-256color" => Supported,
"st-256color" => xterm_check_sixel_support().unwrap_or(None),
"xterm" => xterm_check_sixel_support().unwrap_or(None),
"xterm-256color" => xterm_check_sixel_support().unwrap_or(None),
_ => match env::var("TERM_PROGRAM")
.unwrap_or(String::from("None"))
.as_str()
{
"MacTerm" => Supported,
_ => None,
},
}
}
///Ignore this test because it
///only passes on systems with
///sixel support
#[test]
#[ignore]
fn sixel_support() {
match check_sixel_support() {
SixelSupport::Supported => (),
SixelSupport::None => assert!(false),
}
}
|
use super::TokenCredential;
use azure_core::TokenResponse;
use chrono::Utc;
use oauth2::{
basic::{BasicClient, BasicErrorResponseType},
reqwest::async_http_client,
AccessToken, AuthType, AuthUrl, Scope, StandardErrorResponse, TokenUrl,
};
use std::{str, time::Duration};
use url::Url;
/// Provides options to configure how the Identity library makes authentication
/// requests to Azure Active Directory.
#[derive(Clone, Debug, PartialEq)]
pub struct TokenCredentialOptions {
authority_host: String,
}
impl Default for TokenCredentialOptions {
fn default() -> Self {
Self {
authority_host: authority_hosts::AZURE_PUBLIC_CLOUD.to_owned(),
}
}
}
impl TokenCredentialOptions {
/// Create a new TokenCredentialsOptions. `default()` may also be used.
pub fn new(authority_host: String) -> Self {
Self { authority_host }
}
pub fn set_authority_host(&mut self, authority_host: String) {
self.authority_host = authority_host
}
/// The authority host to use for authentication requests. The default is
/// "https://login.microsoftonline.com".
pub fn authority_host(&self) -> &str {
&self.authority_host
}
}
/// A list of known Azure authority hosts
pub mod authority_hosts {
/// China-based Azure Authority Host
pub const AZURE_CHINA: &str = "https://login.chinacloudapi.cn";
/// Germany-based Azure Authority Host
pub const AZURE_GERMANY: &str = "https://login.microsoftonline.de";
/// US Government Azure Authority Host
pub const AZURE_GOVERNMENT: &str = "https://login.microsoftonline.us";
/// Public Cloud Azure Authority Host
pub const AZURE_PUBLIC_CLOUD: &str = "https://login.microsoftonline.com";
}
pub mod tenant_ids {
/// The tenant ID for multi-tenant apps
///
/// https://docs.microsoft.com/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant
pub const TENANT_ID_COMMON: &str = "common";
/// The tenant ID for Active Directory Federated Services
pub const TENANT_ID_ADFS: &str = "adfs";
}
/// Enables authentication to Azure Active Directory using a client secret that was generated for an App Registration.
///
/// More information on how to configure a client secret can be found here:
/// https://docs.microsoft.com/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application
pub struct ClientSecretCredential {
tenant_id: String,
client_id: oauth2::ClientId,
client_secret: Option<oauth2::ClientSecret>,
options: TokenCredentialOptions,
}
impl ClientSecretCredential {
pub fn new(
tenant_id: String,
client_id: String,
client_secret: String,
options: TokenCredentialOptions,
) -> ClientSecretCredential {
ClientSecretCredential {
tenant_id,
client_id: oauth2::ClientId::new(client_id),
client_secret: Some(oauth2::ClientSecret::new(client_secret)),
options,
}
}
fn options(&self) -> &TokenCredentialOptions {
&self.options
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ClientSecretCredentialError {
#[error("Failed to construct token endpoint with tenant id {1}: {0}")]
FailedConstructTokenEndpoint(url::ParseError, String),
#[error("Failed to construct authorize endpoint with tenant id {1}: {0}")]
FailedConstructAuthorizeEndpoint(url::ParseError, String),
#[error("Request token error: {0}")]
RequestTokenError(
oauth2::RequestTokenError<
oauth2::reqwest::Error<reqwest::Error>,
StandardErrorResponse<BasicErrorResponseType>,
>,
),
}
#[async_trait::async_trait]
impl TokenCredential for ClientSecretCredential {
type Error = ClientSecretCredentialError;
async fn get_token(&self, resource: &str) -> Result<TokenResponse, Self::Error> {
let options = self.options();
let authority_host = options.authority_host();
let token_url = TokenUrl::from_url(
Url::parse(&format!(
"{}/{}/oauth2/v2.0/token",
authority_host, self.tenant_id
))
.map_err(|error| {
ClientSecretCredentialError::FailedConstructTokenEndpoint(
error,
self.tenant_id.clone(),
)
})?,
);
let auth_url = AuthUrl::from_url(
Url::parse(&format!(
"{}/{}/oauth2/v2.0/authorize",
authority_host, self.tenant_id
))
.map_err(|error| {
ClientSecretCredentialError::FailedConstructAuthorizeEndpoint(
error,
self.tenant_id.clone(),
)
})?,
);
let client = BasicClient::new(
self.client_id.clone(),
self.client_secret.clone(),
auth_url,
Some(token_url),
)
.set_auth_type(AuthType::RequestBody);
let token_result = client
.exchange_client_credentials()
.add_scope(Scope::new(format!("{}/.default", resource)))
.request_async(async_http_client)
.await
.map(|r| {
use oauth2::TokenResponse as _;
TokenResponse::new(
AccessToken::new(r.access_token().secret().to_owned()),
Utc::now()
+ chrono::Duration::from_std(
r.expires_in().unwrap_or_else(|| Duration::from_secs(0)),
)
.unwrap(),
)
})
.map_err(ClientSecretCredentialError::RequestTokenError)?;
Ok(token_result)
}
}
#[async_trait::async_trait]
impl azure_core::TokenCredential for ClientSecretCredential {
async fn get_token(
&self,
resource: &str,
) -> Result<azure_core::TokenResponse, azure_core::Error> {
TokenCredential::get_token(self, resource)
.await
.map_err(|error| azure_core::Error::GetTokenError(Box::new(error)))
}
}
|
use clap::{
Arg,
App,
crate_name,
crate_version,
crate_authors,
};
use bio::{
seq::{
parser::LeadingColumns,
fasta::*
}
};
use chunks;
fn main() {
let matches = App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about("Converts embl files to fasta files")
.arg(Arg::with_name("seqIn")
.short("i")
.long("seqIn")
.multiple(false)
.takes_value(true)
.help("EMBL-formatted sequence input file. If not provided, defaults to STDIN.")
)
.arg(Arg::with_name("seqOut")
.short("o")
.long("seqOut")
.multiple(false)
.takes_value(true)
.help("Sequence output file. If not provided, defaults to STDOUT."))
.get_matches();
let mut out =
chunks::write_to_file_or_stdout(matches.value_of("seqOut"))
.expect("Failed to open output file for writing");
let ins = chunks::read_from_files_or_stdin(matches.values_of("seqIn"))
.expect("Failed to open input file for reading");
let delim = chunks::Delim::new(b"\n//\n", true);
let fasta = FastaFormat::new();
let embl_stanzas = LeadingColumns { tag_columns: 5, merge_tags: true };
for in_reader in ins {
for chunk in chunks::chunks(in_reader, &delim) {
let chunk = chunk.expect("Failed to read chunk");
let chunk_text = std::str::from_utf8(&chunk).unwrap();
// println!("<<<");
let stanzas = embl_stanzas.stanzas(chunk_text.lines()).collect::<Vec<_>>();
// println!("Stanza view:");
// println!("{:?}", stanzas);
let id = stanzas.iter()
.filter(|s| s.tag == Some("ID"))
.flat_map(|s| s.lines.iter().flat_map(|l| l.split(';')))
.next();
// println!("ID line:");
// println!("{:?}", id);
let descr = stanzas.iter()
.filter(|s| s.tag == Some("DE"))
.map(|s| s.lines.iter()
.copied()
.collect::<String>()) // fixme: this may abolish whitespace between lines
.next();
// println!("Sequence:");
let seq = stanzas.iter()
.filter(|s| s.tag == Some("SQ"))
.flat_map(|s| s.lines.iter()
.skip(1)
.flat_map(|l| l.split_whitespace()
.filter(|&t| t.chars().all(|c| c.is_ascii_alphabetic()))))
.collect::<String>();
// println!("{:?}", seq);
if !seq.is_empty() {
let descr_line = FastaRecord::descr_line(id, descr.as_ref().map(String::as_str));
// println!("ID line text: {}", descr_line);
let fasta_record = FastaRecord { descr_line, seq };
fasta_record.write(&fasta, &mut out)
.expect("Problem writing fasta record out");
}
// println!(">>>")
}
}
}
|
//! Reference counted handles to various TableProperties* types, that safely
//! preserve destruction order.
use crocksdb_ffi::{
DBTableProperties, DBTablePropertiesCollection, DBTablePropertiesCollectionIterator,
DBUserCollectedProperties,
};
use librocksdb_sys as crocksdb_ffi;
use std::rc::Rc;
/// This is a shared wrapper around a DBTablePropertiesCollection w/ dtor
#[derive(Clone)]
pub struct TablePropertiesCollectionHandle {
shared: Rc<TablePropertiesCollectionHandleWithDrop>,
}
impl TablePropertiesCollectionHandle {
pub unsafe fn new(ptr: *mut DBTablePropertiesCollection) -> TablePropertiesCollectionHandle {
assert!(!ptr.is_null());
TablePropertiesCollectionHandle {
shared: Rc::new(TablePropertiesCollectionHandleWithDrop { ptr }),
}
}
pub fn ptr(&self) -> *mut DBTablePropertiesCollection {
self.shared.ptr
}
}
struct TablePropertiesCollectionHandleWithDrop {
ptr: *mut DBTablePropertiesCollection,
}
impl Drop for TablePropertiesCollectionHandleWithDrop {
fn drop(&mut self) {
unsafe {
crocksdb_ffi::crocksdb_table_properties_collection_destroy(self.ptr);
}
}
}
/// This is a shared wrapper around a DBTablePropertiesCollection w/ dtor.
//
// # Safety
//
// The safety of this struct depends on drop order, with the iterator
// needing to drop before the collection.
#[derive(Clone)]
pub struct TablePropertiesCollectionIteratorHandle {
shared: Rc<TablePropertiesCollectionIteratorHandleWithDrop>,
_collection: TablePropertiesCollectionHandle,
}
impl TablePropertiesCollectionIteratorHandle {
pub fn new(
collection: TablePropertiesCollectionHandle,
) -> TablePropertiesCollectionIteratorHandle {
unsafe {
let ptr =
crocksdb_ffi::crocksdb_table_properties_collection_iter_create(collection.ptr());
TablePropertiesCollectionIteratorHandle {
shared: Rc::new(TablePropertiesCollectionIteratorHandleWithDrop { ptr }),
_collection: collection,
}
}
}
pub fn ptr(&self) -> *mut DBTablePropertiesCollectionIterator {
self.shared.ptr
}
}
struct TablePropertiesCollectionIteratorHandleWithDrop {
ptr: *mut DBTablePropertiesCollectionIterator,
}
impl Drop for TablePropertiesCollectionIteratorHandleWithDrop {
fn drop(&mut self) {
unsafe {
crocksdb_ffi::crocksdb_table_properties_collection_iter_destroy(self.ptr);
}
}
}
// # Safety
//
// `ptr` is valid as long as the iterator is
#[derive(Clone)]
pub struct TablePropertiesHandle {
ptr: *const DBTableProperties,
_iter_handle: TablePropertiesCollectionIteratorHandle,
}
impl TablePropertiesHandle {
pub fn new(
ptr: *const DBTableProperties,
_iter_handle: TablePropertiesCollectionIteratorHandle,
) -> TablePropertiesHandle {
TablePropertiesHandle { ptr, _iter_handle }
}
pub fn ptr(&self) -> *const DBTableProperties {
self.ptr
}
}
// # Safety
//
// `ptr` is valid as long as the table properties are
#[derive(Clone)]
pub struct UserCollectedPropertiesHandle {
ptr: *const DBUserCollectedProperties,
_table_props_handle: TablePropertiesHandle,
}
impl UserCollectedPropertiesHandle {
pub fn new(table_props_handle: TablePropertiesHandle) -> UserCollectedPropertiesHandle {
unsafe {
let ptr = crocksdb_ffi::crocksdb_table_properties_get_user_properties(
table_props_handle.ptr(),
);
UserCollectedPropertiesHandle {
ptr,
_table_props_handle: table_props_handle,
}
}
}
pub fn ptr(&self) -> *const DBUserCollectedProperties {
self.ptr
}
}
|
// src/db.rs
use std::env;
use diesel::prelude::*;
use diesel::{r2d2, PgConnection};
use crate::models::*;
use crate::schema::*;
use crate::StdErr;
type PgPool = r2d2::Pool<r2d2::ConnectionManager<PgConnection>>;
pub struct Db {
pool: PgPool,
}
impl Db {
pub fn connect() -> Result<Self, StdErr> {
let db_url = env::var("DATABASE_URL")?;
let manager = r2d2::ConnectionManager::new(db_url);
let pool = r2d2::Builder::new()
.max_size(100)
.min_idle(Some(50))
.build(manager)?;
Ok(Db { pool })
}
// token methods
pub fn validate_token(&self, token_id: &str) -> Result<Token, StdErr> {
let conn = self.pool.get()?;
let token = tokens::table
.filter(tokens::id.eq(token_id))
.filter(tokens::expired_at.ge(diesel::dsl::now))
.first(&conn)?;
Ok(token)
}
// board methods
pub fn boards(&self) -> Result<Vec<Board>, StdErr> {
let conn = self.pool.get()?;
Ok(boards::table.load(&conn)?)
}
pub fn board_summary(&self, board_id: i64) -> Result<BoardSummary, StdErr> {
let conn = self.pool.get()?;
let counts: Vec<StatusCount> = diesel::sql_query(format!(
"select count(*), status from cards where cards.board_id = {} group by status",
board_id
))
.load(&conn)?;
Ok(counts.into())
}
pub fn create_board(&self, create_board: CreateBoard) -> Result<Board, StdErr> {
let conn = self.pool.get()?;
let board = diesel::insert_into(boards::table)
.values(&create_board)
.get_result(&conn)?;
Ok(board)
}
pub fn delete_board(&self, board_id: i64) -> Result<(), StdErr> {
let conn = self.pool.get()?;
diesel::delete(boards::table.filter(boards::id.eq(board_id))).execute(&conn)?;
Ok(())
}
// card methods
pub fn cards(&self, board_id: i64) -> Result<Vec<Card>, StdErr> {
let conn = self.pool.get()?;
let cards = cards::table
.filter(cards::board_id.eq(board_id))
.load(&conn)?;
Ok(cards)
}
pub fn create_card(&self, create_card: CreateCard) -> Result<Card, StdErr> {
let conn = self.pool.get()?;
let card = diesel::insert_into(cards::table)
.values(create_card)
.get_result(&conn)?;
Ok(card)
}
pub fn update_card(&self, card_id: i64, update_card: UpdateCard) -> Result<Card, StdErr> {
let conn = self.pool.get()?;
let card = diesel::update(cards::table.filter(cards::id.eq(card_id)))
.set(update_card)
.get_result(&conn)?;
Ok(card)
}
pub fn delete_card(&self, card_id: i64) -> Result<(), StdErr> {
let conn = self.pool.get()?;
diesel::delete(cards::table.filter(cards::id.eq(card_id))).execute(&conn)?;
Ok(())
}
}
|
/// An enum to represent all characters in the EnclosedAlphanumericSupplement block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum EnclosedAlphanumericSupplement {
/// \u{1f100}: '🄀'
DigitZeroFullStop,
/// \u{1f101}: '🄁'
DigitZeroComma,
/// \u{1f102}: '🄂'
DigitOneComma,
/// \u{1f103}: '🄃'
DigitTwoComma,
/// \u{1f104}: '🄄'
DigitThreeComma,
/// \u{1f105}: '🄅'
DigitFourComma,
/// \u{1f106}: '🄆'
DigitFiveComma,
/// \u{1f107}: '🄇'
DigitSixComma,
/// \u{1f108}: '🄈'
DigitSevenComma,
/// \u{1f109}: '🄉'
DigitEightComma,
/// \u{1f10a}: '🄊'
DigitNineComma,
/// \u{1f10b}: '🄋'
DingbatCircledSansDashSerifDigitZero,
/// \u{1f10c}: '🄌'
DingbatNegativeCircledSansDashSerifDigitZero,
/// \u{1f110}: '🄐'
ParenthesizedLatinCapitalLetterA,
/// \u{1f111}: '🄑'
ParenthesizedLatinCapitalLetterB,
/// \u{1f112}: '🄒'
ParenthesizedLatinCapitalLetterC,
/// \u{1f113}: '🄓'
ParenthesizedLatinCapitalLetterD,
/// \u{1f114}: '🄔'
ParenthesizedLatinCapitalLetterE,
/// \u{1f115}: '🄕'
ParenthesizedLatinCapitalLetterF,
/// \u{1f116}: '🄖'
ParenthesizedLatinCapitalLetterG,
/// \u{1f117}: '🄗'
ParenthesizedLatinCapitalLetterH,
/// \u{1f118}: '🄘'
ParenthesizedLatinCapitalLetterI,
/// \u{1f119}: '🄙'
ParenthesizedLatinCapitalLetterJ,
/// \u{1f11a}: '🄚'
ParenthesizedLatinCapitalLetterK,
/// \u{1f11b}: '🄛'
ParenthesizedLatinCapitalLetterL,
/// \u{1f11c}: '🄜'
ParenthesizedLatinCapitalLetterM,
/// \u{1f11d}: '🄝'
ParenthesizedLatinCapitalLetterN,
/// \u{1f11e}: '🄞'
ParenthesizedLatinCapitalLetterO,
/// \u{1f11f}: '🄟'
ParenthesizedLatinCapitalLetterP,
/// \u{1f120}: '🄠'
ParenthesizedLatinCapitalLetterQ,
/// \u{1f121}: '🄡'
ParenthesizedLatinCapitalLetterR,
/// \u{1f122}: '🄢'
ParenthesizedLatinCapitalLetterS,
/// \u{1f123}: '🄣'
ParenthesizedLatinCapitalLetterT,
/// \u{1f124}: '🄤'
ParenthesizedLatinCapitalLetterU,
/// \u{1f125}: '🄥'
ParenthesizedLatinCapitalLetterV,
/// \u{1f126}: '🄦'
ParenthesizedLatinCapitalLetterW,
/// \u{1f127}: '🄧'
ParenthesizedLatinCapitalLetterX,
/// \u{1f128}: '🄨'
ParenthesizedLatinCapitalLetterY,
/// \u{1f129}: '🄩'
ParenthesizedLatinCapitalLetterZ,
/// \u{1f12a}: '🄪'
TortoiseShellBracketedLatinCapitalLetterS,
/// \u{1f12b}: '🄫'
CircledItalicLatinCapitalLetterC,
/// \u{1f12c}: '🄬'
CircledItalicLatinCapitalLetterR,
/// \u{1f12d}: '🄭'
CircledCd,
/// \u{1f12e}: '🄮'
CircledWz,
/// \u{1f12f}: '🄯'
CopyleftSymbol,
/// \u{1f130}: '🄰'
SquaredLatinCapitalLetterA,
/// \u{1f131}: '🄱'
SquaredLatinCapitalLetterB,
/// \u{1f132}: '🄲'
SquaredLatinCapitalLetterC,
/// \u{1f133}: '🄳'
SquaredLatinCapitalLetterD,
/// \u{1f134}: '🄴'
SquaredLatinCapitalLetterE,
/// \u{1f135}: '🄵'
SquaredLatinCapitalLetterF,
/// \u{1f136}: '🄶'
SquaredLatinCapitalLetterG,
/// \u{1f137}: '🄷'
SquaredLatinCapitalLetterH,
/// \u{1f138}: '🄸'
SquaredLatinCapitalLetterI,
/// \u{1f139}: '🄹'
SquaredLatinCapitalLetterJ,
/// \u{1f13a}: '🄺'
SquaredLatinCapitalLetterK,
/// \u{1f13b}: '🄻'
SquaredLatinCapitalLetterL,
/// \u{1f13c}: '🄼'
SquaredLatinCapitalLetterM,
/// \u{1f13d}: '🄽'
SquaredLatinCapitalLetterN,
/// \u{1f13e}: '🄾'
SquaredLatinCapitalLetterO,
/// \u{1f13f}: '🄿'
SquaredLatinCapitalLetterP,
/// \u{1f140}: '🅀'
SquaredLatinCapitalLetterQ,
/// \u{1f141}: '🅁'
SquaredLatinCapitalLetterR,
/// \u{1f142}: '🅂'
SquaredLatinCapitalLetterS,
/// \u{1f143}: '🅃'
SquaredLatinCapitalLetterT,
/// \u{1f144}: '🅄'
SquaredLatinCapitalLetterU,
/// \u{1f145}: '🅅'
SquaredLatinCapitalLetterV,
/// \u{1f146}: '🅆'
SquaredLatinCapitalLetterW,
/// \u{1f147}: '🅇'
SquaredLatinCapitalLetterX,
/// \u{1f148}: '🅈'
SquaredLatinCapitalLetterY,
/// \u{1f149}: '🅉'
SquaredLatinCapitalLetterZ,
/// \u{1f14a}: '🅊'
SquaredHv,
/// \u{1f14b}: '🅋'
SquaredMv,
/// \u{1f14c}: '🅌'
SquaredSd,
/// \u{1f14d}: '🅍'
SquaredSs,
/// \u{1f14e}: '🅎'
SquaredPpv,
/// \u{1f14f}: '🅏'
SquaredWc,
/// \u{1f150}: '🅐'
NegativeCircledLatinCapitalLetterA,
/// \u{1f151}: '🅑'
NegativeCircledLatinCapitalLetterB,
/// \u{1f152}: '🅒'
NegativeCircledLatinCapitalLetterC,
/// \u{1f153}: '🅓'
NegativeCircledLatinCapitalLetterD,
/// \u{1f154}: '🅔'
NegativeCircledLatinCapitalLetterE,
/// \u{1f155}: '🅕'
NegativeCircledLatinCapitalLetterF,
/// \u{1f156}: '🅖'
NegativeCircledLatinCapitalLetterG,
/// \u{1f157}: '🅗'
NegativeCircledLatinCapitalLetterH,
/// \u{1f158}: '🅘'
NegativeCircledLatinCapitalLetterI,
/// \u{1f159}: '🅙'
NegativeCircledLatinCapitalLetterJ,
/// \u{1f15a}: '🅚'
NegativeCircledLatinCapitalLetterK,
/// \u{1f15b}: '🅛'
NegativeCircledLatinCapitalLetterL,
/// \u{1f15c}: '🅜'
NegativeCircledLatinCapitalLetterM,
/// \u{1f15d}: '🅝'
NegativeCircledLatinCapitalLetterN,
/// \u{1f15e}: '🅞'
NegativeCircledLatinCapitalLetterO,
/// \u{1f15f}: '🅟'
NegativeCircledLatinCapitalLetterP,
/// \u{1f160}: '🅠'
NegativeCircledLatinCapitalLetterQ,
/// \u{1f161}: '🅡'
NegativeCircledLatinCapitalLetterR,
/// \u{1f162}: '🅢'
NegativeCircledLatinCapitalLetterS,
/// \u{1f163}: '🅣'
NegativeCircledLatinCapitalLetterT,
/// \u{1f164}: '🅤'
NegativeCircledLatinCapitalLetterU,
/// \u{1f165}: '🅥'
NegativeCircledLatinCapitalLetterV,
/// \u{1f166}: '🅦'
NegativeCircledLatinCapitalLetterW,
/// \u{1f167}: '🅧'
NegativeCircledLatinCapitalLetterX,
/// \u{1f168}: '🅨'
NegativeCircledLatinCapitalLetterY,
/// \u{1f169}: '🅩'
NegativeCircledLatinCapitalLetterZ,
/// \u{1f16a}: '🅪'
RaisedMcSign,
/// \u{1f16b}: '🅫'
RaisedMdSign,
/// \u{1f16c}: '🅬'
RaisedMrSign,
/// \u{1f170}: '🅰'
NegativeSquaredLatinCapitalLetterA,
/// \u{1f171}: '🅱'
NegativeSquaredLatinCapitalLetterB,
/// \u{1f172}: '🅲'
NegativeSquaredLatinCapitalLetterC,
/// \u{1f173}: '🅳'
NegativeSquaredLatinCapitalLetterD,
/// \u{1f174}: '🅴'
NegativeSquaredLatinCapitalLetterE,
/// \u{1f175}: '🅵'
NegativeSquaredLatinCapitalLetterF,
/// \u{1f176}: '🅶'
NegativeSquaredLatinCapitalLetterG,
/// \u{1f177}: '🅷'
NegativeSquaredLatinCapitalLetterH,
/// \u{1f178}: '🅸'
NegativeSquaredLatinCapitalLetterI,
/// \u{1f179}: '🅹'
NegativeSquaredLatinCapitalLetterJ,
/// \u{1f17a}: '🅺'
NegativeSquaredLatinCapitalLetterK,
/// \u{1f17b}: '🅻'
NegativeSquaredLatinCapitalLetterL,
/// \u{1f17c}: '🅼'
NegativeSquaredLatinCapitalLetterM,
/// \u{1f17d}: '🅽'
NegativeSquaredLatinCapitalLetterN,
/// \u{1f17e}: '🅾'
NegativeSquaredLatinCapitalLetterO,
/// \u{1f17f}: '🅿'
NegativeSquaredLatinCapitalLetterP,
/// \u{1f180}: '🆀'
NegativeSquaredLatinCapitalLetterQ,
/// \u{1f181}: '🆁'
NegativeSquaredLatinCapitalLetterR,
/// \u{1f182}: '🆂'
NegativeSquaredLatinCapitalLetterS,
/// \u{1f183}: '🆃'
NegativeSquaredLatinCapitalLetterT,
/// \u{1f184}: '🆄'
NegativeSquaredLatinCapitalLetterU,
/// \u{1f185}: '🆅'
NegativeSquaredLatinCapitalLetterV,
/// \u{1f186}: '🆆'
NegativeSquaredLatinCapitalLetterW,
/// \u{1f187}: '🆇'
NegativeSquaredLatinCapitalLetterX,
/// \u{1f188}: '🆈'
NegativeSquaredLatinCapitalLetterY,
/// \u{1f189}: '🆉'
NegativeSquaredLatinCapitalLetterZ,
/// \u{1f18a}: '🆊'
CrossedNegativeSquaredLatinCapitalLetterP,
/// \u{1f18b}: '🆋'
NegativeSquaredIc,
/// \u{1f18c}: '🆌'
NegativeSquaredPa,
/// \u{1f18d}: '🆍'
NegativeSquaredSa,
/// \u{1f18e}: '🆎'
NegativeSquaredAb,
/// \u{1f18f}: '🆏'
NegativeSquaredWc,
/// \u{1f190}: '🆐'
SquareDj,
/// \u{1f191}: '🆑'
SquaredCl,
/// \u{1f192}: '🆒'
SquaredCool,
/// \u{1f193}: '🆓'
SquaredFree,
/// \u{1f194}: '🆔'
SquaredId,
/// \u{1f195}: '🆕'
SquaredNew,
/// \u{1f196}: '🆖'
SquaredNg,
/// \u{1f197}: '🆗'
SquaredOk,
/// \u{1f198}: '🆘'
SquaredSos,
/// \u{1f199}: '🆙'
SquaredUpWithExclamationMark,
/// \u{1f19a}: '🆚'
SquaredVs,
/// \u{1f19b}: '🆛'
SquaredThreeD,
/// \u{1f19c}: '🆜'
SquaredSecondScreen,
/// \u{1f19d}: '🆝'
SquaredTwoK,
/// \u{1f19e}: '🆞'
SquaredFourK,
/// \u{1f19f}: '🆟'
SquaredEightK,
/// \u{1f1a0}: '🆠'
SquaredFivePointOne,
/// \u{1f1a1}: '🆡'
SquaredSevenPointOne,
/// \u{1f1a2}: '🆢'
SquaredTwentyDashTwoPointTwo,
/// \u{1f1a3}: '🆣'
SquaredSixtyP,
/// \u{1f1a4}: '🆤'
SquaredOneHundredTwentyP,
/// \u{1f1a5}: '🆥'
SquaredLatinSmallLetterD,
/// \u{1f1a6}: '🆦'
SquaredHc,
/// \u{1f1a7}: '🆧'
SquaredHdr,
/// \u{1f1a8}: '🆨'
SquaredHiDashRes,
/// \u{1f1a9}: '🆩'
SquaredLossless,
/// \u{1f1aa}: '🆪'
SquaredShv,
/// \u{1f1ab}: '🆫'
SquaredUhd,
/// \u{1f1ac}: '🆬'
SquaredVod,
/// \u{1f1e6}: '🇦'
RegionalIndicatorSymbolLetterA,
/// \u{1f1e7}: '🇧'
RegionalIndicatorSymbolLetterB,
/// \u{1f1e8}: '🇨'
RegionalIndicatorSymbolLetterC,
/// \u{1f1e9}: '🇩'
RegionalIndicatorSymbolLetterD,
/// \u{1f1ea}: '🇪'
RegionalIndicatorSymbolLetterE,
/// \u{1f1eb}: '🇫'
RegionalIndicatorSymbolLetterF,
/// \u{1f1ec}: '🇬'
RegionalIndicatorSymbolLetterG,
/// \u{1f1ed}: '🇭'
RegionalIndicatorSymbolLetterH,
/// \u{1f1ee}: '🇮'
RegionalIndicatorSymbolLetterI,
/// \u{1f1ef}: '🇯'
RegionalIndicatorSymbolLetterJ,
/// \u{1f1f0}: '🇰'
RegionalIndicatorSymbolLetterK,
/// \u{1f1f1}: '🇱'
RegionalIndicatorSymbolLetterL,
/// \u{1f1f2}: '🇲'
RegionalIndicatorSymbolLetterM,
/// \u{1f1f3}: '🇳'
RegionalIndicatorSymbolLetterN,
/// \u{1f1f4}: '🇴'
RegionalIndicatorSymbolLetterO,
/// \u{1f1f5}: '🇵'
RegionalIndicatorSymbolLetterP,
/// \u{1f1f6}: '🇶'
RegionalIndicatorSymbolLetterQ,
/// \u{1f1f7}: '🇷'
RegionalIndicatorSymbolLetterR,
/// \u{1f1f8}: '🇸'
RegionalIndicatorSymbolLetterS,
/// \u{1f1f9}: '🇹'
RegionalIndicatorSymbolLetterT,
/// \u{1f1fa}: '🇺'
RegionalIndicatorSymbolLetterU,
/// \u{1f1fb}: '🇻'
RegionalIndicatorSymbolLetterV,
/// \u{1f1fc}: '🇼'
RegionalIndicatorSymbolLetterW,
/// \u{1f1fd}: '🇽'
RegionalIndicatorSymbolLetterX,
/// \u{1f1fe}: '🇾'
RegionalIndicatorSymbolLetterY,
}
impl Into<char> for EnclosedAlphanumericSupplement {
fn into(self) -> char {
match self {
EnclosedAlphanumericSupplement::DigitZeroFullStop => '🄀',
EnclosedAlphanumericSupplement::DigitZeroComma => '🄁',
EnclosedAlphanumericSupplement::DigitOneComma => '🄂',
EnclosedAlphanumericSupplement::DigitTwoComma => '🄃',
EnclosedAlphanumericSupplement::DigitThreeComma => '🄄',
EnclosedAlphanumericSupplement::DigitFourComma => '🄅',
EnclosedAlphanumericSupplement::DigitFiveComma => '🄆',
EnclosedAlphanumericSupplement::DigitSixComma => '🄇',
EnclosedAlphanumericSupplement::DigitSevenComma => '🄈',
EnclosedAlphanumericSupplement::DigitEightComma => '🄉',
EnclosedAlphanumericSupplement::DigitNineComma => '🄊',
EnclosedAlphanumericSupplement::DingbatCircledSansDashSerifDigitZero => '🄋',
EnclosedAlphanumericSupplement::DingbatNegativeCircledSansDashSerifDigitZero => '🄌',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterA => '🄐',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterB => '🄑',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterC => '🄒',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterD => '🄓',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterE => '🄔',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterF => '🄕',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterG => '🄖',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterH => '🄗',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterI => '🄘',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterJ => '🄙',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterK => '🄚',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterL => '🄛',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterM => '🄜',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterN => '🄝',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterO => '🄞',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterP => '🄟',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterQ => '🄠',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterR => '🄡',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterS => '🄢',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterT => '🄣',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterU => '🄤',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterV => '🄥',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterW => '🄦',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterX => '🄧',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterY => '🄨',
EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterZ => '🄩',
EnclosedAlphanumericSupplement::TortoiseShellBracketedLatinCapitalLetterS => '🄪',
EnclosedAlphanumericSupplement::CircledItalicLatinCapitalLetterC => '🄫',
EnclosedAlphanumericSupplement::CircledItalicLatinCapitalLetterR => '🄬',
EnclosedAlphanumericSupplement::CircledCd => '🄭',
EnclosedAlphanumericSupplement::CircledWz => '🄮',
EnclosedAlphanumericSupplement::CopyleftSymbol => '🄯',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterA => '🄰',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterB => '🄱',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterC => '🄲',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterD => '🄳',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterE => '🄴',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterF => '🄵',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterG => '🄶',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterH => '🄷',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterI => '🄸',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterJ => '🄹',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterK => '🄺',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterL => '🄻',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterM => '🄼',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterN => '🄽',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterO => '🄾',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterP => '🄿',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterQ => '🅀',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterR => '🅁',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterS => '🅂',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterT => '🅃',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterU => '🅄',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterV => '🅅',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterW => '🅆',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterX => '🅇',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterY => '🅈',
EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterZ => '🅉',
EnclosedAlphanumericSupplement::SquaredHv => '🅊',
EnclosedAlphanumericSupplement::SquaredMv => '🅋',
EnclosedAlphanumericSupplement::SquaredSd => '🅌',
EnclosedAlphanumericSupplement::SquaredSs => '🅍',
EnclosedAlphanumericSupplement::SquaredPpv => '🅎',
EnclosedAlphanumericSupplement::SquaredWc => '🅏',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterA => '🅐',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterB => '🅑',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterC => '🅒',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterD => '🅓',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterE => '🅔',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterF => '🅕',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterG => '🅖',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterH => '🅗',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterI => '🅘',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterJ => '🅙',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterK => '🅚',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterL => '🅛',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterM => '🅜',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterN => '🅝',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterO => '🅞',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterP => '🅟',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterQ => '🅠',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterR => '🅡',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterS => '🅢',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterT => '🅣',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterU => '🅤',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterV => '🅥',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterW => '🅦',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterX => '🅧',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterY => '🅨',
EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterZ => '🅩',
EnclosedAlphanumericSupplement::RaisedMcSign => '🅪',
EnclosedAlphanumericSupplement::RaisedMdSign => '🅫',
EnclosedAlphanumericSupplement::RaisedMrSign => '🅬',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterA => '🅰',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterB => '🅱',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterC => '🅲',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterD => '🅳',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterE => '🅴',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterF => '🅵',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterG => '🅶',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterH => '🅷',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterI => '🅸',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterJ => '🅹',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterK => '🅺',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterL => '🅻',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterM => '🅼',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterN => '🅽',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterO => '🅾',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterP => '🅿',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterQ => '🆀',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterR => '🆁',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterS => '🆂',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterT => '🆃',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterU => '🆄',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterV => '🆅',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterW => '🆆',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterX => '🆇',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterY => '🆈',
EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterZ => '🆉',
EnclosedAlphanumericSupplement::CrossedNegativeSquaredLatinCapitalLetterP => '🆊',
EnclosedAlphanumericSupplement::NegativeSquaredIc => '🆋',
EnclosedAlphanumericSupplement::NegativeSquaredPa => '🆌',
EnclosedAlphanumericSupplement::NegativeSquaredSa => '🆍',
EnclosedAlphanumericSupplement::NegativeSquaredAb => '🆎',
EnclosedAlphanumericSupplement::NegativeSquaredWc => '🆏',
EnclosedAlphanumericSupplement::SquareDj => '🆐',
EnclosedAlphanumericSupplement::SquaredCl => '🆑',
EnclosedAlphanumericSupplement::SquaredCool => '🆒',
EnclosedAlphanumericSupplement::SquaredFree => '🆓',
EnclosedAlphanumericSupplement::SquaredId => '🆔',
EnclosedAlphanumericSupplement::SquaredNew => '🆕',
EnclosedAlphanumericSupplement::SquaredNg => '🆖',
EnclosedAlphanumericSupplement::SquaredOk => '🆗',
EnclosedAlphanumericSupplement::SquaredSos => '🆘',
EnclosedAlphanumericSupplement::SquaredUpWithExclamationMark => '🆙',
EnclosedAlphanumericSupplement::SquaredVs => '🆚',
EnclosedAlphanumericSupplement::SquaredThreeD => '🆛',
EnclosedAlphanumericSupplement::SquaredSecondScreen => '🆜',
EnclosedAlphanumericSupplement::SquaredTwoK => '🆝',
EnclosedAlphanumericSupplement::SquaredFourK => '🆞',
EnclosedAlphanumericSupplement::SquaredEightK => '🆟',
EnclosedAlphanumericSupplement::SquaredFivePointOne => '🆠',
EnclosedAlphanumericSupplement::SquaredSevenPointOne => '🆡',
EnclosedAlphanumericSupplement::SquaredTwentyDashTwoPointTwo => '🆢',
EnclosedAlphanumericSupplement::SquaredSixtyP => '🆣',
EnclosedAlphanumericSupplement::SquaredOneHundredTwentyP => '🆤',
EnclosedAlphanumericSupplement::SquaredLatinSmallLetterD => '🆥',
EnclosedAlphanumericSupplement::SquaredHc => '🆦',
EnclosedAlphanumericSupplement::SquaredHdr => '🆧',
EnclosedAlphanumericSupplement::SquaredHiDashRes => '🆨',
EnclosedAlphanumericSupplement::SquaredLossless => '🆩',
EnclosedAlphanumericSupplement::SquaredShv => '🆪',
EnclosedAlphanumericSupplement::SquaredUhd => '🆫',
EnclosedAlphanumericSupplement::SquaredVod => '🆬',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterA => '🇦',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterB => '🇧',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterC => '🇨',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterD => '🇩',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterE => '🇪',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterF => '🇫',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterG => '🇬',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterH => '🇭',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterI => '🇮',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterJ => '🇯',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterK => '🇰',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterL => '🇱',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterM => '🇲',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterN => '🇳',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterO => '🇴',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterP => '🇵',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterQ => '🇶',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterR => '🇷',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterS => '🇸',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterT => '🇹',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterU => '🇺',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterV => '🇻',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterW => '🇼',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterX => '🇽',
EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterY => '🇾',
}
}
}
impl std::convert::TryFrom<char> for EnclosedAlphanumericSupplement {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'🄀' => Ok(EnclosedAlphanumericSupplement::DigitZeroFullStop),
'🄁' => Ok(EnclosedAlphanumericSupplement::DigitZeroComma),
'🄂' => Ok(EnclosedAlphanumericSupplement::DigitOneComma),
'🄃' => Ok(EnclosedAlphanumericSupplement::DigitTwoComma),
'🄄' => Ok(EnclosedAlphanumericSupplement::DigitThreeComma),
'🄅' => Ok(EnclosedAlphanumericSupplement::DigitFourComma),
'🄆' => Ok(EnclosedAlphanumericSupplement::DigitFiveComma),
'🄇' => Ok(EnclosedAlphanumericSupplement::DigitSixComma),
'🄈' => Ok(EnclosedAlphanumericSupplement::DigitSevenComma),
'🄉' => Ok(EnclosedAlphanumericSupplement::DigitEightComma),
'🄊' => Ok(EnclosedAlphanumericSupplement::DigitNineComma),
'🄋' => Ok(EnclosedAlphanumericSupplement::DingbatCircledSansDashSerifDigitZero),
'🄌' => Ok(EnclosedAlphanumericSupplement::DingbatNegativeCircledSansDashSerifDigitZero),
'🄐' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterA),
'🄑' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterB),
'🄒' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterC),
'🄓' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterD),
'🄔' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterE),
'🄕' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterF),
'🄖' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterG),
'🄗' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterH),
'🄘' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterI),
'🄙' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterJ),
'🄚' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterK),
'🄛' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterL),
'🄜' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterM),
'🄝' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterN),
'🄞' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterO),
'🄟' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterP),
'🄠' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterQ),
'🄡' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterR),
'🄢' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterS),
'🄣' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterT),
'🄤' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterU),
'🄥' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterV),
'🄦' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterW),
'🄧' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterX),
'🄨' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterY),
'🄩' => Ok(EnclosedAlphanumericSupplement::ParenthesizedLatinCapitalLetterZ),
'🄪' => Ok(EnclosedAlphanumericSupplement::TortoiseShellBracketedLatinCapitalLetterS),
'🄫' => Ok(EnclosedAlphanumericSupplement::CircledItalicLatinCapitalLetterC),
'🄬' => Ok(EnclosedAlphanumericSupplement::CircledItalicLatinCapitalLetterR),
'🄭' => Ok(EnclosedAlphanumericSupplement::CircledCd),
'🄮' => Ok(EnclosedAlphanumericSupplement::CircledWz),
'🄯' => Ok(EnclosedAlphanumericSupplement::CopyleftSymbol),
'🄰' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterA),
'🄱' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterB),
'🄲' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterC),
'🄳' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterD),
'🄴' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterE),
'🄵' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterF),
'🄶' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterG),
'🄷' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterH),
'🄸' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterI),
'🄹' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterJ),
'🄺' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterK),
'🄻' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterL),
'🄼' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterM),
'🄽' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterN),
'🄾' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterO),
'🄿' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterP),
'🅀' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterQ),
'🅁' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterR),
'🅂' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterS),
'🅃' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterT),
'🅄' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterU),
'🅅' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterV),
'🅆' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterW),
'🅇' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterX),
'🅈' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterY),
'🅉' => Ok(EnclosedAlphanumericSupplement::SquaredLatinCapitalLetterZ),
'🅊' => Ok(EnclosedAlphanumericSupplement::SquaredHv),
'🅋' => Ok(EnclosedAlphanumericSupplement::SquaredMv),
'🅌' => Ok(EnclosedAlphanumericSupplement::SquaredSd),
'🅍' => Ok(EnclosedAlphanumericSupplement::SquaredSs),
'🅎' => Ok(EnclosedAlphanumericSupplement::SquaredPpv),
'🅏' => Ok(EnclosedAlphanumericSupplement::SquaredWc),
'🅐' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterA),
'🅑' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterB),
'🅒' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterC),
'🅓' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterD),
'🅔' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterE),
'🅕' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterF),
'🅖' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterG),
'🅗' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterH),
'🅘' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterI),
'🅙' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterJ),
'🅚' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterK),
'🅛' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterL),
'🅜' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterM),
'🅝' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterN),
'🅞' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterO),
'🅟' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterP),
'🅠' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterQ),
'🅡' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterR),
'🅢' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterS),
'🅣' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterT),
'🅤' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterU),
'🅥' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterV),
'🅦' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterW),
'🅧' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterX),
'🅨' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterY),
'🅩' => Ok(EnclosedAlphanumericSupplement::NegativeCircledLatinCapitalLetterZ),
'🅪' => Ok(EnclosedAlphanumericSupplement::RaisedMcSign),
'🅫' => Ok(EnclosedAlphanumericSupplement::RaisedMdSign),
'🅬' => Ok(EnclosedAlphanumericSupplement::RaisedMrSign),
'🅰' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterA),
'🅱' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterB),
'🅲' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterC),
'🅳' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterD),
'🅴' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterE),
'🅵' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterF),
'🅶' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterG),
'🅷' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterH),
'🅸' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterI),
'🅹' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterJ),
'🅺' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterK),
'🅻' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterL),
'🅼' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterM),
'🅽' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterN),
'🅾' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterO),
'🅿' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterP),
'🆀' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterQ),
'🆁' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterR),
'🆂' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterS),
'🆃' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterT),
'🆄' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterU),
'🆅' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterV),
'🆆' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterW),
'🆇' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterX),
'🆈' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterY),
'🆉' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredLatinCapitalLetterZ),
'🆊' => Ok(EnclosedAlphanumericSupplement::CrossedNegativeSquaredLatinCapitalLetterP),
'🆋' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredIc),
'🆌' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredPa),
'🆍' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredSa),
'🆎' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredAb),
'🆏' => Ok(EnclosedAlphanumericSupplement::NegativeSquaredWc),
'🆐' => Ok(EnclosedAlphanumericSupplement::SquareDj),
'🆑' => Ok(EnclosedAlphanumericSupplement::SquaredCl),
'🆒' => Ok(EnclosedAlphanumericSupplement::SquaredCool),
'🆓' => Ok(EnclosedAlphanumericSupplement::SquaredFree),
'🆔' => Ok(EnclosedAlphanumericSupplement::SquaredId),
'🆕' => Ok(EnclosedAlphanumericSupplement::SquaredNew),
'🆖' => Ok(EnclosedAlphanumericSupplement::SquaredNg),
'🆗' => Ok(EnclosedAlphanumericSupplement::SquaredOk),
'🆘' => Ok(EnclosedAlphanumericSupplement::SquaredSos),
'🆙' => Ok(EnclosedAlphanumericSupplement::SquaredUpWithExclamationMark),
'🆚' => Ok(EnclosedAlphanumericSupplement::SquaredVs),
'🆛' => Ok(EnclosedAlphanumericSupplement::SquaredThreeD),
'🆜' => Ok(EnclosedAlphanumericSupplement::SquaredSecondScreen),
'🆝' => Ok(EnclosedAlphanumericSupplement::SquaredTwoK),
'🆞' => Ok(EnclosedAlphanumericSupplement::SquaredFourK),
'🆟' => Ok(EnclosedAlphanumericSupplement::SquaredEightK),
'🆠' => Ok(EnclosedAlphanumericSupplement::SquaredFivePointOne),
'🆡' => Ok(EnclosedAlphanumericSupplement::SquaredSevenPointOne),
'🆢' => Ok(EnclosedAlphanumericSupplement::SquaredTwentyDashTwoPointTwo),
'🆣' => Ok(EnclosedAlphanumericSupplement::SquaredSixtyP),
'🆤' => Ok(EnclosedAlphanumericSupplement::SquaredOneHundredTwentyP),
'🆥' => Ok(EnclosedAlphanumericSupplement::SquaredLatinSmallLetterD),
'🆦' => Ok(EnclosedAlphanumericSupplement::SquaredHc),
'🆧' => Ok(EnclosedAlphanumericSupplement::SquaredHdr),
'🆨' => Ok(EnclosedAlphanumericSupplement::SquaredHiDashRes),
'🆩' => Ok(EnclosedAlphanumericSupplement::SquaredLossless),
'🆪' => Ok(EnclosedAlphanumericSupplement::SquaredShv),
'🆫' => Ok(EnclosedAlphanumericSupplement::SquaredUhd),
'🆬' => Ok(EnclosedAlphanumericSupplement::SquaredVod),
'🇦' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterA),
'🇧' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterB),
'🇨' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterC),
'🇩' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterD),
'🇪' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterE),
'🇫' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterF),
'🇬' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterG),
'🇭' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterH),
'🇮' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterI),
'🇯' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterJ),
'🇰' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterK),
'🇱' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterL),
'🇲' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterM),
'🇳' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterN),
'🇴' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterO),
'🇵' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterP),
'🇶' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterQ),
'🇷' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterR),
'🇸' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterS),
'🇹' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterT),
'🇺' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterU),
'🇻' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterV),
'🇼' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterW),
'🇽' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterX),
'🇾' => Ok(EnclosedAlphanumericSupplement::RegionalIndicatorSymbolLetterY),
_ => Err(()),
}
}
}
impl Into<u32> for EnclosedAlphanumericSupplement {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for EnclosedAlphanumericSupplement {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for EnclosedAlphanumericSupplement {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl EnclosedAlphanumericSupplement {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
EnclosedAlphanumericSupplement::DigitZeroFullStop
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("EnclosedAlphanumericSupplement{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
use dotenv;
use std::env;
use diesel::prelude::*;
use diesel::r2d2::{ Pool, PooledConnection, ConnectionManager };
pub type SqlitePool = Pool<ConnectionManager<SqliteConnection>>;
pub type SqlitePooledConnection = PooledConnection<ConnectionManager<SqliteConnection>>;
pub fn init_pool() -> SqlitePool {
dotenv::dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL");
let manager = ConnectionManager::<SqliteConnection>::new(database_url);
Pool::builder().build(manager).expect("Failed to create pool")
} |
#![allow(unused_assignments, unreachable_patterns)]
use win32::{HINSTANCE, HWND};
pub const VK_KHR_WIN32_SURFACE_SPEC_VERSION: u32 = 6;
pub const VK_KHR_SURFACE_SPEC_VERSION: u32 = 25;
pub const VK_KHR_SWAPCHAIN_SPEC_VERSION: u32 = 70;
pub const VK_EXT_DEBUG_UTILS_SPEC_VERSION: u32 = 1;
pub const VK_SUBPASS_EXTERNAL: u32 = 4294967295;
pub const VK_QUEUE_FAMILY_IGNORED: u32 = 4294967295;
pub const VK_FALSE: u32 = 0;
pub const VK_TRUE: u32 = 1;
pub const VK_ATTACHMENT_UNUSED: u32 = 4294967295;
pub const VK_WHOLE_SIZE: u64 = 18446744073709551615;
pub const VK_REMAINING_ARRAY_LAYERS: u32 = 4294967295;
pub const VK_REMAINING_MIP_LEVELS: u32 = 4294967295;
pub const VK_LOD_CLAMP_NONE: f32 = 1000.000000;
pub const VK_KHR_WIN32_SURFACE_EXTENSION_NAME: &str = "VK_KHR_win32_surface";
pub const VK_KHR_WIN32_SURFACE_EXTENSION_NAME__C: &[u8] = b"VK_KHR_win32_surface\0";
pub const VK_KHR_SURFACE_EXTENSION_NAME: &str = "VK_KHR_surface";
pub const VK_KHR_SURFACE_EXTENSION_NAME__C: &[u8] = b"VK_KHR_surface\0";
pub const VK_KHR_SWAPCHAIN_EXTENSION_NAME: &str = "VK_KHR_swapchain";
pub const VK_KHR_SWAPCHAIN_EXTENSION_NAME__C: &[u8] = b"VK_KHR_swapchain\0";
pub const VK_EXT_DEBUG_UTILS_EXTENSION_NAME: &str = "VK_EXT_debug_utils";
pub const VK_EXT_DEBUG_UTILS_EXTENSION_NAME__C: &[u8] = b"VK_EXT_debug_utils\0";
pub type VkBool32 = u32;
pub type VkFlags = u32;
pub type VkDeviceSize = u64;
pub type VkSampleMask = u32;
pub type VkImageUsageFlags = VkImageUsageFlagBits;
pub type VkCompositeAlphaFlagsKHR = VkCompositeAlphaFlagBitsKHR;
pub type VkSurfaceTransformFlagsKHR = VkSurfaceTransformFlagBitsKHR;
pub type VkSwapchainCreateFlagsKHR = VkSwapchainCreateFlagBitsKHR;
pub type VkDebugUtilsMessageTypeFlagsEXT = VkDebugUtilsMessageTypeFlagBitsEXT;
pub type VkDebugUtilsMessageSeverityFlagsEXT = VkDebugUtilsMessageSeverityFlagBitsEXT;
pub type VkAccessFlags = VkAccessFlagBits;
pub type VkImageAspectFlags = VkImageAspectFlagBits;
pub type VkShaderStageFlags = VkShaderStageFlagBits;
pub type VkQueryResultFlags = VkQueryResultFlagBits;
pub type VkQueryControlFlags = VkQueryControlFlagBits;
pub type VkDependencyFlags = VkDependencyFlagBits;
pub type VkPipelineStageFlags = VkPipelineStageFlagBits;
pub type VkStencilFaceFlags = VkStencilFaceFlagBits;
pub type VkCommandBufferResetFlags = VkCommandBufferResetFlagBits;
pub type VkQueryPipelineStatisticFlags = VkQueryPipelineStatisticFlagBits;
pub type VkCommandBufferUsageFlags = VkCommandBufferUsageFlagBits;
pub type VkCommandPoolResetFlags = VkCommandPoolResetFlagBits;
pub type VkCommandPoolCreateFlags = VkCommandPoolCreateFlagBits;
pub type VkSubpassDescriptionFlags = VkSubpassDescriptionFlagBits;
pub type VkAttachmentDescriptionFlags = VkAttachmentDescriptionFlagBits;
pub type VkDescriptorPoolCreateFlags = VkDescriptorPoolCreateFlagBits;
pub type VkDescriptorSetLayoutCreateFlags = VkDescriptorSetLayoutCreateFlagBits;
pub type VkSamplerCreateFlags = VkSamplerCreateFlagBits;
pub type VkPipelineCreateFlags = VkPipelineCreateFlagBits;
pub type VkColorComponentFlags = VkColorComponentFlagBits;
pub type VkCullModeFlags = VkCullModeFlagBits;
pub type VkImageViewCreateFlags = VkImageViewCreateFlagBits;
pub type VkImageCreateFlags = VkImageCreateFlagBits;
pub type VkBufferUsageFlags = VkBufferUsageFlagBits;
pub type VkBufferCreateFlags = VkBufferCreateFlagBits;
pub type VkFenceCreateFlags = VkFenceCreateFlagBits;
pub type VkSparseMemoryBindFlags = VkSparseMemoryBindFlagBits;
pub type VkSparseImageFormatFlags = VkSparseImageFormatFlagBits;
pub type VkDeviceQueueCreateFlags = VkDeviceQueueCreateFlagBits;
pub type VkMemoryHeapFlags = VkMemoryHeapFlagBits;
pub type VkMemoryPropertyFlags = VkMemoryPropertyFlagBits;
pub type VkQueueFlags = VkQueueFlagBits;
pub type VkSampleCountFlags = VkSampleCountFlagBits;
pub type VkFormatFeatureFlags = VkFormatFeatureFlagBits;
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkPhysicalDevice(usize);
impl VkPhysicalDevice
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: usize) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> usize
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkSurfaceKHR(u64);
impl VkSurfaceKHR
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkInstance(usize);
impl VkInstance
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: usize) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> usize
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkSwapchainKHR(u64);
impl VkSwapchainKHR
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkSemaphore(u64);
impl VkSemaphore
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkQueue(usize);
impl VkQueue
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: usize) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> usize
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkFence(u64);
impl VkFence
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkDevice(usize);
impl VkDevice
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: usize) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> usize
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkImage(u64);
impl VkImage
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkDebugUtilsMessengerEXT(u64);
impl VkDebugUtilsMessengerEXT
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkCommandBuffer(usize);
impl VkCommandBuffer
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: usize) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> usize
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkBuffer(u64);
impl VkBuffer
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkFramebuffer(u64);
impl VkFramebuffer
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkRenderPass(u64);
impl VkRenderPass
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkPipelineLayout(u64);
impl VkPipelineLayout
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkQueryPool(u64);
impl VkQueryPool
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkEvent(u64);
impl VkEvent
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkDescriptorSet(u64);
impl VkDescriptorSet
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkPipeline(u64);
impl VkPipeline
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkCommandPool(u64);
impl VkCommandPool
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkImageView(u64);
impl VkImageView
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkBufferView(u64);
impl VkBufferView
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkSampler(u64);
impl VkSampler
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkDescriptorPool(u64);
impl VkDescriptorPool
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkDescriptorSetLayout(u64);
impl VkDescriptorSetLayout
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkShaderModule(u64);
impl VkShaderModule
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkPipelineCache(u64);
impl VkPipelineCache
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialEq, Eq)]
pub struct VkDeviceMemory(u64);
impl VkDeviceMemory
{
#[inline]
pub fn null() -> Self
{
Self(0)
}
#[inline]
pub fn from_raw(r: u64) -> Self
{
Self(r)
}
#[inline]
pub fn as_raw(&self) -> u64
{
self.0
}
}
pub type VkWin32SurfaceCreateFlagsKHR = VkFlags;
pub type VkDebugUtilsMessengerCallbackDataFlagsEXT = VkFlags;
pub type VkDebugUtilsMessengerCreateFlagsEXT = VkFlags;
pub type VkRenderPassCreateFlags = VkFlags;
pub type VkFramebufferCreateFlags = VkFlags;
pub type VkDescriptorPoolResetFlags = VkFlags;
pub type VkPipelineLayoutCreateFlags = VkFlags;
pub type VkPipelineShaderStageCreateFlags = VkFlags;
pub type VkPipelineDynamicStateCreateFlags = VkFlags;
pub type VkPipelineColorBlendStateCreateFlags = VkFlags;
pub type VkPipelineDepthStencilStateCreateFlags = VkFlags;
pub type VkPipelineMultisampleStateCreateFlags = VkFlags;
pub type VkPipelineRasterizationStateCreateFlags = VkFlags;
pub type VkPipelineViewportStateCreateFlags = VkFlags;
pub type VkPipelineTessellationStateCreateFlags = VkFlags;
pub type VkPipelineInputAssemblyStateCreateFlags = VkFlags;
pub type VkPipelineVertexInputStateCreateFlags = VkFlags;
pub type VkPipelineCacheCreateFlags = VkFlags;
pub type VkShaderModuleCreateFlags = VkFlags;
pub type VkBufferViewCreateFlags = VkFlags;
pub type VkQueryPoolCreateFlags = VkFlags;
pub type VkEventCreateFlags = VkFlags;
pub type VkSemaphoreCreateFlags = VkFlags;
pub type VkMemoryMapFlags = VkFlags;
pub type VkDeviceCreateFlags = VkFlags;
pub type VkInstanceCreateFlags = VkFlags;
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkSystemAllocationScope(u32);
impl VkSystemAllocationScope
{
pub const COMMAND: VkSystemAllocationScope = VkSystemAllocationScope(0);
pub const OBJECT: VkSystemAllocationScope = VkSystemAllocationScope(1);
pub const CACHE: VkSystemAllocationScope = VkSystemAllocationScope(2);
pub const DEVICE: VkSystemAllocationScope = VkSystemAllocationScope(3);
pub const INSTANCE: VkSystemAllocationScope = VkSystemAllocationScope(4);
}
impl core::fmt::Debug for VkSystemAllocationScope
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkSystemAllocationScope::COMMAND => write!(f, "VkSystemAllocationScope(COMMAND)"),
VkSystemAllocationScope::OBJECT => write!(f, "VkSystemAllocationScope(OBJECT)"),
VkSystemAllocationScope::CACHE => write!(f, "VkSystemAllocationScope(CACHE)"),
VkSystemAllocationScope::DEVICE => write!(f, "VkSystemAllocationScope(DEVICE)"),
VkSystemAllocationScope::INSTANCE => write!(f, "VkSystemAllocationScope(INSTANCE)"),
_ => write!(f, "VkSystemAllocationScope({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkInternalAllocationType(u32);
impl VkInternalAllocationType
{
pub const EXECUTABLE: VkInternalAllocationType = VkInternalAllocationType(0);
}
impl core::fmt::Debug for VkInternalAllocationType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkInternalAllocationType::EXECUTABLE =>
{
write!(f, "VkInternalAllocationType(EXECUTABLE)")
}
_ => write!(f, "VkInternalAllocationType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkStructureType(u32);
impl VkStructureType
{
pub const APPLICATION_INFO: VkStructureType = VkStructureType(0);
pub const INSTANCE_CREATE_INFO: VkStructureType = VkStructureType(1);
pub const DEVICE_QUEUE_CREATE_INFO: VkStructureType = VkStructureType(2);
pub const DEVICE_CREATE_INFO: VkStructureType = VkStructureType(3);
pub const SUBMIT_INFO: VkStructureType = VkStructureType(4);
pub const MEMORY_ALLOCATE_INFO: VkStructureType = VkStructureType(5);
pub const MAPPED_MEMORY_RANGE: VkStructureType = VkStructureType(6);
pub const BIND_SPARSE_INFO: VkStructureType = VkStructureType(7);
pub const FENCE_CREATE_INFO: VkStructureType = VkStructureType(8);
pub const SEMAPHORE_CREATE_INFO: VkStructureType = VkStructureType(9);
pub const EVENT_CREATE_INFO: VkStructureType = VkStructureType(10);
pub const QUERY_POOL_CREATE_INFO: VkStructureType = VkStructureType(11);
pub const BUFFER_CREATE_INFO: VkStructureType = VkStructureType(12);
pub const BUFFER_VIEW_CREATE_INFO: VkStructureType = VkStructureType(13);
pub const IMAGE_CREATE_INFO: VkStructureType = VkStructureType(14);
pub const IMAGE_VIEW_CREATE_INFO: VkStructureType = VkStructureType(15);
pub const SHADER_MODULE_CREATE_INFO: VkStructureType = VkStructureType(16);
pub const PIPELINE_CACHE_CREATE_INFO: VkStructureType = VkStructureType(17);
pub const PIPELINE_SHADER_STAGE_CREATE_INFO: VkStructureType = VkStructureType(18);
pub const PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO: VkStructureType = VkStructureType(19);
pub const PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO: VkStructureType = VkStructureType(20);
pub const PIPELINE_TESSELLATION_STATE_CREATE_INFO: VkStructureType = VkStructureType(21);
pub const PIPELINE_VIEWPORT_STATE_CREATE_INFO: VkStructureType = VkStructureType(22);
pub const PIPELINE_RASTERIZATION_STATE_CREATE_INFO: VkStructureType = VkStructureType(23);
pub const PIPELINE_MULTISAMPLE_STATE_CREATE_INFO: VkStructureType = VkStructureType(24);
pub const PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO: VkStructureType = VkStructureType(25);
pub const PIPELINE_COLOR_BLEND_STATE_CREATE_INFO: VkStructureType = VkStructureType(26);
pub const PIPELINE_DYNAMIC_STATE_CREATE_INFO: VkStructureType = VkStructureType(27);
pub const GRAPHICS_PIPELINE_CREATE_INFO: VkStructureType = VkStructureType(28);
pub const COMPUTE_PIPELINE_CREATE_INFO: VkStructureType = VkStructureType(29);
pub const PIPELINE_LAYOUT_CREATE_INFO: VkStructureType = VkStructureType(30);
pub const SAMPLER_CREATE_INFO: VkStructureType = VkStructureType(31);
pub const DESCRIPTOR_SET_LAYOUT_CREATE_INFO: VkStructureType = VkStructureType(32);
pub const DESCRIPTOR_POOL_CREATE_INFO: VkStructureType = VkStructureType(33);
pub const DESCRIPTOR_SET_ALLOCATE_INFO: VkStructureType = VkStructureType(34);
pub const WRITE_DESCRIPTOR_SET: VkStructureType = VkStructureType(35);
pub const COPY_DESCRIPTOR_SET: VkStructureType = VkStructureType(36);
pub const FRAMEBUFFER_CREATE_INFO: VkStructureType = VkStructureType(37);
pub const RENDER_PASS_CREATE_INFO: VkStructureType = VkStructureType(38);
pub const COMMAND_POOL_CREATE_INFO: VkStructureType = VkStructureType(39);
pub const COMMAND_BUFFER_ALLOCATE_INFO: VkStructureType = VkStructureType(40);
pub const COMMAND_BUFFER_INHERITANCE_INFO: VkStructureType = VkStructureType(41);
pub const COMMAND_BUFFER_BEGIN_INFO: VkStructureType = VkStructureType(42);
pub const RENDER_PASS_BEGIN_INFO: VkStructureType = VkStructureType(43);
pub const BUFFER_MEMORY_BARRIER: VkStructureType = VkStructureType(44);
pub const IMAGE_MEMORY_BARRIER: VkStructureType = VkStructureType(45);
pub const MEMORY_BARRIER: VkStructureType = VkStructureType(46);
pub const LOADER_INSTANCE_CREATE_INFO: VkStructureType = VkStructureType(47);
pub const LOADER_DEVICE_CREATE_INFO: VkStructureType = VkStructureType(48);
pub const SWAPCHAIN_CREATE_INFO_KHR: VkStructureType = VkStructureType(1000001000);
pub const PRESENT_INFO_KHR: VkStructureType = VkStructureType(1000001001);
pub const WIN32_SURFACE_CREATE_INFO_KHR: VkStructureType = VkStructureType(1000009000);
pub const DEBUG_UTILS_OBJECT_NAME_INFO_EXT: VkStructureType = VkStructureType(1000128000);
pub const DEBUG_UTILS_OBJECT_TAG_INFO_EXT: VkStructureType = VkStructureType(1000128001);
pub const DEBUG_UTILS_LABEL_EXT: VkStructureType = VkStructureType(1000128002);
pub const DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT: VkStructureType =
VkStructureType(1000128003);
pub const DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT: VkStructureType = VkStructureType(1000128004);
}
impl core::fmt::Debug for VkStructureType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkStructureType::APPLICATION_INFO => write!(f, "VkStructureType(APPLICATION_INFO)"),
VkStructureType::INSTANCE_CREATE_INFO =>
{
write!(f, "VkStructureType(INSTANCE_CREATE_INFO)")
}
VkStructureType::DEVICE_QUEUE_CREATE_INFO =>
{
write!(f, "VkStructureType(DEVICE_QUEUE_CREATE_INFO)")
}
VkStructureType::DEVICE_CREATE_INFO => write!(f, "VkStructureType(DEVICE_CREATE_INFO)"),
VkStructureType::SUBMIT_INFO => write!(f, "VkStructureType(SUBMIT_INFO)"),
VkStructureType::MEMORY_ALLOCATE_INFO =>
{
write!(f, "VkStructureType(MEMORY_ALLOCATE_INFO)")
}
VkStructureType::MAPPED_MEMORY_RANGE =>
{
write!(f, "VkStructureType(MAPPED_MEMORY_RANGE)")
}
VkStructureType::BIND_SPARSE_INFO => write!(f, "VkStructureType(BIND_SPARSE_INFO)"),
VkStructureType::FENCE_CREATE_INFO => write!(f, "VkStructureType(FENCE_CREATE_INFO)"),
VkStructureType::SEMAPHORE_CREATE_INFO =>
{
write!(f, "VkStructureType(SEMAPHORE_CREATE_INFO)")
}
VkStructureType::EVENT_CREATE_INFO => write!(f, "VkStructureType(EVENT_CREATE_INFO)"),
VkStructureType::QUERY_POOL_CREATE_INFO =>
{
write!(f, "VkStructureType(QUERY_POOL_CREATE_INFO)")
}
VkStructureType::BUFFER_CREATE_INFO => write!(f, "VkStructureType(BUFFER_CREATE_INFO)"),
VkStructureType::BUFFER_VIEW_CREATE_INFO =>
{
write!(f, "VkStructureType(BUFFER_VIEW_CREATE_INFO)")
}
VkStructureType::IMAGE_CREATE_INFO => write!(f, "VkStructureType(IMAGE_CREATE_INFO)"),
VkStructureType::IMAGE_VIEW_CREATE_INFO =>
{
write!(f, "VkStructureType(IMAGE_VIEW_CREATE_INFO)")
}
VkStructureType::SHADER_MODULE_CREATE_INFO =>
{
write!(f, "VkStructureType(SHADER_MODULE_CREATE_INFO)")
}
VkStructureType::PIPELINE_CACHE_CREATE_INFO =>
{
write!(f, "VkStructureType(PIPELINE_CACHE_CREATE_INFO)")
}
VkStructureType::PIPELINE_SHADER_STAGE_CREATE_INFO =>
{
write!(f, "VkStructureType(PIPELINE_SHADER_STAGE_CREATE_INFO)")
}
VkStructureType::PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO => write!(
f,
"VkStructureType(PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO)"
),
VkStructureType::PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO => write!(
f,
"VkStructureType(PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO)"
),
VkStructureType::PIPELINE_TESSELLATION_STATE_CREATE_INFO => write!(
f,
"VkStructureType(PIPELINE_TESSELLATION_STATE_CREATE_INFO)"
),
VkStructureType::PIPELINE_VIEWPORT_STATE_CREATE_INFO =>
{
write!(f, "VkStructureType(PIPELINE_VIEWPORT_STATE_CREATE_INFO)")
}
VkStructureType::PIPELINE_RASTERIZATION_STATE_CREATE_INFO => write!(
f,
"VkStructureType(PIPELINE_RASTERIZATION_STATE_CREATE_INFO)"
),
VkStructureType::PIPELINE_MULTISAMPLE_STATE_CREATE_INFO =>
{
write!(f, "VkStructureType(PIPELINE_MULTISAMPLE_STATE_CREATE_INFO)")
}
VkStructureType::PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO => write!(
f,
"VkStructureType(PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO)"
),
VkStructureType::PIPELINE_COLOR_BLEND_STATE_CREATE_INFO =>
{
write!(f, "VkStructureType(PIPELINE_COLOR_BLEND_STATE_CREATE_INFO)")
}
VkStructureType::PIPELINE_DYNAMIC_STATE_CREATE_INFO =>
{
write!(f, "VkStructureType(PIPELINE_DYNAMIC_STATE_CREATE_INFO)")
}
VkStructureType::GRAPHICS_PIPELINE_CREATE_INFO =>
{
write!(f, "VkStructureType(GRAPHICS_PIPELINE_CREATE_INFO)")
}
VkStructureType::COMPUTE_PIPELINE_CREATE_INFO =>
{
write!(f, "VkStructureType(COMPUTE_PIPELINE_CREATE_INFO)")
}
VkStructureType::PIPELINE_LAYOUT_CREATE_INFO =>
{
write!(f, "VkStructureType(PIPELINE_LAYOUT_CREATE_INFO)")
}
VkStructureType::SAMPLER_CREATE_INFO =>
{
write!(f, "VkStructureType(SAMPLER_CREATE_INFO)")
}
VkStructureType::DESCRIPTOR_SET_LAYOUT_CREATE_INFO =>
{
write!(f, "VkStructureType(DESCRIPTOR_SET_LAYOUT_CREATE_INFO)")
}
VkStructureType::DESCRIPTOR_POOL_CREATE_INFO =>
{
write!(f, "VkStructureType(DESCRIPTOR_POOL_CREATE_INFO)")
}
VkStructureType::DESCRIPTOR_SET_ALLOCATE_INFO =>
{
write!(f, "VkStructureType(DESCRIPTOR_SET_ALLOCATE_INFO)")
}
VkStructureType::WRITE_DESCRIPTOR_SET =>
{
write!(f, "VkStructureType(WRITE_DESCRIPTOR_SET)")
}
VkStructureType::COPY_DESCRIPTOR_SET =>
{
write!(f, "VkStructureType(COPY_DESCRIPTOR_SET)")
}
VkStructureType::FRAMEBUFFER_CREATE_INFO =>
{
write!(f, "VkStructureType(FRAMEBUFFER_CREATE_INFO)")
}
VkStructureType::RENDER_PASS_CREATE_INFO =>
{
write!(f, "VkStructureType(RENDER_PASS_CREATE_INFO)")
}
VkStructureType::COMMAND_POOL_CREATE_INFO =>
{
write!(f, "VkStructureType(COMMAND_POOL_CREATE_INFO)")
}
VkStructureType::COMMAND_BUFFER_ALLOCATE_INFO =>
{
write!(f, "VkStructureType(COMMAND_BUFFER_ALLOCATE_INFO)")
}
VkStructureType::COMMAND_BUFFER_INHERITANCE_INFO =>
{
write!(f, "VkStructureType(COMMAND_BUFFER_INHERITANCE_INFO)")
}
VkStructureType::COMMAND_BUFFER_BEGIN_INFO =>
{
write!(f, "VkStructureType(COMMAND_BUFFER_BEGIN_INFO)")
}
VkStructureType::RENDER_PASS_BEGIN_INFO =>
{
write!(f, "VkStructureType(RENDER_PASS_BEGIN_INFO)")
}
VkStructureType::BUFFER_MEMORY_BARRIER =>
{
write!(f, "VkStructureType(BUFFER_MEMORY_BARRIER)")
}
VkStructureType::IMAGE_MEMORY_BARRIER =>
{
write!(f, "VkStructureType(IMAGE_MEMORY_BARRIER)")
}
VkStructureType::MEMORY_BARRIER => write!(f, "VkStructureType(MEMORY_BARRIER)"),
VkStructureType::LOADER_INSTANCE_CREATE_INFO =>
{
write!(f, "VkStructureType(LOADER_INSTANCE_CREATE_INFO)")
}
VkStructureType::LOADER_DEVICE_CREATE_INFO =>
{
write!(f, "VkStructureType(LOADER_DEVICE_CREATE_INFO)")
}
VkStructureType::SWAPCHAIN_CREATE_INFO_KHR =>
{
write!(f, "VkStructureType(SWAPCHAIN_CREATE_INFO_KHR)")
}
VkStructureType::PRESENT_INFO_KHR => write!(f, "VkStructureType(PRESENT_INFO_KHR)"),
VkStructureType::WIN32_SURFACE_CREATE_INFO_KHR =>
{
write!(f, "VkStructureType(WIN32_SURFACE_CREATE_INFO_KHR)")
}
VkStructureType::DEBUG_UTILS_OBJECT_NAME_INFO_EXT =>
{
write!(f, "VkStructureType(DEBUG_UTILS_OBJECT_NAME_INFO_EXT)")
}
VkStructureType::DEBUG_UTILS_OBJECT_TAG_INFO_EXT =>
{
write!(f, "VkStructureType(DEBUG_UTILS_OBJECT_TAG_INFO_EXT)")
}
VkStructureType::DEBUG_UTILS_LABEL_EXT =>
{
write!(f, "VkStructureType(DEBUG_UTILS_LABEL_EXT)")
}
VkStructureType::DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT => write!(
f,
"VkStructureType(DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT)"
),
VkStructureType::DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT =>
{
write!(f, "VkStructureType(DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT)")
}
_ => write!(f, "VkStructureType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkResult(u32);
impl VkResult
{
pub const ERROR_OUT_OF_DATE_KHR: VkResult = VkResult(-1000001004i32 as u32);
pub const ERROR_NATIVE_WINDOW_IN_USE_KHR: VkResult = VkResult(-1000000001i32 as u32);
pub const ERROR_SURFACE_LOST_KHR: VkResult = VkResult(-1000000000i32 as u32);
pub const ERROR_FRAGMENTED_POOL: VkResult = VkResult(-12i32 as u32);
pub const ERROR_FORMAT_NOT_SUPPORTED: VkResult = VkResult(-11i32 as u32);
pub const ERROR_TOO_MANY_OBJECTS: VkResult = VkResult(-10i32 as u32);
pub const ERROR_INCOMPATIBLE_DRIVER: VkResult = VkResult(-9i32 as u32);
pub const ERROR_FEATURE_NOT_PRESENT: VkResult = VkResult(-8i32 as u32);
pub const ERROR_EXTENSION_NOT_PRESENT: VkResult = VkResult(-7i32 as u32);
pub const ERROR_LAYER_NOT_PRESENT: VkResult = VkResult(-6i32 as u32);
pub const ERROR_MEMORY_MAP_FAILED: VkResult = VkResult(-5i32 as u32);
pub const ERROR_DEVICE_LOST: VkResult = VkResult(-4i32 as u32);
pub const ERROR_INITIALIZATION_FAILED: VkResult = VkResult(-3i32 as u32);
pub const ERROR_OUT_OF_DEVICE_MEMORY: VkResult = VkResult(-2i32 as u32);
pub const ERROR_OUT_OF_HOST_MEMORY: VkResult = VkResult(-1i32 as u32);
pub const SUCCESS: VkResult = VkResult(0);
pub const NOT_READY: VkResult = VkResult(1);
pub const TIMEOUT: VkResult = VkResult(2);
pub const EVENT_SET: VkResult = VkResult(3);
pub const EVENT_RESET: VkResult = VkResult(4);
pub const INCOMPLETE: VkResult = VkResult(5);
pub const SUBOPTIMAL_KHR: VkResult = VkResult(1000001003);
}
impl core::fmt::Debug for VkResult
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkResult::ERROR_OUT_OF_DATE_KHR => write!(f, "VkResult(ERROR_OUT_OF_DATE_KHR)"),
VkResult::ERROR_NATIVE_WINDOW_IN_USE_KHR =>
{
write!(f, "VkResult(ERROR_NATIVE_WINDOW_IN_USE_KHR)")
}
VkResult::ERROR_SURFACE_LOST_KHR => write!(f, "VkResult(ERROR_SURFACE_LOST_KHR)"),
VkResult::ERROR_FRAGMENTED_POOL => write!(f, "VkResult(ERROR_FRAGMENTED_POOL)"),
VkResult::ERROR_FORMAT_NOT_SUPPORTED =>
{
write!(f, "VkResult(ERROR_FORMAT_NOT_SUPPORTED)")
}
VkResult::ERROR_TOO_MANY_OBJECTS => write!(f, "VkResult(ERROR_TOO_MANY_OBJECTS)"),
VkResult::ERROR_INCOMPATIBLE_DRIVER => write!(f, "VkResult(ERROR_INCOMPATIBLE_DRIVER)"),
VkResult::ERROR_FEATURE_NOT_PRESENT => write!(f, "VkResult(ERROR_FEATURE_NOT_PRESENT)"),
VkResult::ERROR_EXTENSION_NOT_PRESENT =>
{
write!(f, "VkResult(ERROR_EXTENSION_NOT_PRESENT)")
}
VkResult::ERROR_LAYER_NOT_PRESENT => write!(f, "VkResult(ERROR_LAYER_NOT_PRESENT)"),
VkResult::ERROR_MEMORY_MAP_FAILED => write!(f, "VkResult(ERROR_MEMORY_MAP_FAILED)"),
VkResult::ERROR_DEVICE_LOST => write!(f, "VkResult(ERROR_DEVICE_LOST)"),
VkResult::ERROR_INITIALIZATION_FAILED =>
{
write!(f, "VkResult(ERROR_INITIALIZATION_FAILED)")
}
VkResult::ERROR_OUT_OF_DEVICE_MEMORY =>
{
write!(f, "VkResult(ERROR_OUT_OF_DEVICE_MEMORY)")
}
VkResult::ERROR_OUT_OF_HOST_MEMORY => write!(f, "VkResult(ERROR_OUT_OF_HOST_MEMORY)"),
VkResult::SUCCESS => write!(f, "VkResult(SUCCESS)"),
VkResult::NOT_READY => write!(f, "VkResult(NOT_READY)"),
VkResult::TIMEOUT => write!(f, "VkResult(TIMEOUT)"),
VkResult::EVENT_SET => write!(f, "VkResult(EVENT_SET)"),
VkResult::EVENT_RESET => write!(f, "VkResult(EVENT_RESET)"),
VkResult::INCOMPLETE => write!(f, "VkResult(INCOMPLETE)"),
VkResult::SUBOPTIMAL_KHR => write!(f, "VkResult(SUBOPTIMAL_KHR)"),
_ => write!(f, "VkResult({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkPresentModeKHR(u32);
impl VkPresentModeKHR
{
pub const IMMEDIATE_KHR: VkPresentModeKHR = VkPresentModeKHR(0);
pub const MAILBOX_KHR: VkPresentModeKHR = VkPresentModeKHR(1);
pub const FIFO_KHR: VkPresentModeKHR = VkPresentModeKHR(2);
pub const FIFO_RELAXED_KHR: VkPresentModeKHR = VkPresentModeKHR(3);
}
impl core::fmt::Debug for VkPresentModeKHR
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkPresentModeKHR::IMMEDIATE_KHR => write!(f, "VkPresentModeKHR(IMMEDIATE_KHR)"),
VkPresentModeKHR::MAILBOX_KHR => write!(f, "VkPresentModeKHR(MAILBOX_KHR)"),
VkPresentModeKHR::FIFO_KHR => write!(f, "VkPresentModeKHR(FIFO_KHR)"),
VkPresentModeKHR::FIFO_RELAXED_KHR => write!(f, "VkPresentModeKHR(FIFO_RELAXED_KHR)"),
_ => write!(f, "VkPresentModeKHR({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkColorSpaceKHR(u32);
impl VkColorSpaceKHR
{
pub const SRGB_NONLINEAR_KHR: VkColorSpaceKHR = VkColorSpaceKHR(0);
pub const VK_COLORSPACE_SRGB_NONLINEAR_KHR: VkColorSpaceKHR = VkColorSpaceKHR(0);
}
impl core::fmt::Debug for VkColorSpaceKHR
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkColorSpaceKHR::SRGB_NONLINEAR_KHR => write!(f, "VkColorSpaceKHR(SRGB_NONLINEAR_KHR)"),
VkColorSpaceKHR::VK_COLORSPACE_SRGB_NONLINEAR_KHR =>
{
write!(f, "VkColorSpaceKHR(VK_COLORSPACE_SRGB_NONLINEAR_KHR)")
}
_ => write!(f, "VkColorSpaceKHR({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkFormat(u32);
impl VkFormat
{
pub const UNDEFINED: VkFormat = VkFormat(0);
pub const R4G4_UNORM_PACK8: VkFormat = VkFormat(1);
pub const R4G4B4A4_UNORM_PACK16: VkFormat = VkFormat(2);
pub const B4G4R4A4_UNORM_PACK16: VkFormat = VkFormat(3);
pub const R5G6B5_UNORM_PACK16: VkFormat = VkFormat(4);
pub const B5G6R5_UNORM_PACK16: VkFormat = VkFormat(5);
pub const R5G5B5A1_UNORM_PACK16: VkFormat = VkFormat(6);
pub const B5G5R5A1_UNORM_PACK16: VkFormat = VkFormat(7);
pub const A1R5G5B5_UNORM_PACK16: VkFormat = VkFormat(8);
pub const R8_UNORM: VkFormat = VkFormat(9);
pub const R8_SNORM: VkFormat = VkFormat(10);
pub const R8_USCALED: VkFormat = VkFormat(11);
pub const R8_SSCALED: VkFormat = VkFormat(12);
pub const R8_UINT: VkFormat = VkFormat(13);
pub const R8_SINT: VkFormat = VkFormat(14);
pub const R8_SRGB: VkFormat = VkFormat(15);
pub const R8G8_UNORM: VkFormat = VkFormat(16);
pub const R8G8_SNORM: VkFormat = VkFormat(17);
pub const R8G8_USCALED: VkFormat = VkFormat(18);
pub const R8G8_SSCALED: VkFormat = VkFormat(19);
pub const R8G8_UINT: VkFormat = VkFormat(20);
pub const R8G8_SINT: VkFormat = VkFormat(21);
pub const R8G8_SRGB: VkFormat = VkFormat(22);
pub const R8G8B8_UNORM: VkFormat = VkFormat(23);
pub const R8G8B8_SNORM: VkFormat = VkFormat(24);
pub const R8G8B8_USCALED: VkFormat = VkFormat(25);
pub const R8G8B8_SSCALED: VkFormat = VkFormat(26);
pub const R8G8B8_UINT: VkFormat = VkFormat(27);
pub const R8G8B8_SINT: VkFormat = VkFormat(28);
pub const R8G8B8_SRGB: VkFormat = VkFormat(29);
pub const B8G8R8_UNORM: VkFormat = VkFormat(30);
pub const B8G8R8_SNORM: VkFormat = VkFormat(31);
pub const B8G8R8_USCALED: VkFormat = VkFormat(32);
pub const B8G8R8_SSCALED: VkFormat = VkFormat(33);
pub const B8G8R8_UINT: VkFormat = VkFormat(34);
pub const B8G8R8_SINT: VkFormat = VkFormat(35);
pub const B8G8R8_SRGB: VkFormat = VkFormat(36);
pub const R8G8B8A8_UNORM: VkFormat = VkFormat(37);
pub const R8G8B8A8_SNORM: VkFormat = VkFormat(38);
pub const R8G8B8A8_USCALED: VkFormat = VkFormat(39);
pub const R8G8B8A8_SSCALED: VkFormat = VkFormat(40);
pub const R8G8B8A8_UINT: VkFormat = VkFormat(41);
pub const R8G8B8A8_SINT: VkFormat = VkFormat(42);
pub const R8G8B8A8_SRGB: VkFormat = VkFormat(43);
pub const B8G8R8A8_UNORM: VkFormat = VkFormat(44);
pub const B8G8R8A8_SNORM: VkFormat = VkFormat(45);
pub const B8G8R8A8_USCALED: VkFormat = VkFormat(46);
pub const B8G8R8A8_SSCALED: VkFormat = VkFormat(47);
pub const B8G8R8A8_UINT: VkFormat = VkFormat(48);
pub const B8G8R8A8_SINT: VkFormat = VkFormat(49);
pub const B8G8R8A8_SRGB: VkFormat = VkFormat(50);
pub const A8B8G8R8_UNORM_PACK32: VkFormat = VkFormat(51);
pub const A8B8G8R8_SNORM_PACK32: VkFormat = VkFormat(52);
pub const A8B8G8R8_USCALED_PACK32: VkFormat = VkFormat(53);
pub const A8B8G8R8_SSCALED_PACK32: VkFormat = VkFormat(54);
pub const A8B8G8R8_UINT_PACK32: VkFormat = VkFormat(55);
pub const A8B8G8R8_SINT_PACK32: VkFormat = VkFormat(56);
pub const A8B8G8R8_SRGB_PACK32: VkFormat = VkFormat(57);
pub const A2R10G10B10_UNORM_PACK32: VkFormat = VkFormat(58);
pub const A2R10G10B10_SNORM_PACK32: VkFormat = VkFormat(59);
pub const A2R10G10B10_USCALED_PACK32: VkFormat = VkFormat(60);
pub const A2R10G10B10_SSCALED_PACK32: VkFormat = VkFormat(61);
pub const A2R10G10B10_UINT_PACK32: VkFormat = VkFormat(62);
pub const A2R10G10B10_SINT_PACK32: VkFormat = VkFormat(63);
pub const A2B10G10R10_UNORM_PACK32: VkFormat = VkFormat(64);
pub const A2B10G10R10_SNORM_PACK32: VkFormat = VkFormat(65);
pub const A2B10G10R10_USCALED_PACK32: VkFormat = VkFormat(66);
pub const A2B10G10R10_SSCALED_PACK32: VkFormat = VkFormat(67);
pub const A2B10G10R10_UINT_PACK32: VkFormat = VkFormat(68);
pub const A2B10G10R10_SINT_PACK32: VkFormat = VkFormat(69);
pub const R16_UNORM: VkFormat = VkFormat(70);
pub const R16_SNORM: VkFormat = VkFormat(71);
pub const R16_USCALED: VkFormat = VkFormat(72);
pub const R16_SSCALED: VkFormat = VkFormat(73);
pub const R16_UINT: VkFormat = VkFormat(74);
pub const R16_SINT: VkFormat = VkFormat(75);
pub const R16_SFLOAT: VkFormat = VkFormat(76);
pub const R16G16_UNORM: VkFormat = VkFormat(77);
pub const R16G16_SNORM: VkFormat = VkFormat(78);
pub const R16G16_USCALED: VkFormat = VkFormat(79);
pub const R16G16_SSCALED: VkFormat = VkFormat(80);
pub const R16G16_UINT: VkFormat = VkFormat(81);
pub const R16G16_SINT: VkFormat = VkFormat(82);
pub const R16G16_SFLOAT: VkFormat = VkFormat(83);
pub const R16G16B16_UNORM: VkFormat = VkFormat(84);
pub const R16G16B16_SNORM: VkFormat = VkFormat(85);
pub const R16G16B16_USCALED: VkFormat = VkFormat(86);
pub const R16G16B16_SSCALED: VkFormat = VkFormat(87);
pub const R16G16B16_UINT: VkFormat = VkFormat(88);
pub const R16G16B16_SINT: VkFormat = VkFormat(89);
pub const R16G16B16_SFLOAT: VkFormat = VkFormat(90);
pub const R16G16B16A16_UNORM: VkFormat = VkFormat(91);
pub const R16G16B16A16_SNORM: VkFormat = VkFormat(92);
pub const R16G16B16A16_USCALED: VkFormat = VkFormat(93);
pub const R16G16B16A16_SSCALED: VkFormat = VkFormat(94);
pub const R16G16B16A16_UINT: VkFormat = VkFormat(95);
pub const R16G16B16A16_SINT: VkFormat = VkFormat(96);
pub const R16G16B16A16_SFLOAT: VkFormat = VkFormat(97);
pub const R32_UINT: VkFormat = VkFormat(98);
pub const R32_SINT: VkFormat = VkFormat(99);
pub const R32_SFLOAT: VkFormat = VkFormat(100);
pub const R32G32_UINT: VkFormat = VkFormat(101);
pub const R32G32_SINT: VkFormat = VkFormat(102);
pub const R32G32_SFLOAT: VkFormat = VkFormat(103);
pub const R32G32B32_UINT: VkFormat = VkFormat(104);
pub const R32G32B32_SINT: VkFormat = VkFormat(105);
pub const R32G32B32_SFLOAT: VkFormat = VkFormat(106);
pub const R32G32B32A32_UINT: VkFormat = VkFormat(107);
pub const R32G32B32A32_SINT: VkFormat = VkFormat(108);
pub const R32G32B32A32_SFLOAT: VkFormat = VkFormat(109);
pub const R64_UINT: VkFormat = VkFormat(110);
pub const R64_SINT: VkFormat = VkFormat(111);
pub const R64_SFLOAT: VkFormat = VkFormat(112);
pub const R64G64_UINT: VkFormat = VkFormat(113);
pub const R64G64_SINT: VkFormat = VkFormat(114);
pub const R64G64_SFLOAT: VkFormat = VkFormat(115);
pub const R64G64B64_UINT: VkFormat = VkFormat(116);
pub const R64G64B64_SINT: VkFormat = VkFormat(117);
pub const R64G64B64_SFLOAT: VkFormat = VkFormat(118);
pub const R64G64B64A64_UINT: VkFormat = VkFormat(119);
pub const R64G64B64A64_SINT: VkFormat = VkFormat(120);
pub const R64G64B64A64_SFLOAT: VkFormat = VkFormat(121);
pub const B10G11R11_UFLOAT_PACK32: VkFormat = VkFormat(122);
pub const E5B9G9R9_UFLOAT_PACK32: VkFormat = VkFormat(123);
pub const D16_UNORM: VkFormat = VkFormat(124);
pub const X8_D24_UNORM_PACK32: VkFormat = VkFormat(125);
pub const D32_SFLOAT: VkFormat = VkFormat(126);
pub const S8_UINT: VkFormat = VkFormat(127);
pub const D16_UNORM_S8_UINT: VkFormat = VkFormat(128);
pub const D24_UNORM_S8_UINT: VkFormat = VkFormat(129);
pub const D32_SFLOAT_S8_UINT: VkFormat = VkFormat(130);
pub const BC1_RGB_UNORM_BLOCK: VkFormat = VkFormat(131);
pub const BC1_RGB_SRGB_BLOCK: VkFormat = VkFormat(132);
pub const BC1_RGBA_UNORM_BLOCK: VkFormat = VkFormat(133);
pub const BC1_RGBA_SRGB_BLOCK: VkFormat = VkFormat(134);
pub const BC2_UNORM_BLOCK: VkFormat = VkFormat(135);
pub const BC2_SRGB_BLOCK: VkFormat = VkFormat(136);
pub const BC3_UNORM_BLOCK: VkFormat = VkFormat(137);
pub const BC3_SRGB_BLOCK: VkFormat = VkFormat(138);
pub const BC4_UNORM_BLOCK: VkFormat = VkFormat(139);
pub const BC4_SNORM_BLOCK: VkFormat = VkFormat(140);
pub const BC5_UNORM_BLOCK: VkFormat = VkFormat(141);
pub const BC5_SNORM_BLOCK: VkFormat = VkFormat(142);
pub const BC6H_UFLOAT_BLOCK: VkFormat = VkFormat(143);
pub const BC6H_SFLOAT_BLOCK: VkFormat = VkFormat(144);
pub const BC7_UNORM_BLOCK: VkFormat = VkFormat(145);
pub const BC7_SRGB_BLOCK: VkFormat = VkFormat(146);
pub const ETC2_R8G8B8_UNORM_BLOCK: VkFormat = VkFormat(147);
pub const ETC2_R8G8B8_SRGB_BLOCK: VkFormat = VkFormat(148);
pub const ETC2_R8G8B8A1_UNORM_BLOCK: VkFormat = VkFormat(149);
pub const ETC2_R8G8B8A1_SRGB_BLOCK: VkFormat = VkFormat(150);
pub const ETC2_R8G8B8A8_UNORM_BLOCK: VkFormat = VkFormat(151);
pub const ETC2_R8G8B8A8_SRGB_BLOCK: VkFormat = VkFormat(152);
pub const EAC_R11_UNORM_BLOCK: VkFormat = VkFormat(153);
pub const EAC_R11_SNORM_BLOCK: VkFormat = VkFormat(154);
pub const EAC_R11G11_UNORM_BLOCK: VkFormat = VkFormat(155);
pub const EAC_R11G11_SNORM_BLOCK: VkFormat = VkFormat(156);
pub const ASTC_4X4_UNORM_BLOCK: VkFormat = VkFormat(157);
pub const ASTC_4X4_SRGB_BLOCK: VkFormat = VkFormat(158);
pub const ASTC_5X4_UNORM_BLOCK: VkFormat = VkFormat(159);
pub const ASTC_5X4_SRGB_BLOCK: VkFormat = VkFormat(160);
pub const ASTC_5X5_UNORM_BLOCK: VkFormat = VkFormat(161);
pub const ASTC_5X5_SRGB_BLOCK: VkFormat = VkFormat(162);
pub const ASTC_6X5_UNORM_BLOCK: VkFormat = VkFormat(163);
pub const ASTC_6X5_SRGB_BLOCK: VkFormat = VkFormat(164);
pub const ASTC_6X6_UNORM_BLOCK: VkFormat = VkFormat(165);
pub const ASTC_6X6_SRGB_BLOCK: VkFormat = VkFormat(166);
pub const ASTC_8X5_UNORM_BLOCK: VkFormat = VkFormat(167);
pub const ASTC_8X5_SRGB_BLOCK: VkFormat = VkFormat(168);
pub const ASTC_8X6_UNORM_BLOCK: VkFormat = VkFormat(169);
pub const ASTC_8X6_SRGB_BLOCK: VkFormat = VkFormat(170);
pub const ASTC_8X8_UNORM_BLOCK: VkFormat = VkFormat(171);
pub const ASTC_8X8_SRGB_BLOCK: VkFormat = VkFormat(172);
pub const ASTC_10X5_UNORM_BLOCK: VkFormat = VkFormat(173);
pub const ASTC_10X5_SRGB_BLOCK: VkFormat = VkFormat(174);
pub const ASTC_10X6_UNORM_BLOCK: VkFormat = VkFormat(175);
pub const ASTC_10X6_SRGB_BLOCK: VkFormat = VkFormat(176);
pub const ASTC_10X8_UNORM_BLOCK: VkFormat = VkFormat(177);
pub const ASTC_10X8_SRGB_BLOCK: VkFormat = VkFormat(178);
pub const ASTC_10X10_UNORM_BLOCK: VkFormat = VkFormat(179);
pub const ASTC_10X10_SRGB_BLOCK: VkFormat = VkFormat(180);
pub const ASTC_12X10_UNORM_BLOCK: VkFormat = VkFormat(181);
pub const ASTC_12X10_SRGB_BLOCK: VkFormat = VkFormat(182);
pub const ASTC_12X12_UNORM_BLOCK: VkFormat = VkFormat(183);
pub const ASTC_12X12_SRGB_BLOCK: VkFormat = VkFormat(184);
}
impl core::fmt::Debug for VkFormat
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkFormat::UNDEFINED => write!(f, "VkFormat(UNDEFINED)"),
VkFormat::R4G4_UNORM_PACK8 => write!(f, "VkFormat(R4G4_UNORM_PACK8)"),
VkFormat::R4G4B4A4_UNORM_PACK16 => write!(f, "VkFormat(R4G4B4A4_UNORM_PACK16)"),
VkFormat::B4G4R4A4_UNORM_PACK16 => write!(f, "VkFormat(B4G4R4A4_UNORM_PACK16)"),
VkFormat::R5G6B5_UNORM_PACK16 => write!(f, "VkFormat(R5G6B5_UNORM_PACK16)"),
VkFormat::B5G6R5_UNORM_PACK16 => write!(f, "VkFormat(B5G6R5_UNORM_PACK16)"),
VkFormat::R5G5B5A1_UNORM_PACK16 => write!(f, "VkFormat(R5G5B5A1_UNORM_PACK16)"),
VkFormat::B5G5R5A1_UNORM_PACK16 => write!(f, "VkFormat(B5G5R5A1_UNORM_PACK16)"),
VkFormat::A1R5G5B5_UNORM_PACK16 => write!(f, "VkFormat(A1R5G5B5_UNORM_PACK16)"),
VkFormat::R8_UNORM => write!(f, "VkFormat(R8_UNORM)"),
VkFormat::R8_SNORM => write!(f, "VkFormat(R8_SNORM)"),
VkFormat::R8_USCALED => write!(f, "VkFormat(R8_USCALED)"),
VkFormat::R8_SSCALED => write!(f, "VkFormat(R8_SSCALED)"),
VkFormat::R8_UINT => write!(f, "VkFormat(R8_UINT)"),
VkFormat::R8_SINT => write!(f, "VkFormat(R8_SINT)"),
VkFormat::R8_SRGB => write!(f, "VkFormat(R8_SRGB)"),
VkFormat::R8G8_UNORM => write!(f, "VkFormat(R8G8_UNORM)"),
VkFormat::R8G8_SNORM => write!(f, "VkFormat(R8G8_SNORM)"),
VkFormat::R8G8_USCALED => write!(f, "VkFormat(R8G8_USCALED)"),
VkFormat::R8G8_SSCALED => write!(f, "VkFormat(R8G8_SSCALED)"),
VkFormat::R8G8_UINT => write!(f, "VkFormat(R8G8_UINT)"),
VkFormat::R8G8_SINT => write!(f, "VkFormat(R8G8_SINT)"),
VkFormat::R8G8_SRGB => write!(f, "VkFormat(R8G8_SRGB)"),
VkFormat::R8G8B8_UNORM => write!(f, "VkFormat(R8G8B8_UNORM)"),
VkFormat::R8G8B8_SNORM => write!(f, "VkFormat(R8G8B8_SNORM)"),
VkFormat::R8G8B8_USCALED => write!(f, "VkFormat(R8G8B8_USCALED)"),
VkFormat::R8G8B8_SSCALED => write!(f, "VkFormat(R8G8B8_SSCALED)"),
VkFormat::R8G8B8_UINT => write!(f, "VkFormat(R8G8B8_UINT)"),
VkFormat::R8G8B8_SINT => write!(f, "VkFormat(R8G8B8_SINT)"),
VkFormat::R8G8B8_SRGB => write!(f, "VkFormat(R8G8B8_SRGB)"),
VkFormat::B8G8R8_UNORM => write!(f, "VkFormat(B8G8R8_UNORM)"),
VkFormat::B8G8R8_SNORM => write!(f, "VkFormat(B8G8R8_SNORM)"),
VkFormat::B8G8R8_USCALED => write!(f, "VkFormat(B8G8R8_USCALED)"),
VkFormat::B8G8R8_SSCALED => write!(f, "VkFormat(B8G8R8_SSCALED)"),
VkFormat::B8G8R8_UINT => write!(f, "VkFormat(B8G8R8_UINT)"),
VkFormat::B8G8R8_SINT => write!(f, "VkFormat(B8G8R8_SINT)"),
VkFormat::B8G8R8_SRGB => write!(f, "VkFormat(B8G8R8_SRGB)"),
VkFormat::R8G8B8A8_UNORM => write!(f, "VkFormat(R8G8B8A8_UNORM)"),
VkFormat::R8G8B8A8_SNORM => write!(f, "VkFormat(R8G8B8A8_SNORM)"),
VkFormat::R8G8B8A8_USCALED => write!(f, "VkFormat(R8G8B8A8_USCALED)"),
VkFormat::R8G8B8A8_SSCALED => write!(f, "VkFormat(R8G8B8A8_SSCALED)"),
VkFormat::R8G8B8A8_UINT => write!(f, "VkFormat(R8G8B8A8_UINT)"),
VkFormat::R8G8B8A8_SINT => write!(f, "VkFormat(R8G8B8A8_SINT)"),
VkFormat::R8G8B8A8_SRGB => write!(f, "VkFormat(R8G8B8A8_SRGB)"),
VkFormat::B8G8R8A8_UNORM => write!(f, "VkFormat(B8G8R8A8_UNORM)"),
VkFormat::B8G8R8A8_SNORM => write!(f, "VkFormat(B8G8R8A8_SNORM)"),
VkFormat::B8G8R8A8_USCALED => write!(f, "VkFormat(B8G8R8A8_USCALED)"),
VkFormat::B8G8R8A8_SSCALED => write!(f, "VkFormat(B8G8R8A8_SSCALED)"),
VkFormat::B8G8R8A8_UINT => write!(f, "VkFormat(B8G8R8A8_UINT)"),
VkFormat::B8G8R8A8_SINT => write!(f, "VkFormat(B8G8R8A8_SINT)"),
VkFormat::B8G8R8A8_SRGB => write!(f, "VkFormat(B8G8R8A8_SRGB)"),
VkFormat::A8B8G8R8_UNORM_PACK32 => write!(f, "VkFormat(A8B8G8R8_UNORM_PACK32)"),
VkFormat::A8B8G8R8_SNORM_PACK32 => write!(f, "VkFormat(A8B8G8R8_SNORM_PACK32)"),
VkFormat::A8B8G8R8_USCALED_PACK32 => write!(f, "VkFormat(A8B8G8R8_USCALED_PACK32)"),
VkFormat::A8B8G8R8_SSCALED_PACK32 => write!(f, "VkFormat(A8B8G8R8_SSCALED_PACK32)"),
VkFormat::A8B8G8R8_UINT_PACK32 => write!(f, "VkFormat(A8B8G8R8_UINT_PACK32)"),
VkFormat::A8B8G8R8_SINT_PACK32 => write!(f, "VkFormat(A8B8G8R8_SINT_PACK32)"),
VkFormat::A8B8G8R8_SRGB_PACK32 => write!(f, "VkFormat(A8B8G8R8_SRGB_PACK32)"),
VkFormat::A2R10G10B10_UNORM_PACK32 => write!(f, "VkFormat(A2R10G10B10_UNORM_PACK32)"),
VkFormat::A2R10G10B10_SNORM_PACK32 => write!(f, "VkFormat(A2R10G10B10_SNORM_PACK32)"),
VkFormat::A2R10G10B10_USCALED_PACK32 =>
{
write!(f, "VkFormat(A2R10G10B10_USCALED_PACK32)")
}
VkFormat::A2R10G10B10_SSCALED_PACK32 =>
{
write!(f, "VkFormat(A2R10G10B10_SSCALED_PACK32)")
}
VkFormat::A2R10G10B10_UINT_PACK32 => write!(f, "VkFormat(A2R10G10B10_UINT_PACK32)"),
VkFormat::A2R10G10B10_SINT_PACK32 => write!(f, "VkFormat(A2R10G10B10_SINT_PACK32)"),
VkFormat::A2B10G10R10_UNORM_PACK32 => write!(f, "VkFormat(A2B10G10R10_UNORM_PACK32)"),
VkFormat::A2B10G10R10_SNORM_PACK32 => write!(f, "VkFormat(A2B10G10R10_SNORM_PACK32)"),
VkFormat::A2B10G10R10_USCALED_PACK32 =>
{
write!(f, "VkFormat(A2B10G10R10_USCALED_PACK32)")
}
VkFormat::A2B10G10R10_SSCALED_PACK32 =>
{
write!(f, "VkFormat(A2B10G10R10_SSCALED_PACK32)")
}
VkFormat::A2B10G10R10_UINT_PACK32 => write!(f, "VkFormat(A2B10G10R10_UINT_PACK32)"),
VkFormat::A2B10G10R10_SINT_PACK32 => write!(f, "VkFormat(A2B10G10R10_SINT_PACK32)"),
VkFormat::R16_UNORM => write!(f, "VkFormat(R16_UNORM)"),
VkFormat::R16_SNORM => write!(f, "VkFormat(R16_SNORM)"),
VkFormat::R16_USCALED => write!(f, "VkFormat(R16_USCALED)"),
VkFormat::R16_SSCALED => write!(f, "VkFormat(R16_SSCALED)"),
VkFormat::R16_UINT => write!(f, "VkFormat(R16_UINT)"),
VkFormat::R16_SINT => write!(f, "VkFormat(R16_SINT)"),
VkFormat::R16_SFLOAT => write!(f, "VkFormat(R16_SFLOAT)"),
VkFormat::R16G16_UNORM => write!(f, "VkFormat(R16G16_UNORM)"),
VkFormat::R16G16_SNORM => write!(f, "VkFormat(R16G16_SNORM)"),
VkFormat::R16G16_USCALED => write!(f, "VkFormat(R16G16_USCALED)"),
VkFormat::R16G16_SSCALED => write!(f, "VkFormat(R16G16_SSCALED)"),
VkFormat::R16G16_UINT => write!(f, "VkFormat(R16G16_UINT)"),
VkFormat::R16G16_SINT => write!(f, "VkFormat(R16G16_SINT)"),
VkFormat::R16G16_SFLOAT => write!(f, "VkFormat(R16G16_SFLOAT)"),
VkFormat::R16G16B16_UNORM => write!(f, "VkFormat(R16G16B16_UNORM)"),
VkFormat::R16G16B16_SNORM => write!(f, "VkFormat(R16G16B16_SNORM)"),
VkFormat::R16G16B16_USCALED => write!(f, "VkFormat(R16G16B16_USCALED)"),
VkFormat::R16G16B16_SSCALED => write!(f, "VkFormat(R16G16B16_SSCALED)"),
VkFormat::R16G16B16_UINT => write!(f, "VkFormat(R16G16B16_UINT)"),
VkFormat::R16G16B16_SINT => write!(f, "VkFormat(R16G16B16_SINT)"),
VkFormat::R16G16B16_SFLOAT => write!(f, "VkFormat(R16G16B16_SFLOAT)"),
VkFormat::R16G16B16A16_UNORM => write!(f, "VkFormat(R16G16B16A16_UNORM)"),
VkFormat::R16G16B16A16_SNORM => write!(f, "VkFormat(R16G16B16A16_SNORM)"),
VkFormat::R16G16B16A16_USCALED => write!(f, "VkFormat(R16G16B16A16_USCALED)"),
VkFormat::R16G16B16A16_SSCALED => write!(f, "VkFormat(R16G16B16A16_SSCALED)"),
VkFormat::R16G16B16A16_UINT => write!(f, "VkFormat(R16G16B16A16_UINT)"),
VkFormat::R16G16B16A16_SINT => write!(f, "VkFormat(R16G16B16A16_SINT)"),
VkFormat::R16G16B16A16_SFLOAT => write!(f, "VkFormat(R16G16B16A16_SFLOAT)"),
VkFormat::R32_UINT => write!(f, "VkFormat(R32_UINT)"),
VkFormat::R32_SINT => write!(f, "VkFormat(R32_SINT)"),
VkFormat::R32_SFLOAT => write!(f, "VkFormat(R32_SFLOAT)"),
VkFormat::R32G32_UINT => write!(f, "VkFormat(R32G32_UINT)"),
VkFormat::R32G32_SINT => write!(f, "VkFormat(R32G32_SINT)"),
VkFormat::R32G32_SFLOAT => write!(f, "VkFormat(R32G32_SFLOAT)"),
VkFormat::R32G32B32_UINT => write!(f, "VkFormat(R32G32B32_UINT)"),
VkFormat::R32G32B32_SINT => write!(f, "VkFormat(R32G32B32_SINT)"),
VkFormat::R32G32B32_SFLOAT => write!(f, "VkFormat(R32G32B32_SFLOAT)"),
VkFormat::R32G32B32A32_UINT => write!(f, "VkFormat(R32G32B32A32_UINT)"),
VkFormat::R32G32B32A32_SINT => write!(f, "VkFormat(R32G32B32A32_SINT)"),
VkFormat::R32G32B32A32_SFLOAT => write!(f, "VkFormat(R32G32B32A32_SFLOAT)"),
VkFormat::R64_UINT => write!(f, "VkFormat(R64_UINT)"),
VkFormat::R64_SINT => write!(f, "VkFormat(R64_SINT)"),
VkFormat::R64_SFLOAT => write!(f, "VkFormat(R64_SFLOAT)"),
VkFormat::R64G64_UINT => write!(f, "VkFormat(R64G64_UINT)"),
VkFormat::R64G64_SINT => write!(f, "VkFormat(R64G64_SINT)"),
VkFormat::R64G64_SFLOAT => write!(f, "VkFormat(R64G64_SFLOAT)"),
VkFormat::R64G64B64_UINT => write!(f, "VkFormat(R64G64B64_UINT)"),
VkFormat::R64G64B64_SINT => write!(f, "VkFormat(R64G64B64_SINT)"),
VkFormat::R64G64B64_SFLOAT => write!(f, "VkFormat(R64G64B64_SFLOAT)"),
VkFormat::R64G64B64A64_UINT => write!(f, "VkFormat(R64G64B64A64_UINT)"),
VkFormat::R64G64B64A64_SINT => write!(f, "VkFormat(R64G64B64A64_SINT)"),
VkFormat::R64G64B64A64_SFLOAT => write!(f, "VkFormat(R64G64B64A64_SFLOAT)"),
VkFormat::B10G11R11_UFLOAT_PACK32 => write!(f, "VkFormat(B10G11R11_UFLOAT_PACK32)"),
VkFormat::E5B9G9R9_UFLOAT_PACK32 => write!(f, "VkFormat(E5B9G9R9_UFLOAT_PACK32)"),
VkFormat::D16_UNORM => write!(f, "VkFormat(D16_UNORM)"),
VkFormat::X8_D24_UNORM_PACK32 => write!(f, "VkFormat(X8_D24_UNORM_PACK32)"),
VkFormat::D32_SFLOAT => write!(f, "VkFormat(D32_SFLOAT)"),
VkFormat::S8_UINT => write!(f, "VkFormat(S8_UINT)"),
VkFormat::D16_UNORM_S8_UINT => write!(f, "VkFormat(D16_UNORM_S8_UINT)"),
VkFormat::D24_UNORM_S8_UINT => write!(f, "VkFormat(D24_UNORM_S8_UINT)"),
VkFormat::D32_SFLOAT_S8_UINT => write!(f, "VkFormat(D32_SFLOAT_S8_UINT)"),
VkFormat::BC1_RGB_UNORM_BLOCK => write!(f, "VkFormat(BC1_RGB_UNORM_BLOCK)"),
VkFormat::BC1_RGB_SRGB_BLOCK => write!(f, "VkFormat(BC1_RGB_SRGB_BLOCK)"),
VkFormat::BC1_RGBA_UNORM_BLOCK => write!(f, "VkFormat(BC1_RGBA_UNORM_BLOCK)"),
VkFormat::BC1_RGBA_SRGB_BLOCK => write!(f, "VkFormat(BC1_RGBA_SRGB_BLOCK)"),
VkFormat::BC2_UNORM_BLOCK => write!(f, "VkFormat(BC2_UNORM_BLOCK)"),
VkFormat::BC2_SRGB_BLOCK => write!(f, "VkFormat(BC2_SRGB_BLOCK)"),
VkFormat::BC3_UNORM_BLOCK => write!(f, "VkFormat(BC3_UNORM_BLOCK)"),
VkFormat::BC3_SRGB_BLOCK => write!(f, "VkFormat(BC3_SRGB_BLOCK)"),
VkFormat::BC4_UNORM_BLOCK => write!(f, "VkFormat(BC4_UNORM_BLOCK)"),
VkFormat::BC4_SNORM_BLOCK => write!(f, "VkFormat(BC4_SNORM_BLOCK)"),
VkFormat::BC5_UNORM_BLOCK => write!(f, "VkFormat(BC5_UNORM_BLOCK)"),
VkFormat::BC5_SNORM_BLOCK => write!(f, "VkFormat(BC5_SNORM_BLOCK)"),
VkFormat::BC6H_UFLOAT_BLOCK => write!(f, "VkFormat(BC6H_UFLOAT_BLOCK)"),
VkFormat::BC6H_SFLOAT_BLOCK => write!(f, "VkFormat(BC6H_SFLOAT_BLOCK)"),
VkFormat::BC7_UNORM_BLOCK => write!(f, "VkFormat(BC7_UNORM_BLOCK)"),
VkFormat::BC7_SRGB_BLOCK => write!(f, "VkFormat(BC7_SRGB_BLOCK)"),
VkFormat::ETC2_R8G8B8_UNORM_BLOCK => write!(f, "VkFormat(ETC2_R8G8B8_UNORM_BLOCK)"),
VkFormat::ETC2_R8G8B8_SRGB_BLOCK => write!(f, "VkFormat(ETC2_R8G8B8_SRGB_BLOCK)"),
VkFormat::ETC2_R8G8B8A1_UNORM_BLOCK => write!(f, "VkFormat(ETC2_R8G8B8A1_UNORM_BLOCK)"),
VkFormat::ETC2_R8G8B8A1_SRGB_BLOCK => write!(f, "VkFormat(ETC2_R8G8B8A1_SRGB_BLOCK)"),
VkFormat::ETC2_R8G8B8A8_UNORM_BLOCK => write!(f, "VkFormat(ETC2_R8G8B8A8_UNORM_BLOCK)"),
VkFormat::ETC2_R8G8B8A8_SRGB_BLOCK => write!(f, "VkFormat(ETC2_R8G8B8A8_SRGB_BLOCK)"),
VkFormat::EAC_R11_UNORM_BLOCK => write!(f, "VkFormat(EAC_R11_UNORM_BLOCK)"),
VkFormat::EAC_R11_SNORM_BLOCK => write!(f, "VkFormat(EAC_R11_SNORM_BLOCK)"),
VkFormat::EAC_R11G11_UNORM_BLOCK => write!(f, "VkFormat(EAC_R11G11_UNORM_BLOCK)"),
VkFormat::EAC_R11G11_SNORM_BLOCK => write!(f, "VkFormat(EAC_R11G11_SNORM_BLOCK)"),
VkFormat::ASTC_4X4_UNORM_BLOCK => write!(f, "VkFormat(ASTC_4X4_UNORM_BLOCK)"),
VkFormat::ASTC_4X4_SRGB_BLOCK => write!(f, "VkFormat(ASTC_4X4_SRGB_BLOCK)"),
VkFormat::ASTC_5X4_UNORM_BLOCK => write!(f, "VkFormat(ASTC_5X4_UNORM_BLOCK)"),
VkFormat::ASTC_5X4_SRGB_BLOCK => write!(f, "VkFormat(ASTC_5X4_SRGB_BLOCK)"),
VkFormat::ASTC_5X5_UNORM_BLOCK => write!(f, "VkFormat(ASTC_5X5_UNORM_BLOCK)"),
VkFormat::ASTC_5X5_SRGB_BLOCK => write!(f, "VkFormat(ASTC_5X5_SRGB_BLOCK)"),
VkFormat::ASTC_6X5_UNORM_BLOCK => write!(f, "VkFormat(ASTC_6X5_UNORM_BLOCK)"),
VkFormat::ASTC_6X5_SRGB_BLOCK => write!(f, "VkFormat(ASTC_6X5_SRGB_BLOCK)"),
VkFormat::ASTC_6X6_UNORM_BLOCK => write!(f, "VkFormat(ASTC_6X6_UNORM_BLOCK)"),
VkFormat::ASTC_6X6_SRGB_BLOCK => write!(f, "VkFormat(ASTC_6X6_SRGB_BLOCK)"),
VkFormat::ASTC_8X5_UNORM_BLOCK => write!(f, "VkFormat(ASTC_8X5_UNORM_BLOCK)"),
VkFormat::ASTC_8X5_SRGB_BLOCK => write!(f, "VkFormat(ASTC_8X5_SRGB_BLOCK)"),
VkFormat::ASTC_8X6_UNORM_BLOCK => write!(f, "VkFormat(ASTC_8X6_UNORM_BLOCK)"),
VkFormat::ASTC_8X6_SRGB_BLOCK => write!(f, "VkFormat(ASTC_8X6_SRGB_BLOCK)"),
VkFormat::ASTC_8X8_UNORM_BLOCK => write!(f, "VkFormat(ASTC_8X8_UNORM_BLOCK)"),
VkFormat::ASTC_8X8_SRGB_BLOCK => write!(f, "VkFormat(ASTC_8X8_SRGB_BLOCK)"),
VkFormat::ASTC_10X5_UNORM_BLOCK => write!(f, "VkFormat(ASTC_10X5_UNORM_BLOCK)"),
VkFormat::ASTC_10X5_SRGB_BLOCK => write!(f, "VkFormat(ASTC_10X5_SRGB_BLOCK)"),
VkFormat::ASTC_10X6_UNORM_BLOCK => write!(f, "VkFormat(ASTC_10X6_UNORM_BLOCK)"),
VkFormat::ASTC_10X6_SRGB_BLOCK => write!(f, "VkFormat(ASTC_10X6_SRGB_BLOCK)"),
VkFormat::ASTC_10X8_UNORM_BLOCK => write!(f, "VkFormat(ASTC_10X8_UNORM_BLOCK)"),
VkFormat::ASTC_10X8_SRGB_BLOCK => write!(f, "VkFormat(ASTC_10X8_SRGB_BLOCK)"),
VkFormat::ASTC_10X10_UNORM_BLOCK => write!(f, "VkFormat(ASTC_10X10_UNORM_BLOCK)"),
VkFormat::ASTC_10X10_SRGB_BLOCK => write!(f, "VkFormat(ASTC_10X10_SRGB_BLOCK)"),
VkFormat::ASTC_12X10_UNORM_BLOCK => write!(f, "VkFormat(ASTC_12X10_UNORM_BLOCK)"),
VkFormat::ASTC_12X10_SRGB_BLOCK => write!(f, "VkFormat(ASTC_12X10_SRGB_BLOCK)"),
VkFormat::ASTC_12X12_UNORM_BLOCK => write!(f, "VkFormat(ASTC_12X12_UNORM_BLOCK)"),
VkFormat::ASTC_12X12_SRGB_BLOCK => write!(f, "VkFormat(ASTC_12X12_SRGB_BLOCK)"),
_ => write!(f, "VkFormat({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkObjectType(u32);
impl VkObjectType
{
pub const UNKNOWN: VkObjectType = VkObjectType(0);
pub const INSTANCE: VkObjectType = VkObjectType(1);
pub const PHYSICAL_DEVICE: VkObjectType = VkObjectType(2);
pub const DEVICE: VkObjectType = VkObjectType(3);
pub const QUEUE: VkObjectType = VkObjectType(4);
pub const SEMAPHORE: VkObjectType = VkObjectType(5);
pub const COMMAND_BUFFER: VkObjectType = VkObjectType(6);
pub const FENCE: VkObjectType = VkObjectType(7);
pub const DEVICE_MEMORY: VkObjectType = VkObjectType(8);
pub const BUFFER: VkObjectType = VkObjectType(9);
pub const IMAGE: VkObjectType = VkObjectType(10);
pub const EVENT: VkObjectType = VkObjectType(11);
pub const QUERY_POOL: VkObjectType = VkObjectType(12);
pub const BUFFER_VIEW: VkObjectType = VkObjectType(13);
pub const IMAGE_VIEW: VkObjectType = VkObjectType(14);
pub const SHADER_MODULE: VkObjectType = VkObjectType(15);
pub const PIPELINE_CACHE: VkObjectType = VkObjectType(16);
pub const PIPELINE_LAYOUT: VkObjectType = VkObjectType(17);
pub const RENDER_PASS: VkObjectType = VkObjectType(18);
pub const PIPELINE: VkObjectType = VkObjectType(19);
pub const DESCRIPTOR_SET_LAYOUT: VkObjectType = VkObjectType(20);
pub const SAMPLER: VkObjectType = VkObjectType(21);
pub const DESCRIPTOR_POOL: VkObjectType = VkObjectType(22);
pub const DESCRIPTOR_SET: VkObjectType = VkObjectType(23);
pub const FRAMEBUFFER: VkObjectType = VkObjectType(24);
pub const COMMAND_POOL: VkObjectType = VkObjectType(25);
pub const SURFACE_KHR: VkObjectType = VkObjectType(1000000000);
pub const SWAPCHAIN_KHR: VkObjectType = VkObjectType(1000001000);
pub const DEBUG_UTILS_MESSENGER_EXT: VkObjectType = VkObjectType(1000128000);
}
impl core::fmt::Debug for VkObjectType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkObjectType::UNKNOWN => write!(f, "VkObjectType(UNKNOWN)"),
VkObjectType::INSTANCE => write!(f, "VkObjectType(INSTANCE)"),
VkObjectType::PHYSICAL_DEVICE => write!(f, "VkObjectType(PHYSICAL_DEVICE)"),
VkObjectType::DEVICE => write!(f, "VkObjectType(DEVICE)"),
VkObjectType::QUEUE => write!(f, "VkObjectType(QUEUE)"),
VkObjectType::SEMAPHORE => write!(f, "VkObjectType(SEMAPHORE)"),
VkObjectType::COMMAND_BUFFER => write!(f, "VkObjectType(COMMAND_BUFFER)"),
VkObjectType::FENCE => write!(f, "VkObjectType(FENCE)"),
VkObjectType::DEVICE_MEMORY => write!(f, "VkObjectType(DEVICE_MEMORY)"),
VkObjectType::BUFFER => write!(f, "VkObjectType(BUFFER)"),
VkObjectType::IMAGE => write!(f, "VkObjectType(IMAGE)"),
VkObjectType::EVENT => write!(f, "VkObjectType(EVENT)"),
VkObjectType::QUERY_POOL => write!(f, "VkObjectType(QUERY_POOL)"),
VkObjectType::BUFFER_VIEW => write!(f, "VkObjectType(BUFFER_VIEW)"),
VkObjectType::IMAGE_VIEW => write!(f, "VkObjectType(IMAGE_VIEW)"),
VkObjectType::SHADER_MODULE => write!(f, "VkObjectType(SHADER_MODULE)"),
VkObjectType::PIPELINE_CACHE => write!(f, "VkObjectType(PIPELINE_CACHE)"),
VkObjectType::PIPELINE_LAYOUT => write!(f, "VkObjectType(PIPELINE_LAYOUT)"),
VkObjectType::RENDER_PASS => write!(f, "VkObjectType(RENDER_PASS)"),
VkObjectType::PIPELINE => write!(f, "VkObjectType(PIPELINE)"),
VkObjectType::DESCRIPTOR_SET_LAYOUT => write!(f, "VkObjectType(DESCRIPTOR_SET_LAYOUT)"),
VkObjectType::SAMPLER => write!(f, "VkObjectType(SAMPLER)"),
VkObjectType::DESCRIPTOR_POOL => write!(f, "VkObjectType(DESCRIPTOR_POOL)"),
VkObjectType::DESCRIPTOR_SET => write!(f, "VkObjectType(DESCRIPTOR_SET)"),
VkObjectType::FRAMEBUFFER => write!(f, "VkObjectType(FRAMEBUFFER)"),
VkObjectType::COMMAND_POOL => write!(f, "VkObjectType(COMMAND_POOL)"),
VkObjectType::SURFACE_KHR => write!(f, "VkObjectType(SURFACE_KHR)"),
VkObjectType::SWAPCHAIN_KHR => write!(f, "VkObjectType(SWAPCHAIN_KHR)"),
VkObjectType::DEBUG_UTILS_MESSENGER_EXT =>
{
write!(f, "VkObjectType(DEBUG_UTILS_MESSENGER_EXT)")
}
_ => write!(f, "VkObjectType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkSharingMode(u32);
impl VkSharingMode
{
pub const EXCLUSIVE: VkSharingMode = VkSharingMode(0);
pub const CONCURRENT: VkSharingMode = VkSharingMode(1);
}
impl core::fmt::Debug for VkSharingMode
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkSharingMode::EXCLUSIVE => write!(f, "VkSharingMode(EXCLUSIVE)"),
VkSharingMode::CONCURRENT => write!(f, "VkSharingMode(CONCURRENT)"),
_ => write!(f, "VkSharingMode({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkImageLayout(u32);
impl VkImageLayout
{
pub const UNDEFINED: VkImageLayout = VkImageLayout(0);
pub const GENERAL: VkImageLayout = VkImageLayout(1);
pub const COLOR_ATTACHMENT_OPTIMAL: VkImageLayout = VkImageLayout(2);
pub const DEPTH_STENCIL_ATTACHMENT_OPTIMAL: VkImageLayout = VkImageLayout(3);
pub const DEPTH_STENCIL_READ_ONLY_OPTIMAL: VkImageLayout = VkImageLayout(4);
pub const SHADER_READ_ONLY_OPTIMAL: VkImageLayout = VkImageLayout(5);
pub const TRANSFER_SRC_OPTIMAL: VkImageLayout = VkImageLayout(6);
pub const TRANSFER_DST_OPTIMAL: VkImageLayout = VkImageLayout(7);
pub const PREINITIALIZED: VkImageLayout = VkImageLayout(8);
pub const PRESENT_SRC_KHR: VkImageLayout = VkImageLayout(1000001002);
}
impl core::fmt::Debug for VkImageLayout
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkImageLayout::UNDEFINED => write!(f, "VkImageLayout(UNDEFINED)"),
VkImageLayout::GENERAL => write!(f, "VkImageLayout(GENERAL)"),
VkImageLayout::COLOR_ATTACHMENT_OPTIMAL =>
{
write!(f, "VkImageLayout(COLOR_ATTACHMENT_OPTIMAL)")
}
VkImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL =>
{
write!(f, "VkImageLayout(DEPTH_STENCIL_ATTACHMENT_OPTIMAL)")
}
VkImageLayout::DEPTH_STENCIL_READ_ONLY_OPTIMAL =>
{
write!(f, "VkImageLayout(DEPTH_STENCIL_READ_ONLY_OPTIMAL)")
}
VkImageLayout::SHADER_READ_ONLY_OPTIMAL =>
{
write!(f, "VkImageLayout(SHADER_READ_ONLY_OPTIMAL)")
}
VkImageLayout::TRANSFER_SRC_OPTIMAL => write!(f, "VkImageLayout(TRANSFER_SRC_OPTIMAL)"),
VkImageLayout::TRANSFER_DST_OPTIMAL => write!(f, "VkImageLayout(TRANSFER_DST_OPTIMAL)"),
VkImageLayout::PREINITIALIZED => write!(f, "VkImageLayout(PREINITIALIZED)"),
VkImageLayout::PRESENT_SRC_KHR => write!(f, "VkImageLayout(PRESENT_SRC_KHR)"),
_ => write!(f, "VkImageLayout({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkVendorId(u32);
impl VkVendorId
{
pub const VIV: VkVendorId = VkVendorId(65537);
pub const VSI: VkVendorId = VkVendorId(65538);
pub const KAZAN: VkVendorId = VkVendorId(65539);
}
impl core::fmt::Debug for VkVendorId
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkVendorId::VIV => write!(f, "VkVendorId(VIV)"),
VkVendorId::VSI => write!(f, "VkVendorId(VSI)"),
VkVendorId::KAZAN => write!(f, "VkVendorId(KAZAN)"),
_ => write!(f, "VkVendorId({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkSubpassContents(u32);
impl VkSubpassContents
{
pub const INLINE: VkSubpassContents = VkSubpassContents(0);
pub const SECONDARY_COMMAND_BUFFERS: VkSubpassContents = VkSubpassContents(1);
}
impl core::fmt::Debug for VkSubpassContents
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkSubpassContents::INLINE => write!(f, "VkSubpassContents(INLINE)"),
VkSubpassContents::SECONDARY_COMMAND_BUFFERS =>
{
write!(f, "VkSubpassContents(SECONDARY_COMMAND_BUFFERS)")
}
_ => write!(f, "VkSubpassContents({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkFilter(u32);
impl VkFilter
{
pub const NEAREST: VkFilter = VkFilter(0);
pub const LINEAR: VkFilter = VkFilter(1);
}
impl core::fmt::Debug for VkFilter
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkFilter::NEAREST => write!(f, "VkFilter(NEAREST)"),
VkFilter::LINEAR => write!(f, "VkFilter(LINEAR)"),
_ => write!(f, "VkFilter({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkIndexType(u32);
impl VkIndexType
{
pub const UINT16: VkIndexType = VkIndexType(0);
pub const UINT32: VkIndexType = VkIndexType(1);
}
impl core::fmt::Debug for VkIndexType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkIndexType::UINT16 => write!(f, "VkIndexType(UINT16)"),
VkIndexType::UINT32 => write!(f, "VkIndexType(UINT32)"),
_ => write!(f, "VkIndexType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkPipelineBindPoint(u32);
impl VkPipelineBindPoint
{
pub const GRAPHICS: VkPipelineBindPoint = VkPipelineBindPoint(0);
pub const COMPUTE: VkPipelineBindPoint = VkPipelineBindPoint(1);
}
impl core::fmt::Debug for VkPipelineBindPoint
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkPipelineBindPoint::GRAPHICS => write!(f, "VkPipelineBindPoint(GRAPHICS)"),
VkPipelineBindPoint::COMPUTE => write!(f, "VkPipelineBindPoint(COMPUTE)"),
_ => write!(f, "VkPipelineBindPoint({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkCommandBufferLevel(u32);
impl VkCommandBufferLevel
{
pub const PRIMARY: VkCommandBufferLevel = VkCommandBufferLevel(0);
pub const SECONDARY: VkCommandBufferLevel = VkCommandBufferLevel(1);
}
impl core::fmt::Debug for VkCommandBufferLevel
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkCommandBufferLevel::PRIMARY => write!(f, "VkCommandBufferLevel(PRIMARY)"),
VkCommandBufferLevel::SECONDARY => write!(f, "VkCommandBufferLevel(SECONDARY)"),
_ => write!(f, "VkCommandBufferLevel({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkAttachmentStoreOp(u32);
impl VkAttachmentStoreOp
{
pub const STORE: VkAttachmentStoreOp = VkAttachmentStoreOp(0);
pub const DONT_CARE: VkAttachmentStoreOp = VkAttachmentStoreOp(1);
}
impl core::fmt::Debug for VkAttachmentStoreOp
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkAttachmentStoreOp::STORE => write!(f, "VkAttachmentStoreOp(STORE)"),
VkAttachmentStoreOp::DONT_CARE => write!(f, "VkAttachmentStoreOp(DONT_CARE)"),
_ => write!(f, "VkAttachmentStoreOp({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkAttachmentLoadOp(u32);
impl VkAttachmentLoadOp
{
pub const LOAD: VkAttachmentLoadOp = VkAttachmentLoadOp(0);
pub const CLEAR: VkAttachmentLoadOp = VkAttachmentLoadOp(1);
pub const DONT_CARE: VkAttachmentLoadOp = VkAttachmentLoadOp(2);
}
impl core::fmt::Debug for VkAttachmentLoadOp
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkAttachmentLoadOp::LOAD => write!(f, "VkAttachmentLoadOp(LOAD)"),
VkAttachmentLoadOp::CLEAR => write!(f, "VkAttachmentLoadOp(CLEAR)"),
VkAttachmentLoadOp::DONT_CARE => write!(f, "VkAttachmentLoadOp(DONT_CARE)"),
_ => write!(f, "VkAttachmentLoadOp({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkDescriptorType(u32);
impl VkDescriptorType
{
pub const SAMPLER: VkDescriptorType = VkDescriptorType(0);
pub const COMBINED_IMAGE_SAMPLER: VkDescriptorType = VkDescriptorType(1);
pub const SAMPLED_IMAGE: VkDescriptorType = VkDescriptorType(2);
pub const STORAGE_IMAGE: VkDescriptorType = VkDescriptorType(3);
pub const UNIFORM_TEXEL_BUFFER: VkDescriptorType = VkDescriptorType(4);
pub const STORAGE_TEXEL_BUFFER: VkDescriptorType = VkDescriptorType(5);
pub const UNIFORM_BUFFER: VkDescriptorType = VkDescriptorType(6);
pub const STORAGE_BUFFER: VkDescriptorType = VkDescriptorType(7);
pub const UNIFORM_BUFFER_DYNAMIC: VkDescriptorType = VkDescriptorType(8);
pub const STORAGE_BUFFER_DYNAMIC: VkDescriptorType = VkDescriptorType(9);
pub const INPUT_ATTACHMENT: VkDescriptorType = VkDescriptorType(10);
}
impl core::fmt::Debug for VkDescriptorType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkDescriptorType::SAMPLER => write!(f, "VkDescriptorType(SAMPLER)"),
VkDescriptorType::COMBINED_IMAGE_SAMPLER =>
{
write!(f, "VkDescriptorType(COMBINED_IMAGE_SAMPLER)")
}
VkDescriptorType::SAMPLED_IMAGE => write!(f, "VkDescriptorType(SAMPLED_IMAGE)"),
VkDescriptorType::STORAGE_IMAGE => write!(f, "VkDescriptorType(STORAGE_IMAGE)"),
VkDescriptorType::UNIFORM_TEXEL_BUFFER =>
{
write!(f, "VkDescriptorType(UNIFORM_TEXEL_BUFFER)")
}
VkDescriptorType::STORAGE_TEXEL_BUFFER =>
{
write!(f, "VkDescriptorType(STORAGE_TEXEL_BUFFER)")
}
VkDescriptorType::UNIFORM_BUFFER => write!(f, "VkDescriptorType(UNIFORM_BUFFER)"),
VkDescriptorType::STORAGE_BUFFER => write!(f, "VkDescriptorType(STORAGE_BUFFER)"),
VkDescriptorType::UNIFORM_BUFFER_DYNAMIC =>
{
write!(f, "VkDescriptorType(UNIFORM_BUFFER_DYNAMIC)")
}
VkDescriptorType::STORAGE_BUFFER_DYNAMIC =>
{
write!(f, "VkDescriptorType(STORAGE_BUFFER_DYNAMIC)")
}
VkDescriptorType::INPUT_ATTACHMENT => write!(f, "VkDescriptorType(INPUT_ATTACHMENT)"),
_ => write!(f, "VkDescriptorType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkBorderColor(u32);
impl VkBorderColor
{
pub const FLOAT_TRANSPARENT_BLACK: VkBorderColor = VkBorderColor(0);
pub const INT_TRANSPARENT_BLACK: VkBorderColor = VkBorderColor(1);
pub const FLOAT_OPAQUE_BLACK: VkBorderColor = VkBorderColor(2);
pub const INT_OPAQUE_BLACK: VkBorderColor = VkBorderColor(3);
pub const FLOAT_OPAQUE_WHITE: VkBorderColor = VkBorderColor(4);
pub const INT_OPAQUE_WHITE: VkBorderColor = VkBorderColor(5);
}
impl core::fmt::Debug for VkBorderColor
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkBorderColor::FLOAT_TRANSPARENT_BLACK =>
{
write!(f, "VkBorderColor(FLOAT_TRANSPARENT_BLACK)")
}
VkBorderColor::INT_TRANSPARENT_BLACK =>
{
write!(f, "VkBorderColor(INT_TRANSPARENT_BLACK)")
}
VkBorderColor::FLOAT_OPAQUE_BLACK => write!(f, "VkBorderColor(FLOAT_OPAQUE_BLACK)"),
VkBorderColor::INT_OPAQUE_BLACK => write!(f, "VkBorderColor(INT_OPAQUE_BLACK)"),
VkBorderColor::FLOAT_OPAQUE_WHITE => write!(f, "VkBorderColor(FLOAT_OPAQUE_WHITE)"),
VkBorderColor::INT_OPAQUE_WHITE => write!(f, "VkBorderColor(INT_OPAQUE_WHITE)"),
_ => write!(f, "VkBorderColor({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkCompareOp(u32);
impl VkCompareOp
{
pub const NEVER: VkCompareOp = VkCompareOp(0);
pub const LESS: VkCompareOp = VkCompareOp(1);
pub const EQUAL: VkCompareOp = VkCompareOp(2);
pub const LESS_OR_EQUAL: VkCompareOp = VkCompareOp(3);
pub const GREATER: VkCompareOp = VkCompareOp(4);
pub const NOT_EQUAL: VkCompareOp = VkCompareOp(5);
pub const GREATER_OR_EQUAL: VkCompareOp = VkCompareOp(6);
pub const ALWAYS: VkCompareOp = VkCompareOp(7);
}
impl core::fmt::Debug for VkCompareOp
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkCompareOp::NEVER => write!(f, "VkCompareOp(NEVER)"),
VkCompareOp::LESS => write!(f, "VkCompareOp(LESS)"),
VkCompareOp::EQUAL => write!(f, "VkCompareOp(EQUAL)"),
VkCompareOp::LESS_OR_EQUAL => write!(f, "VkCompareOp(LESS_OR_EQUAL)"),
VkCompareOp::GREATER => write!(f, "VkCompareOp(GREATER)"),
VkCompareOp::NOT_EQUAL => write!(f, "VkCompareOp(NOT_EQUAL)"),
VkCompareOp::GREATER_OR_EQUAL => write!(f, "VkCompareOp(GREATER_OR_EQUAL)"),
VkCompareOp::ALWAYS => write!(f, "VkCompareOp(ALWAYS)"),
_ => write!(f, "VkCompareOp({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkSamplerAddressMode(u32);
impl VkSamplerAddressMode
{
pub const REPEAT: VkSamplerAddressMode = VkSamplerAddressMode(0);
pub const MIRRORED_REPEAT: VkSamplerAddressMode = VkSamplerAddressMode(1);
pub const CLAMP_TO_EDGE: VkSamplerAddressMode = VkSamplerAddressMode(2);
pub const CLAMP_TO_BORDER: VkSamplerAddressMode = VkSamplerAddressMode(3);
}
impl core::fmt::Debug for VkSamplerAddressMode
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkSamplerAddressMode::REPEAT => write!(f, "VkSamplerAddressMode(REPEAT)"),
VkSamplerAddressMode::MIRRORED_REPEAT =>
{
write!(f, "VkSamplerAddressMode(MIRRORED_REPEAT)")
}
VkSamplerAddressMode::CLAMP_TO_EDGE => write!(f, "VkSamplerAddressMode(CLAMP_TO_EDGE)"),
VkSamplerAddressMode::CLAMP_TO_BORDER =>
{
write!(f, "VkSamplerAddressMode(CLAMP_TO_BORDER)")
}
_ => write!(f, "VkSamplerAddressMode({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkSamplerMipmapMode(u32);
impl VkSamplerMipmapMode
{
pub const NEAREST: VkSamplerMipmapMode = VkSamplerMipmapMode(0);
pub const LINEAR: VkSamplerMipmapMode = VkSamplerMipmapMode(1);
}
impl core::fmt::Debug for VkSamplerMipmapMode
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkSamplerMipmapMode::NEAREST => write!(f, "VkSamplerMipmapMode(NEAREST)"),
VkSamplerMipmapMode::LINEAR => write!(f, "VkSamplerMipmapMode(LINEAR)"),
_ => write!(f, "VkSamplerMipmapMode({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkDynamicState(u32);
impl VkDynamicState
{
pub const VIEWPORT: VkDynamicState = VkDynamicState(0);
pub const SCISSOR: VkDynamicState = VkDynamicState(1);
pub const LINE_WIDTH: VkDynamicState = VkDynamicState(2);
pub const DEPTH_BIAS: VkDynamicState = VkDynamicState(3);
pub const BLEND_CONSTANTS: VkDynamicState = VkDynamicState(4);
pub const DEPTH_BOUNDS: VkDynamicState = VkDynamicState(5);
pub const STENCIL_COMPARE_MASK: VkDynamicState = VkDynamicState(6);
pub const STENCIL_WRITE_MASK: VkDynamicState = VkDynamicState(7);
pub const STENCIL_REFERENCE: VkDynamicState = VkDynamicState(8);
}
impl core::fmt::Debug for VkDynamicState
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkDynamicState::VIEWPORT => write!(f, "VkDynamicState(VIEWPORT)"),
VkDynamicState::SCISSOR => write!(f, "VkDynamicState(SCISSOR)"),
VkDynamicState::LINE_WIDTH => write!(f, "VkDynamicState(LINE_WIDTH)"),
VkDynamicState::DEPTH_BIAS => write!(f, "VkDynamicState(DEPTH_BIAS)"),
VkDynamicState::BLEND_CONSTANTS => write!(f, "VkDynamicState(BLEND_CONSTANTS)"),
VkDynamicState::DEPTH_BOUNDS => write!(f, "VkDynamicState(DEPTH_BOUNDS)"),
VkDynamicState::STENCIL_COMPARE_MASK =>
{
write!(f, "VkDynamicState(STENCIL_COMPARE_MASK)")
}
VkDynamicState::STENCIL_WRITE_MASK => write!(f, "VkDynamicState(STENCIL_WRITE_MASK)"),
VkDynamicState::STENCIL_REFERENCE => write!(f, "VkDynamicState(STENCIL_REFERENCE)"),
_ => write!(f, "VkDynamicState({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkBlendOp(u32);
impl VkBlendOp
{
pub const ADD: VkBlendOp = VkBlendOp(0);
pub const SUBTRACT: VkBlendOp = VkBlendOp(1);
pub const REVERSE_SUBTRACT: VkBlendOp = VkBlendOp(2);
pub const MIN: VkBlendOp = VkBlendOp(3);
pub const MAX: VkBlendOp = VkBlendOp(4);
}
impl core::fmt::Debug for VkBlendOp
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkBlendOp::ADD => write!(f, "VkBlendOp(ADD)"),
VkBlendOp::SUBTRACT => write!(f, "VkBlendOp(SUBTRACT)"),
VkBlendOp::REVERSE_SUBTRACT => write!(f, "VkBlendOp(REVERSE_SUBTRACT)"),
VkBlendOp::MIN => write!(f, "VkBlendOp(MIN)"),
VkBlendOp::MAX => write!(f, "VkBlendOp(MAX)"),
_ => write!(f, "VkBlendOp({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkBlendFactor(u32);
impl VkBlendFactor
{
pub const ZERO: VkBlendFactor = VkBlendFactor(0);
pub const ONE: VkBlendFactor = VkBlendFactor(1);
pub const SRC_COLOR: VkBlendFactor = VkBlendFactor(2);
pub const ONE_MINUS_SRC_COLOR: VkBlendFactor = VkBlendFactor(3);
pub const DST_COLOR: VkBlendFactor = VkBlendFactor(4);
pub const ONE_MINUS_DST_COLOR: VkBlendFactor = VkBlendFactor(5);
pub const SRC_ALPHA: VkBlendFactor = VkBlendFactor(6);
pub const ONE_MINUS_SRC_ALPHA: VkBlendFactor = VkBlendFactor(7);
pub const DST_ALPHA: VkBlendFactor = VkBlendFactor(8);
pub const ONE_MINUS_DST_ALPHA: VkBlendFactor = VkBlendFactor(9);
pub const CONSTANT_COLOR: VkBlendFactor = VkBlendFactor(10);
pub const ONE_MINUS_CONSTANT_COLOR: VkBlendFactor = VkBlendFactor(11);
pub const CONSTANT_ALPHA: VkBlendFactor = VkBlendFactor(12);
pub const ONE_MINUS_CONSTANT_ALPHA: VkBlendFactor = VkBlendFactor(13);
pub const SRC_ALPHA_SATURATE: VkBlendFactor = VkBlendFactor(14);
pub const SRC1_COLOR: VkBlendFactor = VkBlendFactor(15);
pub const ONE_MINUS_SRC1_COLOR: VkBlendFactor = VkBlendFactor(16);
pub const SRC1_ALPHA: VkBlendFactor = VkBlendFactor(17);
pub const ONE_MINUS_SRC1_ALPHA: VkBlendFactor = VkBlendFactor(18);
}
impl core::fmt::Debug for VkBlendFactor
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkBlendFactor::ZERO => write!(f, "VkBlendFactor(ZERO)"),
VkBlendFactor::ONE => write!(f, "VkBlendFactor(ONE)"),
VkBlendFactor::SRC_COLOR => write!(f, "VkBlendFactor(SRC_COLOR)"),
VkBlendFactor::ONE_MINUS_SRC_COLOR => write!(f, "VkBlendFactor(ONE_MINUS_SRC_COLOR)"),
VkBlendFactor::DST_COLOR => write!(f, "VkBlendFactor(DST_COLOR)"),
VkBlendFactor::ONE_MINUS_DST_COLOR => write!(f, "VkBlendFactor(ONE_MINUS_DST_COLOR)"),
VkBlendFactor::SRC_ALPHA => write!(f, "VkBlendFactor(SRC_ALPHA)"),
VkBlendFactor::ONE_MINUS_SRC_ALPHA => write!(f, "VkBlendFactor(ONE_MINUS_SRC_ALPHA)"),
VkBlendFactor::DST_ALPHA => write!(f, "VkBlendFactor(DST_ALPHA)"),
VkBlendFactor::ONE_MINUS_DST_ALPHA => write!(f, "VkBlendFactor(ONE_MINUS_DST_ALPHA)"),
VkBlendFactor::CONSTANT_COLOR => write!(f, "VkBlendFactor(CONSTANT_COLOR)"),
VkBlendFactor::ONE_MINUS_CONSTANT_COLOR =>
{
write!(f, "VkBlendFactor(ONE_MINUS_CONSTANT_COLOR)")
}
VkBlendFactor::CONSTANT_ALPHA => write!(f, "VkBlendFactor(CONSTANT_ALPHA)"),
VkBlendFactor::ONE_MINUS_CONSTANT_ALPHA =>
{
write!(f, "VkBlendFactor(ONE_MINUS_CONSTANT_ALPHA)")
}
VkBlendFactor::SRC_ALPHA_SATURATE => write!(f, "VkBlendFactor(SRC_ALPHA_SATURATE)"),
VkBlendFactor::SRC1_COLOR => write!(f, "VkBlendFactor(SRC1_COLOR)"),
VkBlendFactor::ONE_MINUS_SRC1_COLOR => write!(f, "VkBlendFactor(ONE_MINUS_SRC1_COLOR)"),
VkBlendFactor::SRC1_ALPHA => write!(f, "VkBlendFactor(SRC1_ALPHA)"),
VkBlendFactor::ONE_MINUS_SRC1_ALPHA => write!(f, "VkBlendFactor(ONE_MINUS_SRC1_ALPHA)"),
_ => write!(f, "VkBlendFactor({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkLogicOp(u32);
impl VkLogicOp
{
pub const CLEAR: VkLogicOp = VkLogicOp(0);
pub const AND: VkLogicOp = VkLogicOp(1);
pub const AND_REVERSE: VkLogicOp = VkLogicOp(2);
pub const COPY: VkLogicOp = VkLogicOp(3);
pub const AND_INVERTED: VkLogicOp = VkLogicOp(4);
pub const NO_OP: VkLogicOp = VkLogicOp(5);
pub const XOR: VkLogicOp = VkLogicOp(6);
pub const OR: VkLogicOp = VkLogicOp(7);
pub const NOR: VkLogicOp = VkLogicOp(8);
pub const EQUIVALENT: VkLogicOp = VkLogicOp(9);
pub const INVERT: VkLogicOp = VkLogicOp(10);
pub const OR_REVERSE: VkLogicOp = VkLogicOp(11);
pub const COPY_INVERTED: VkLogicOp = VkLogicOp(12);
pub const OR_INVERTED: VkLogicOp = VkLogicOp(13);
pub const NAND: VkLogicOp = VkLogicOp(14);
pub const SET: VkLogicOp = VkLogicOp(15);
}
impl core::fmt::Debug for VkLogicOp
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkLogicOp::CLEAR => write!(f, "VkLogicOp(CLEAR)"),
VkLogicOp::AND => write!(f, "VkLogicOp(AND)"),
VkLogicOp::AND_REVERSE => write!(f, "VkLogicOp(AND_REVERSE)"),
VkLogicOp::COPY => write!(f, "VkLogicOp(COPY)"),
VkLogicOp::AND_INVERTED => write!(f, "VkLogicOp(AND_INVERTED)"),
VkLogicOp::NO_OP => write!(f, "VkLogicOp(NO_OP)"),
VkLogicOp::XOR => write!(f, "VkLogicOp(XOR)"),
VkLogicOp::OR => write!(f, "VkLogicOp(OR)"),
VkLogicOp::NOR => write!(f, "VkLogicOp(NOR)"),
VkLogicOp::EQUIVALENT => write!(f, "VkLogicOp(EQUIVALENT)"),
VkLogicOp::INVERT => write!(f, "VkLogicOp(INVERT)"),
VkLogicOp::OR_REVERSE => write!(f, "VkLogicOp(OR_REVERSE)"),
VkLogicOp::COPY_INVERTED => write!(f, "VkLogicOp(COPY_INVERTED)"),
VkLogicOp::OR_INVERTED => write!(f, "VkLogicOp(OR_INVERTED)"),
VkLogicOp::NAND => write!(f, "VkLogicOp(NAND)"),
VkLogicOp::SET => write!(f, "VkLogicOp(SET)"),
_ => write!(f, "VkLogicOp({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkStencilOp(u32);
impl VkStencilOp
{
pub const KEEP: VkStencilOp = VkStencilOp(0);
pub const ZERO: VkStencilOp = VkStencilOp(1);
pub const REPLACE: VkStencilOp = VkStencilOp(2);
pub const INCREMENT_AND_CLAMP: VkStencilOp = VkStencilOp(3);
pub const DECREMENT_AND_CLAMP: VkStencilOp = VkStencilOp(4);
pub const INVERT: VkStencilOp = VkStencilOp(5);
pub const INCREMENT_AND_WRAP: VkStencilOp = VkStencilOp(6);
pub const DECREMENT_AND_WRAP: VkStencilOp = VkStencilOp(7);
}
impl core::fmt::Debug for VkStencilOp
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkStencilOp::KEEP => write!(f, "VkStencilOp(KEEP)"),
VkStencilOp::ZERO => write!(f, "VkStencilOp(ZERO)"),
VkStencilOp::REPLACE => write!(f, "VkStencilOp(REPLACE)"),
VkStencilOp::INCREMENT_AND_CLAMP => write!(f, "VkStencilOp(INCREMENT_AND_CLAMP)"),
VkStencilOp::DECREMENT_AND_CLAMP => write!(f, "VkStencilOp(DECREMENT_AND_CLAMP)"),
VkStencilOp::INVERT => write!(f, "VkStencilOp(INVERT)"),
VkStencilOp::INCREMENT_AND_WRAP => write!(f, "VkStencilOp(INCREMENT_AND_WRAP)"),
VkStencilOp::DECREMENT_AND_WRAP => write!(f, "VkStencilOp(DECREMENT_AND_WRAP)"),
_ => write!(f, "VkStencilOp({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkFrontFace(u32);
impl VkFrontFace
{
pub const COUNTER_CLOCKWISE: VkFrontFace = VkFrontFace(0);
pub const CLOCKWISE: VkFrontFace = VkFrontFace(1);
}
impl core::fmt::Debug for VkFrontFace
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkFrontFace::COUNTER_CLOCKWISE => write!(f, "VkFrontFace(COUNTER_CLOCKWISE)"),
VkFrontFace::CLOCKWISE => write!(f, "VkFrontFace(CLOCKWISE)"),
_ => write!(f, "VkFrontFace({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkPolygonMode(u32);
impl VkPolygonMode
{
pub const FILL: VkPolygonMode = VkPolygonMode(0);
pub const LINE: VkPolygonMode = VkPolygonMode(1);
pub const POINT: VkPolygonMode = VkPolygonMode(2);
}
impl core::fmt::Debug for VkPolygonMode
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkPolygonMode::FILL => write!(f, "VkPolygonMode(FILL)"),
VkPolygonMode::LINE => write!(f, "VkPolygonMode(LINE)"),
VkPolygonMode::POINT => write!(f, "VkPolygonMode(POINT)"),
_ => write!(f, "VkPolygonMode({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkPrimitiveTopology(u32);
impl VkPrimitiveTopology
{
pub const POINT_LIST: VkPrimitiveTopology = VkPrimitiveTopology(0);
pub const LINE_LIST: VkPrimitiveTopology = VkPrimitiveTopology(1);
pub const LINE_STRIP: VkPrimitiveTopology = VkPrimitiveTopology(2);
pub const TRIANGLE_LIST: VkPrimitiveTopology = VkPrimitiveTopology(3);
pub const TRIANGLE_STRIP: VkPrimitiveTopology = VkPrimitiveTopology(4);
pub const TRIANGLE_FAN: VkPrimitiveTopology = VkPrimitiveTopology(5);
pub const LINE_LIST_WITH_ADJACENCY: VkPrimitiveTopology = VkPrimitiveTopology(6);
pub const LINE_STRIP_WITH_ADJACENCY: VkPrimitiveTopology = VkPrimitiveTopology(7);
pub const TRIANGLE_LIST_WITH_ADJACENCY: VkPrimitiveTopology = VkPrimitiveTopology(8);
pub const TRIANGLE_STRIP_WITH_ADJACENCY: VkPrimitiveTopology = VkPrimitiveTopology(9);
pub const PATCH_LIST: VkPrimitiveTopology = VkPrimitiveTopology(10);
}
impl core::fmt::Debug for VkPrimitiveTopology
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkPrimitiveTopology::POINT_LIST => write!(f, "VkPrimitiveTopology(POINT_LIST)"),
VkPrimitiveTopology::LINE_LIST => write!(f, "VkPrimitiveTopology(LINE_LIST)"),
VkPrimitiveTopology::LINE_STRIP => write!(f, "VkPrimitiveTopology(LINE_STRIP)"),
VkPrimitiveTopology::TRIANGLE_LIST => write!(f, "VkPrimitiveTopology(TRIANGLE_LIST)"),
VkPrimitiveTopology::TRIANGLE_STRIP => write!(f, "VkPrimitiveTopology(TRIANGLE_STRIP)"),
VkPrimitiveTopology::TRIANGLE_FAN => write!(f, "VkPrimitiveTopology(TRIANGLE_FAN)"),
VkPrimitiveTopology::LINE_LIST_WITH_ADJACENCY =>
{
write!(f, "VkPrimitiveTopology(LINE_LIST_WITH_ADJACENCY)")
}
VkPrimitiveTopology::LINE_STRIP_WITH_ADJACENCY =>
{
write!(f, "VkPrimitiveTopology(LINE_STRIP_WITH_ADJACENCY)")
}
VkPrimitiveTopology::TRIANGLE_LIST_WITH_ADJACENCY =>
{
write!(f, "VkPrimitiveTopology(TRIANGLE_LIST_WITH_ADJACENCY)")
}
VkPrimitiveTopology::TRIANGLE_STRIP_WITH_ADJACENCY =>
{
write!(f, "VkPrimitiveTopology(TRIANGLE_STRIP_WITH_ADJACENCY)")
}
VkPrimitiveTopology::PATCH_LIST => write!(f, "VkPrimitiveTopology(PATCH_LIST)"),
_ => write!(f, "VkPrimitiveTopology({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkVertexInputRate(u32);
impl VkVertexInputRate
{
pub const VERTEX: VkVertexInputRate = VkVertexInputRate(0);
pub const INSTANCE: VkVertexInputRate = VkVertexInputRate(1);
}
impl core::fmt::Debug for VkVertexInputRate
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkVertexInputRate::VERTEX => write!(f, "VkVertexInputRate(VERTEX)"),
VkVertexInputRate::INSTANCE => write!(f, "VkVertexInputRate(INSTANCE)"),
_ => write!(f, "VkVertexInputRate({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkComponentSwizzle(u32);
impl VkComponentSwizzle
{
pub const IDENTITY: VkComponentSwizzle = VkComponentSwizzle(0);
pub const ZERO: VkComponentSwizzle = VkComponentSwizzle(1);
pub const ONE: VkComponentSwizzle = VkComponentSwizzle(2);
pub const R: VkComponentSwizzle = VkComponentSwizzle(3);
pub const G: VkComponentSwizzle = VkComponentSwizzle(4);
pub const B: VkComponentSwizzle = VkComponentSwizzle(5);
pub const A: VkComponentSwizzle = VkComponentSwizzle(6);
}
impl core::fmt::Debug for VkComponentSwizzle
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkComponentSwizzle::IDENTITY => write!(f, "VkComponentSwizzle(IDENTITY)"),
VkComponentSwizzle::ZERO => write!(f, "VkComponentSwizzle(ZERO)"),
VkComponentSwizzle::ONE => write!(f, "VkComponentSwizzle(ONE)"),
VkComponentSwizzle::R => write!(f, "VkComponentSwizzle(R)"),
VkComponentSwizzle::G => write!(f, "VkComponentSwizzle(G)"),
VkComponentSwizzle::B => write!(f, "VkComponentSwizzle(B)"),
VkComponentSwizzle::A => write!(f, "VkComponentSwizzle(A)"),
_ => write!(f, "VkComponentSwizzle({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkImageViewType(u32);
impl VkImageViewType
{
pub const K_1D: VkImageViewType = VkImageViewType(0);
pub const K_2D: VkImageViewType = VkImageViewType(1);
pub const K_3D: VkImageViewType = VkImageViewType(2);
pub const CUBE: VkImageViewType = VkImageViewType(3);
pub const K_1D_ARRAY: VkImageViewType = VkImageViewType(4);
pub const K_2D_ARRAY: VkImageViewType = VkImageViewType(5);
pub const CUBE_ARRAY: VkImageViewType = VkImageViewType(6);
}
impl core::fmt::Debug for VkImageViewType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkImageViewType::K_1D => write!(f, "VkImageViewType(K_1D)"),
VkImageViewType::K_2D => write!(f, "VkImageViewType(K_2D)"),
VkImageViewType::K_3D => write!(f, "VkImageViewType(K_3D)"),
VkImageViewType::CUBE => write!(f, "VkImageViewType(CUBE)"),
VkImageViewType::K_1D_ARRAY => write!(f, "VkImageViewType(K_1D_ARRAY)"),
VkImageViewType::K_2D_ARRAY => write!(f, "VkImageViewType(K_2D_ARRAY)"),
VkImageViewType::CUBE_ARRAY => write!(f, "VkImageViewType(CUBE_ARRAY)"),
_ => write!(f, "VkImageViewType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkImageTiling(u32);
impl VkImageTiling
{
pub const OPTIMAL: VkImageTiling = VkImageTiling(0);
pub const LINEAR: VkImageTiling = VkImageTiling(1);
}
impl core::fmt::Debug for VkImageTiling
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkImageTiling::OPTIMAL => write!(f, "VkImageTiling(OPTIMAL)"),
VkImageTiling::LINEAR => write!(f, "VkImageTiling(LINEAR)"),
_ => write!(f, "VkImageTiling({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkImageType(u32);
impl VkImageType
{
pub const K_1D: VkImageType = VkImageType(0);
pub const K_2D: VkImageType = VkImageType(1);
pub const K_3D: VkImageType = VkImageType(2);
}
impl core::fmt::Debug for VkImageType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkImageType::K_1D => write!(f, "VkImageType(K_1D)"),
VkImageType::K_2D => write!(f, "VkImageType(K_2D)"),
VkImageType::K_3D => write!(f, "VkImageType(K_3D)"),
_ => write!(f, "VkImageType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkQueryType(u32);
impl VkQueryType
{
pub const OCCLUSION: VkQueryType = VkQueryType(0);
pub const PIPELINE_STATISTICS: VkQueryType = VkQueryType(1);
pub const TIMESTAMP: VkQueryType = VkQueryType(2);
}
impl core::fmt::Debug for VkQueryType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkQueryType::OCCLUSION => write!(f, "VkQueryType(OCCLUSION)"),
VkQueryType::PIPELINE_STATISTICS => write!(f, "VkQueryType(PIPELINE_STATISTICS)"),
VkQueryType::TIMESTAMP => write!(f, "VkQueryType(TIMESTAMP)"),
_ => write!(f, "VkQueryType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkPhysicalDeviceType(u32);
impl VkPhysicalDeviceType
{
pub const OTHER: VkPhysicalDeviceType = VkPhysicalDeviceType(0);
pub const INTEGRATED_GPU: VkPhysicalDeviceType = VkPhysicalDeviceType(1);
pub const DISCRETE_GPU: VkPhysicalDeviceType = VkPhysicalDeviceType(2);
pub const VIRTUAL_GPU: VkPhysicalDeviceType = VkPhysicalDeviceType(3);
pub const CPU: VkPhysicalDeviceType = VkPhysicalDeviceType(4);
}
impl core::fmt::Debug for VkPhysicalDeviceType
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkPhysicalDeviceType::OTHER => write!(f, "VkPhysicalDeviceType(OTHER)"),
VkPhysicalDeviceType::INTEGRATED_GPU =>
{
write!(f, "VkPhysicalDeviceType(INTEGRATED_GPU)")
}
VkPhysicalDeviceType::DISCRETE_GPU => write!(f, "VkPhysicalDeviceType(DISCRETE_GPU)"),
VkPhysicalDeviceType::VIRTUAL_GPU => write!(f, "VkPhysicalDeviceType(VIRTUAL_GPU)"),
VkPhysicalDeviceType::CPU => write!(f, "VkPhysicalDeviceType(CPU)"),
_ => write!(f, "VkPhysicalDeviceType({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, PartialOrd, Copy, Clone, Ord, PartialEq, Eq, Hash)]
pub struct VkPipelineCacheHeaderVersion(u32);
impl VkPipelineCacheHeaderVersion
{
pub const ONE: VkPipelineCacheHeaderVersion = VkPipelineCacheHeaderVersion(1);
}
impl core::fmt::Debug for VkPipelineCacheHeaderVersion
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
match *self
{
VkPipelineCacheHeaderVersion::ONE => write!(f, "VkPipelineCacheHeaderVersion(ONE)"),
_ => write!(f, "VkPipelineCacheHeaderVersion({})", self.0),
}
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkImageUsageFlagBits(VkFlags);
impl VkImageUsageFlagBits
{
pub const TRANSFER_SRC_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(1);
pub const TRANSFER_DST_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(2);
pub const SAMPLED_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(4);
pub const STORAGE_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(8);
pub const COLOR_ATTACHMENT_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(16);
pub const DEPTH_STENCIL_ATTACHMENT_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(32);
pub const TRANSIENT_ATTACHMENT_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(64);
pub const INPUT_ATTACHMENT_BIT: VkImageUsageFlagBits = VkImageUsageFlagBits(128);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkImageUsageFlagBits
{
type Output = VkImageUsageFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkImageUsageFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkImageUsageFlagBits
{
type Output = VkImageUsageFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkImageUsageFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkImageUsageFlagBits
{
type Output = VkImageUsageFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkImageUsageFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkImageUsageFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkImageUsageFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkImageUsageFlagBits::TRANSFER_SRC_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_SRC_BIT")?;
}
if self.contains(VkImageUsageFlagBits::TRANSFER_DST_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_DST_BIT")?;
}
if self.contains(VkImageUsageFlagBits::SAMPLED_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SAMPLED_BIT")?;
}
if self.contains(VkImageUsageFlagBits::STORAGE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STORAGE_BIT")?;
}
if self.contains(VkImageUsageFlagBits::COLOR_ATTACHMENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COLOR_ATTACHMENT_BIT")?;
}
if self.contains(VkImageUsageFlagBits::DEPTH_STENCIL_ATTACHMENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DEPTH_STENCIL_ATTACHMENT_BIT")?;
}
if self.contains(VkImageUsageFlagBits::TRANSIENT_ATTACHMENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSIENT_ATTACHMENT_BIT")?;
}
if self.contains(VkImageUsageFlagBits::INPUT_ATTACHMENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INPUT_ATTACHMENT_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkCompositeAlphaFlagBitsKHR(VkFlags);
impl VkCompositeAlphaFlagBitsKHR
{
pub const OPAQUE_BIT_KHR: VkCompositeAlphaFlagBitsKHR = VkCompositeAlphaFlagBitsKHR(1);
pub const PRE_MULTIPLIED_BIT_KHR: VkCompositeAlphaFlagBitsKHR = VkCompositeAlphaFlagBitsKHR(2);
pub const POST_MULTIPLIED_BIT_KHR: VkCompositeAlphaFlagBitsKHR = VkCompositeAlphaFlagBitsKHR(4);
pub const INHERIT_BIT_KHR: VkCompositeAlphaFlagBitsKHR = VkCompositeAlphaFlagBitsKHR(8);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkCompositeAlphaFlagBitsKHR
{
type Output = VkCompositeAlphaFlagBitsKHR;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkCompositeAlphaFlagBitsKHR
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkCompositeAlphaFlagBitsKHR
{
type Output = VkCompositeAlphaFlagBitsKHR;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkCompositeAlphaFlagBitsKHR
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkCompositeAlphaFlagBitsKHR
{
type Output = VkCompositeAlphaFlagBitsKHR;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkCompositeAlphaFlagBitsKHR
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkCompositeAlphaFlagBitsKHR
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkCompositeAlphaFlagBitsKHR(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkCompositeAlphaFlagBitsKHR::OPAQUE_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("OPAQUE_BIT_KHR")?;
}
if self.contains(VkCompositeAlphaFlagBitsKHR::PRE_MULTIPLIED_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("PRE_MULTIPLIED_BIT_KHR")?;
}
if self.contains(VkCompositeAlphaFlagBitsKHR::POST_MULTIPLIED_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("POST_MULTIPLIED_BIT_KHR")?;
}
if self.contains(VkCompositeAlphaFlagBitsKHR::INHERIT_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INHERIT_BIT_KHR")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkSurfaceTransformFlagBitsKHR(VkFlags);
impl VkSurfaceTransformFlagBitsKHR
{
pub const IDENTITY_BIT_KHR: VkSurfaceTransformFlagBitsKHR = VkSurfaceTransformFlagBitsKHR(1);
pub const ROTATE_90_BIT_KHR: VkSurfaceTransformFlagBitsKHR = VkSurfaceTransformFlagBitsKHR(2);
pub const ROTATE_180_BIT_KHR: VkSurfaceTransformFlagBitsKHR = VkSurfaceTransformFlagBitsKHR(4);
pub const ROTATE_270_BIT_KHR: VkSurfaceTransformFlagBitsKHR = VkSurfaceTransformFlagBitsKHR(8);
pub const HORIZONTAL_MIRROR_BIT_KHR: VkSurfaceTransformFlagBitsKHR =
VkSurfaceTransformFlagBitsKHR(16);
pub const HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR: VkSurfaceTransformFlagBitsKHR =
VkSurfaceTransformFlagBitsKHR(32);
pub const HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR: VkSurfaceTransformFlagBitsKHR =
VkSurfaceTransformFlagBitsKHR(64);
pub const HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR: VkSurfaceTransformFlagBitsKHR =
VkSurfaceTransformFlagBitsKHR(128);
pub const INHERIT_BIT_KHR: VkSurfaceTransformFlagBitsKHR = VkSurfaceTransformFlagBitsKHR(256);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkSurfaceTransformFlagBitsKHR
{
type Output = VkSurfaceTransformFlagBitsKHR;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkSurfaceTransformFlagBitsKHR
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkSurfaceTransformFlagBitsKHR
{
type Output = VkSurfaceTransformFlagBitsKHR;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkSurfaceTransformFlagBitsKHR
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkSurfaceTransformFlagBitsKHR
{
type Output = VkSurfaceTransformFlagBitsKHR;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkSurfaceTransformFlagBitsKHR
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkSurfaceTransformFlagBitsKHR
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkSurfaceTransformFlagBitsKHR(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkSurfaceTransformFlagBitsKHR::IDENTITY_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("IDENTITY_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::ROTATE_90_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ROTATE_90_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::ROTATE_180_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ROTATE_180_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::ROTATE_270_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ROTATE_270_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::HORIZONTAL_MIRROR_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HORIZONTAL_MIRROR_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR")?;
}
if self.contains(VkSurfaceTransformFlagBitsKHR::INHERIT_BIT_KHR)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INHERIT_BIT_KHR")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkSwapchainCreateFlagBitsKHR(VkFlags);
impl VkSwapchainCreateFlagBitsKHR
{
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkSwapchainCreateFlagBitsKHR
{
type Output = VkSwapchainCreateFlagBitsKHR;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkSwapchainCreateFlagBitsKHR
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkSwapchainCreateFlagBitsKHR
{
type Output = VkSwapchainCreateFlagBitsKHR;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkSwapchainCreateFlagBitsKHR
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkSwapchainCreateFlagBitsKHR
{
type Output = VkSwapchainCreateFlagBitsKHR;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkSwapchainCreateFlagBitsKHR
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkSwapchainCreateFlagBitsKHR
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkSwapchainCreateFlagBitsKHR(")?;
#[allow(unused_mut, unused)]
let mut first = true;
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkDebugUtilsMessageTypeFlagBitsEXT(VkFlags);
impl VkDebugUtilsMessageTypeFlagBitsEXT
{
pub const GENERAL_BIT_EXT: VkDebugUtilsMessageTypeFlagBitsEXT =
VkDebugUtilsMessageTypeFlagBitsEXT(1);
pub const VALIDATION_BIT_EXT: VkDebugUtilsMessageTypeFlagBitsEXT =
VkDebugUtilsMessageTypeFlagBitsEXT(2);
pub const PERFORMANCE_BIT_EXT: VkDebugUtilsMessageTypeFlagBitsEXT =
VkDebugUtilsMessageTypeFlagBitsEXT(4);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkDebugUtilsMessageTypeFlagBitsEXT
{
type Output = VkDebugUtilsMessageTypeFlagBitsEXT;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkDebugUtilsMessageTypeFlagBitsEXT
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkDebugUtilsMessageTypeFlagBitsEXT
{
type Output = VkDebugUtilsMessageTypeFlagBitsEXT;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkDebugUtilsMessageTypeFlagBitsEXT
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkDebugUtilsMessageTypeFlagBitsEXT
{
type Output = VkDebugUtilsMessageTypeFlagBitsEXT;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkDebugUtilsMessageTypeFlagBitsEXT
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkDebugUtilsMessageTypeFlagBitsEXT
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkDebugUtilsMessageTypeFlagBitsEXT(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkDebugUtilsMessageTypeFlagBitsEXT::GENERAL_BIT_EXT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("GENERAL_BIT_EXT")?;
}
if self.contains(VkDebugUtilsMessageTypeFlagBitsEXT::VALIDATION_BIT_EXT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VALIDATION_BIT_EXT")?;
}
if self.contains(VkDebugUtilsMessageTypeFlagBitsEXT::PERFORMANCE_BIT_EXT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("PERFORMANCE_BIT_EXT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkDebugUtilsMessageSeverityFlagBitsEXT(VkFlags);
impl VkDebugUtilsMessageSeverityFlagBitsEXT
{
pub const VERBOSE_BIT_EXT: VkDebugUtilsMessageSeverityFlagBitsEXT =
VkDebugUtilsMessageSeverityFlagBitsEXT(1);
pub const INFO_BIT_EXT: VkDebugUtilsMessageSeverityFlagBitsEXT =
VkDebugUtilsMessageSeverityFlagBitsEXT(16);
pub const WARNING_BIT_EXT: VkDebugUtilsMessageSeverityFlagBitsEXT =
VkDebugUtilsMessageSeverityFlagBitsEXT(256);
pub const ERROR_BIT_EXT: VkDebugUtilsMessageSeverityFlagBitsEXT =
VkDebugUtilsMessageSeverityFlagBitsEXT(4096);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkDebugUtilsMessageSeverityFlagBitsEXT
{
type Output = VkDebugUtilsMessageSeverityFlagBitsEXT;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkDebugUtilsMessageSeverityFlagBitsEXT
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkDebugUtilsMessageSeverityFlagBitsEXT
{
type Output = VkDebugUtilsMessageSeverityFlagBitsEXT;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkDebugUtilsMessageSeverityFlagBitsEXT
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkDebugUtilsMessageSeverityFlagBitsEXT
{
type Output = VkDebugUtilsMessageSeverityFlagBitsEXT;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkDebugUtilsMessageSeverityFlagBitsEXT
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkDebugUtilsMessageSeverityFlagBitsEXT
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkDebugUtilsMessageSeverityFlagBitsEXT(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkDebugUtilsMessageSeverityFlagBitsEXT::VERBOSE_BIT_EXT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERBOSE_BIT_EXT")?;
}
if self.contains(VkDebugUtilsMessageSeverityFlagBitsEXT::INFO_BIT_EXT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INFO_BIT_EXT")?;
}
if self.contains(VkDebugUtilsMessageSeverityFlagBitsEXT::WARNING_BIT_EXT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("WARNING_BIT_EXT")?;
}
if self.contains(VkDebugUtilsMessageSeverityFlagBitsEXT::ERROR_BIT_EXT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ERROR_BIT_EXT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkAccessFlagBits(VkFlags);
impl VkAccessFlagBits
{
pub const INDIRECT_COMMAND_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(1);
pub const INDEX_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(2);
pub const VERTEX_ATTRIBUTE_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(4);
pub const UNIFORM_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(8);
pub const INPUT_ATTACHMENT_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(16);
pub const SHADER_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(32);
pub const SHADER_WRITE_BIT: VkAccessFlagBits = VkAccessFlagBits(64);
pub const COLOR_ATTACHMENT_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(128);
pub const COLOR_ATTACHMENT_WRITE_BIT: VkAccessFlagBits = VkAccessFlagBits(256);
pub const DEPTH_STENCIL_ATTACHMENT_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(512);
pub const DEPTH_STENCIL_ATTACHMENT_WRITE_BIT: VkAccessFlagBits = VkAccessFlagBits(1024);
pub const TRANSFER_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(2048);
pub const TRANSFER_WRITE_BIT: VkAccessFlagBits = VkAccessFlagBits(4096);
pub const HOST_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(8192);
pub const HOST_WRITE_BIT: VkAccessFlagBits = VkAccessFlagBits(16384);
pub const MEMORY_READ_BIT: VkAccessFlagBits = VkAccessFlagBits(32768);
pub const MEMORY_WRITE_BIT: VkAccessFlagBits = VkAccessFlagBits(65536);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkAccessFlagBits
{
type Output = VkAccessFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkAccessFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkAccessFlagBits
{
type Output = VkAccessFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkAccessFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkAccessFlagBits
{
type Output = VkAccessFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkAccessFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkAccessFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkAccessFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkAccessFlagBits::INDIRECT_COMMAND_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INDIRECT_COMMAND_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::INDEX_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INDEX_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::VERTEX_ATTRIBUTE_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERTEX_ATTRIBUTE_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::UNIFORM_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("UNIFORM_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::INPUT_ATTACHMENT_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INPUT_ATTACHMENT_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::SHADER_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SHADER_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::SHADER_WRITE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SHADER_WRITE_BIT")?;
}
if self.contains(VkAccessFlagBits::COLOR_ATTACHMENT_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COLOR_ATTACHMENT_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::COLOR_ATTACHMENT_WRITE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COLOR_ATTACHMENT_WRITE_BIT")?;
}
if self.contains(VkAccessFlagBits::DEPTH_STENCIL_ATTACHMENT_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DEPTH_STENCIL_ATTACHMENT_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::DEPTH_STENCIL_ATTACHMENT_WRITE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DEPTH_STENCIL_ATTACHMENT_WRITE_BIT")?;
}
if self.contains(VkAccessFlagBits::TRANSFER_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::TRANSFER_WRITE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_WRITE_BIT")?;
}
if self.contains(VkAccessFlagBits::HOST_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HOST_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::HOST_WRITE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HOST_WRITE_BIT")?;
}
if self.contains(VkAccessFlagBits::MEMORY_READ_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("MEMORY_READ_BIT")?;
}
if self.contains(VkAccessFlagBits::MEMORY_WRITE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("MEMORY_WRITE_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkImageAspectFlagBits(VkFlags);
impl VkImageAspectFlagBits
{
pub const COLOR_BIT: VkImageAspectFlagBits = VkImageAspectFlagBits(1);
pub const DEPTH_BIT: VkImageAspectFlagBits = VkImageAspectFlagBits(2);
pub const STENCIL_BIT: VkImageAspectFlagBits = VkImageAspectFlagBits(4);
pub const METADATA_BIT: VkImageAspectFlagBits = VkImageAspectFlagBits(8);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkImageAspectFlagBits
{
type Output = VkImageAspectFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkImageAspectFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkImageAspectFlagBits
{
type Output = VkImageAspectFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkImageAspectFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkImageAspectFlagBits
{
type Output = VkImageAspectFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkImageAspectFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkImageAspectFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkImageAspectFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkImageAspectFlagBits::COLOR_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COLOR_BIT")?;
}
if self.contains(VkImageAspectFlagBits::DEPTH_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DEPTH_BIT")?;
}
if self.contains(VkImageAspectFlagBits::STENCIL_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STENCIL_BIT")?;
}
if self.contains(VkImageAspectFlagBits::METADATA_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("METADATA_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkShaderStageFlagBits(VkFlags);
impl VkShaderStageFlagBits
{
pub const VERTEX_BIT: VkShaderStageFlagBits = VkShaderStageFlagBits(1);
pub const TESSELLATION_CONTROL_BIT: VkShaderStageFlagBits = VkShaderStageFlagBits(2);
pub const TESSELLATION_EVALUATION_BIT: VkShaderStageFlagBits = VkShaderStageFlagBits(4);
pub const GEOMETRY_BIT: VkShaderStageFlagBits = VkShaderStageFlagBits(8);
pub const FRAGMENT_BIT: VkShaderStageFlagBits = VkShaderStageFlagBits(16);
pub const ALL_GRAPHICS: VkShaderStageFlagBits = VkShaderStageFlagBits(31);
pub const COMPUTE_BIT: VkShaderStageFlagBits = VkShaderStageFlagBits(32);
pub const ALL: VkShaderStageFlagBits = VkShaderStageFlagBits(2147483647);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkShaderStageFlagBits
{
type Output = VkShaderStageFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkShaderStageFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkShaderStageFlagBits
{
type Output = VkShaderStageFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkShaderStageFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkShaderStageFlagBits
{
type Output = VkShaderStageFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkShaderStageFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkShaderStageFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkShaderStageFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkShaderStageFlagBits::VERTEX_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERTEX_BIT")?;
}
if self.contains(VkShaderStageFlagBits::TESSELLATION_CONTROL_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TESSELLATION_CONTROL_BIT")?;
}
if self.contains(VkShaderStageFlagBits::TESSELLATION_EVALUATION_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TESSELLATION_EVALUATION_BIT")?;
}
if self.contains(VkShaderStageFlagBits::GEOMETRY_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("GEOMETRY_BIT")?;
}
if self.contains(VkShaderStageFlagBits::FRAGMENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FRAGMENT_BIT")?;
}
if self.contains(VkShaderStageFlagBits::ALL_GRAPHICS)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ALL_GRAPHICS")?;
}
if self.contains(VkShaderStageFlagBits::COMPUTE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COMPUTE_BIT")?;
}
if self.contains(VkShaderStageFlagBits::ALL)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ALL")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkQueryResultFlagBits(VkFlags);
impl VkQueryResultFlagBits
{
pub const K_64_BIT: VkQueryResultFlagBits = VkQueryResultFlagBits(1);
pub const WAIT_BIT: VkQueryResultFlagBits = VkQueryResultFlagBits(2);
pub const WITH_AVAILABILITY_BIT: VkQueryResultFlagBits = VkQueryResultFlagBits(4);
pub const PARTIAL_BIT: VkQueryResultFlagBits = VkQueryResultFlagBits(8);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkQueryResultFlagBits
{
type Output = VkQueryResultFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkQueryResultFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkQueryResultFlagBits
{
type Output = VkQueryResultFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkQueryResultFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkQueryResultFlagBits
{
type Output = VkQueryResultFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkQueryResultFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkQueryResultFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkQueryResultFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkQueryResultFlagBits::K_64_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_64_BIT")?;
}
if self.contains(VkQueryResultFlagBits::WAIT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("WAIT_BIT")?;
}
if self.contains(VkQueryResultFlagBits::WITH_AVAILABILITY_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("WITH_AVAILABILITY_BIT")?;
}
if self.contains(VkQueryResultFlagBits::PARTIAL_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("PARTIAL_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkPipelineStageFlagBits(VkFlags);
impl VkPipelineStageFlagBits
{
pub const TOP_OF_PIPE_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(1);
pub const DRAW_INDIRECT_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(2);
pub const VERTEX_INPUT_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(4);
pub const VERTEX_SHADER_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(8);
pub const TESSELLATION_CONTROL_SHADER_BIT: VkPipelineStageFlagBits =
VkPipelineStageFlagBits(16);
pub const TESSELLATION_EVALUATION_SHADER_BIT: VkPipelineStageFlagBits =
VkPipelineStageFlagBits(32);
pub const GEOMETRY_SHADER_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(64);
pub const FRAGMENT_SHADER_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(128);
pub const EARLY_FRAGMENT_TESTS_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(256);
pub const LATE_FRAGMENT_TESTS_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(512);
pub const COLOR_ATTACHMENT_OUTPUT_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(1024);
pub const COMPUTE_SHADER_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(2048);
pub const TRANSFER_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(4096);
pub const BOTTOM_OF_PIPE_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(8192);
pub const HOST_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(16384);
pub const ALL_GRAPHICS_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(32768);
pub const ALL_COMMANDS_BIT: VkPipelineStageFlagBits = VkPipelineStageFlagBits(65536);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkPipelineStageFlagBits
{
type Output = VkPipelineStageFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkPipelineStageFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkPipelineStageFlagBits
{
type Output = VkPipelineStageFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkPipelineStageFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkPipelineStageFlagBits
{
type Output = VkPipelineStageFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkPipelineStageFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkPipelineStageFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkPipelineStageFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkPipelineStageFlagBits::TOP_OF_PIPE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TOP_OF_PIPE_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::DRAW_INDIRECT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DRAW_INDIRECT_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::VERTEX_INPUT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERTEX_INPUT_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::VERTEX_SHADER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERTEX_SHADER_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::TESSELLATION_CONTROL_SHADER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TESSELLATION_CONTROL_SHADER_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::TESSELLATION_EVALUATION_SHADER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TESSELLATION_EVALUATION_SHADER_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::GEOMETRY_SHADER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("GEOMETRY_SHADER_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::FRAGMENT_SHADER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FRAGMENT_SHADER_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::EARLY_FRAGMENT_TESTS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("EARLY_FRAGMENT_TESTS_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::LATE_FRAGMENT_TESTS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("LATE_FRAGMENT_TESTS_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::COLOR_ATTACHMENT_OUTPUT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COLOR_ATTACHMENT_OUTPUT_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::COMPUTE_SHADER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COMPUTE_SHADER_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::TRANSFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::BOTTOM_OF_PIPE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("BOTTOM_OF_PIPE_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::HOST_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HOST_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::ALL_GRAPHICS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ALL_GRAPHICS_BIT")?;
}
if self.contains(VkPipelineStageFlagBits::ALL_COMMANDS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ALL_COMMANDS_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkQueryControlFlagBits(VkFlags);
impl VkQueryControlFlagBits
{
pub const PRECISE_BIT: VkQueryControlFlagBits = VkQueryControlFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkQueryControlFlagBits
{
type Output = VkQueryControlFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkQueryControlFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkQueryControlFlagBits
{
type Output = VkQueryControlFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkQueryControlFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkQueryControlFlagBits
{
type Output = VkQueryControlFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkQueryControlFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkQueryControlFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkQueryControlFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkQueryControlFlagBits::PRECISE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("PRECISE_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkDependencyFlagBits(VkFlags);
impl VkDependencyFlagBits
{
pub const BY_REGION_BIT: VkDependencyFlagBits = VkDependencyFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkDependencyFlagBits
{
type Output = VkDependencyFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkDependencyFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkDependencyFlagBits
{
type Output = VkDependencyFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkDependencyFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkDependencyFlagBits
{
type Output = VkDependencyFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkDependencyFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkDependencyFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkDependencyFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkDependencyFlagBits::BY_REGION_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("BY_REGION_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkStencilFaceFlagBits(VkFlags);
impl VkStencilFaceFlagBits
{
pub const FRONT_BIT: VkStencilFaceFlagBits = VkStencilFaceFlagBits(1);
pub const BACK_BIT: VkStencilFaceFlagBits = VkStencilFaceFlagBits(2);
pub const FRONT_AND_BACK: VkStencilFaceFlagBits = VkStencilFaceFlagBits(3);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkStencilFaceFlagBits
{
type Output = VkStencilFaceFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkStencilFaceFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkStencilFaceFlagBits
{
type Output = VkStencilFaceFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkStencilFaceFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkStencilFaceFlagBits
{
type Output = VkStencilFaceFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkStencilFaceFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkStencilFaceFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkStencilFaceFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkStencilFaceFlagBits::FRONT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FRONT_BIT")?;
}
if self.contains(VkStencilFaceFlagBits::BACK_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("BACK_BIT")?;
}
if self.contains(VkStencilFaceFlagBits::FRONT_AND_BACK)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FRONT_AND_BACK")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkCommandBufferResetFlagBits(VkFlags);
impl VkCommandBufferResetFlagBits
{
pub const RELEASE_RESOURCES_BIT: VkCommandBufferResetFlagBits = VkCommandBufferResetFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkCommandBufferResetFlagBits
{
type Output = VkCommandBufferResetFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkCommandBufferResetFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkCommandBufferResetFlagBits
{
type Output = VkCommandBufferResetFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkCommandBufferResetFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkCommandBufferResetFlagBits
{
type Output = VkCommandBufferResetFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkCommandBufferResetFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkCommandBufferResetFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkCommandBufferResetFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkCommandBufferResetFlagBits::RELEASE_RESOURCES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("RELEASE_RESOURCES_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkQueryPipelineStatisticFlagBits(VkFlags);
impl VkQueryPipelineStatisticFlagBits
{
pub const INPUT_ASSEMBLY_VERTICES_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(1);
pub const INPUT_ASSEMBLY_PRIMITIVES_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(2);
pub const VERTEX_SHADER_INVOCATIONS_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(4);
pub const GEOMETRY_SHADER_INVOCATIONS_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(8);
pub const GEOMETRY_SHADER_PRIMITIVES_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(16);
pub const CLIPPING_INVOCATIONS_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(32);
pub const CLIPPING_PRIMITIVES_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(64);
pub const FRAGMENT_SHADER_INVOCATIONS_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(128);
pub const TESSELLATION_CONTROL_SHADER_PATCHES_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(256);
pub const TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(512);
pub const COMPUTE_SHADER_INVOCATIONS_BIT: VkQueryPipelineStatisticFlagBits =
VkQueryPipelineStatisticFlagBits(1024);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkQueryPipelineStatisticFlagBits
{
type Output = VkQueryPipelineStatisticFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkQueryPipelineStatisticFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkQueryPipelineStatisticFlagBits
{
type Output = VkQueryPipelineStatisticFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkQueryPipelineStatisticFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkQueryPipelineStatisticFlagBits
{
type Output = VkQueryPipelineStatisticFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkQueryPipelineStatisticFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkQueryPipelineStatisticFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkQueryPipelineStatisticFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkQueryPipelineStatisticFlagBits::INPUT_ASSEMBLY_VERTICES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INPUT_ASSEMBLY_VERTICES_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::INPUT_ASSEMBLY_PRIMITIVES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INPUT_ASSEMBLY_PRIMITIVES_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::VERTEX_SHADER_INVOCATIONS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERTEX_SHADER_INVOCATIONS_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::GEOMETRY_SHADER_INVOCATIONS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("GEOMETRY_SHADER_INVOCATIONS_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::GEOMETRY_SHADER_PRIMITIVES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("GEOMETRY_SHADER_PRIMITIVES_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::CLIPPING_INVOCATIONS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("CLIPPING_INVOCATIONS_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::CLIPPING_PRIMITIVES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("CLIPPING_PRIMITIVES_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::FRAGMENT_SHADER_INVOCATIONS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FRAGMENT_SHADER_INVOCATIONS_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::TESSELLATION_CONTROL_SHADER_PATCHES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TESSELLATION_CONTROL_SHADER_PATCHES_BIT")?;
}
if self.contains(
VkQueryPipelineStatisticFlagBits::TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT,
)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT")?;
}
if self.contains(VkQueryPipelineStatisticFlagBits::COMPUTE_SHADER_INVOCATIONS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COMPUTE_SHADER_INVOCATIONS_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkCommandBufferUsageFlagBits(VkFlags);
impl VkCommandBufferUsageFlagBits
{
pub const ONE_TIME_SUBMIT_BIT: VkCommandBufferUsageFlagBits = VkCommandBufferUsageFlagBits(1);
pub const RENDER_PASS_CONTINUE_BIT: VkCommandBufferUsageFlagBits =
VkCommandBufferUsageFlagBits(2);
pub const SIMULTANEOUS_USE_BIT: VkCommandBufferUsageFlagBits = VkCommandBufferUsageFlagBits(4);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkCommandBufferUsageFlagBits
{
type Output = VkCommandBufferUsageFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkCommandBufferUsageFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkCommandBufferUsageFlagBits
{
type Output = VkCommandBufferUsageFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkCommandBufferUsageFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkCommandBufferUsageFlagBits
{
type Output = VkCommandBufferUsageFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkCommandBufferUsageFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkCommandBufferUsageFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkCommandBufferUsageFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkCommandBufferUsageFlagBits::ONE_TIME_SUBMIT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ONE_TIME_SUBMIT_BIT")?;
}
if self.contains(VkCommandBufferUsageFlagBits::RENDER_PASS_CONTINUE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("RENDER_PASS_CONTINUE_BIT")?;
}
if self.contains(VkCommandBufferUsageFlagBits::SIMULTANEOUS_USE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SIMULTANEOUS_USE_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkCommandPoolResetFlagBits(VkFlags);
impl VkCommandPoolResetFlagBits
{
pub const RELEASE_RESOURCES_BIT: VkCommandPoolResetFlagBits = VkCommandPoolResetFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkCommandPoolResetFlagBits
{
type Output = VkCommandPoolResetFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkCommandPoolResetFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkCommandPoolResetFlagBits
{
type Output = VkCommandPoolResetFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkCommandPoolResetFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkCommandPoolResetFlagBits
{
type Output = VkCommandPoolResetFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkCommandPoolResetFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkCommandPoolResetFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkCommandPoolResetFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkCommandPoolResetFlagBits::RELEASE_RESOURCES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("RELEASE_RESOURCES_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkCommandPoolCreateFlagBits(VkFlags);
impl VkCommandPoolCreateFlagBits
{
pub const TRANSIENT_BIT: VkCommandPoolCreateFlagBits = VkCommandPoolCreateFlagBits(1);
pub const RESET_COMMAND_BUFFER_BIT: VkCommandPoolCreateFlagBits =
VkCommandPoolCreateFlagBits(2);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkCommandPoolCreateFlagBits
{
type Output = VkCommandPoolCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkCommandPoolCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkCommandPoolCreateFlagBits
{
type Output = VkCommandPoolCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkCommandPoolCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkCommandPoolCreateFlagBits
{
type Output = VkCommandPoolCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkCommandPoolCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkCommandPoolCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkCommandPoolCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkCommandPoolCreateFlagBits::TRANSIENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSIENT_BIT")?;
}
if self.contains(VkCommandPoolCreateFlagBits::RESET_COMMAND_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("RESET_COMMAND_BUFFER_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkSubpassDescriptionFlagBits(VkFlags);
impl VkSubpassDescriptionFlagBits
{
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkSubpassDescriptionFlagBits
{
type Output = VkSubpassDescriptionFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkSubpassDescriptionFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkSubpassDescriptionFlagBits
{
type Output = VkSubpassDescriptionFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkSubpassDescriptionFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkSubpassDescriptionFlagBits
{
type Output = VkSubpassDescriptionFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkSubpassDescriptionFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkSubpassDescriptionFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkSubpassDescriptionFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkSampleCountFlagBits(VkFlags);
impl VkSampleCountFlagBits
{
pub const K_1_BIT: VkSampleCountFlagBits = VkSampleCountFlagBits(1);
pub const K_2_BIT: VkSampleCountFlagBits = VkSampleCountFlagBits(2);
pub const K_4_BIT: VkSampleCountFlagBits = VkSampleCountFlagBits(4);
pub const K_8_BIT: VkSampleCountFlagBits = VkSampleCountFlagBits(8);
pub const K_16_BIT: VkSampleCountFlagBits = VkSampleCountFlagBits(16);
pub const K_32_BIT: VkSampleCountFlagBits = VkSampleCountFlagBits(32);
pub const K_64_BIT: VkSampleCountFlagBits = VkSampleCountFlagBits(64);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkSampleCountFlagBits
{
type Output = VkSampleCountFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkSampleCountFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkSampleCountFlagBits
{
type Output = VkSampleCountFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkSampleCountFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkSampleCountFlagBits
{
type Output = VkSampleCountFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkSampleCountFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkSampleCountFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkSampleCountFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkSampleCountFlagBits::K_1_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_1_BIT")?;
}
if self.contains(VkSampleCountFlagBits::K_2_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_2_BIT")?;
}
if self.contains(VkSampleCountFlagBits::K_4_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_4_BIT")?;
}
if self.contains(VkSampleCountFlagBits::K_8_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_8_BIT")?;
}
if self.contains(VkSampleCountFlagBits::K_16_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_16_BIT")?;
}
if self.contains(VkSampleCountFlagBits::K_32_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_32_BIT")?;
}
if self.contains(VkSampleCountFlagBits::K_64_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("K_64_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkAttachmentDescriptionFlagBits(VkFlags);
impl VkAttachmentDescriptionFlagBits
{
pub const MAY_ALIAS_BIT: VkAttachmentDescriptionFlagBits = VkAttachmentDescriptionFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkAttachmentDescriptionFlagBits
{
type Output = VkAttachmentDescriptionFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkAttachmentDescriptionFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkAttachmentDescriptionFlagBits
{
type Output = VkAttachmentDescriptionFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkAttachmentDescriptionFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkAttachmentDescriptionFlagBits
{
type Output = VkAttachmentDescriptionFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkAttachmentDescriptionFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkAttachmentDescriptionFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkAttachmentDescriptionFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkAttachmentDescriptionFlagBits::MAY_ALIAS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("MAY_ALIAS_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkDescriptorPoolCreateFlagBits(VkFlags);
impl VkDescriptorPoolCreateFlagBits
{
pub const FREE_DESCRIPTOR_SET_BIT: VkDescriptorPoolCreateFlagBits =
VkDescriptorPoolCreateFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkDescriptorPoolCreateFlagBits
{
type Output = VkDescriptorPoolCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkDescriptorPoolCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkDescriptorPoolCreateFlagBits
{
type Output = VkDescriptorPoolCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkDescriptorPoolCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkDescriptorPoolCreateFlagBits
{
type Output = VkDescriptorPoolCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkDescriptorPoolCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkDescriptorPoolCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkDescriptorPoolCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkDescriptorPoolCreateFlagBits::FREE_DESCRIPTOR_SET_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FREE_DESCRIPTOR_SET_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkDescriptorSetLayoutCreateFlagBits(VkFlags);
impl VkDescriptorSetLayoutCreateFlagBits
{
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkDescriptorSetLayoutCreateFlagBits
{
type Output = VkDescriptorSetLayoutCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkDescriptorSetLayoutCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkDescriptorSetLayoutCreateFlagBits
{
type Output = VkDescriptorSetLayoutCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkDescriptorSetLayoutCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkDescriptorSetLayoutCreateFlagBits
{
type Output = VkDescriptorSetLayoutCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkDescriptorSetLayoutCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkDescriptorSetLayoutCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkDescriptorSetLayoutCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkSamplerCreateFlagBits(VkFlags);
impl VkSamplerCreateFlagBits
{
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkSamplerCreateFlagBits
{
type Output = VkSamplerCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkSamplerCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkSamplerCreateFlagBits
{
type Output = VkSamplerCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkSamplerCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkSamplerCreateFlagBits
{
type Output = VkSamplerCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkSamplerCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkSamplerCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkSamplerCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkPipelineCreateFlagBits(VkFlags);
impl VkPipelineCreateFlagBits
{
pub const DISABLE_OPTIMIZATION_BIT: VkPipelineCreateFlagBits = VkPipelineCreateFlagBits(1);
pub const ALLOW_DERIVATIVES_BIT: VkPipelineCreateFlagBits = VkPipelineCreateFlagBits(2);
pub const DERIVATIVE_BIT: VkPipelineCreateFlagBits = VkPipelineCreateFlagBits(4);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkPipelineCreateFlagBits
{
type Output = VkPipelineCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkPipelineCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkPipelineCreateFlagBits
{
type Output = VkPipelineCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkPipelineCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkPipelineCreateFlagBits
{
type Output = VkPipelineCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkPipelineCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkPipelineCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkPipelineCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkPipelineCreateFlagBits::DISABLE_OPTIMIZATION_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DISABLE_OPTIMIZATION_BIT")?;
}
if self.contains(VkPipelineCreateFlagBits::ALLOW_DERIVATIVES_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ALLOW_DERIVATIVES_BIT")?;
}
if self.contains(VkPipelineCreateFlagBits::DERIVATIVE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DERIVATIVE_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkColorComponentFlagBits(VkFlags);
impl VkColorComponentFlagBits
{
pub const R_BIT: VkColorComponentFlagBits = VkColorComponentFlagBits(1);
pub const G_BIT: VkColorComponentFlagBits = VkColorComponentFlagBits(2);
pub const B_BIT: VkColorComponentFlagBits = VkColorComponentFlagBits(4);
pub const A_BIT: VkColorComponentFlagBits = VkColorComponentFlagBits(8);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkColorComponentFlagBits
{
type Output = VkColorComponentFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkColorComponentFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkColorComponentFlagBits
{
type Output = VkColorComponentFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkColorComponentFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkColorComponentFlagBits
{
type Output = VkColorComponentFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkColorComponentFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkColorComponentFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkColorComponentFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkColorComponentFlagBits::R_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("R_BIT")?;
}
if self.contains(VkColorComponentFlagBits::G_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("G_BIT")?;
}
if self.contains(VkColorComponentFlagBits::B_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("B_BIT")?;
}
if self.contains(VkColorComponentFlagBits::A_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("A_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkCullModeFlagBits(VkFlags);
impl VkCullModeFlagBits
{
pub const NONE: VkCullModeFlagBits = VkCullModeFlagBits(0);
pub const FRONT_BIT: VkCullModeFlagBits = VkCullModeFlagBits(1);
pub const BACK_BIT: VkCullModeFlagBits = VkCullModeFlagBits(2);
pub const FRONT_AND_BACK: VkCullModeFlagBits = VkCullModeFlagBits(3);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkCullModeFlagBits
{
type Output = VkCullModeFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkCullModeFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkCullModeFlagBits
{
type Output = VkCullModeFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkCullModeFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkCullModeFlagBits
{
type Output = VkCullModeFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkCullModeFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkCullModeFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkCullModeFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkCullModeFlagBits::NONE)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("NONE")?;
}
if self.contains(VkCullModeFlagBits::FRONT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FRONT_BIT")?;
}
if self.contains(VkCullModeFlagBits::BACK_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("BACK_BIT")?;
}
if self.contains(VkCullModeFlagBits::FRONT_AND_BACK)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("FRONT_AND_BACK")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkImageViewCreateFlagBits(VkFlags);
impl VkImageViewCreateFlagBits
{
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkImageViewCreateFlagBits
{
type Output = VkImageViewCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkImageViewCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkImageViewCreateFlagBits
{
type Output = VkImageViewCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkImageViewCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkImageViewCreateFlagBits
{
type Output = VkImageViewCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkImageViewCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkImageViewCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkImageViewCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkImageCreateFlagBits(VkFlags);
impl VkImageCreateFlagBits
{
pub const SPARSE_BINDING_BIT: VkImageCreateFlagBits = VkImageCreateFlagBits(1);
pub const SPARSE_RESIDENCY_BIT: VkImageCreateFlagBits = VkImageCreateFlagBits(2);
pub const SPARSE_ALIASED_BIT: VkImageCreateFlagBits = VkImageCreateFlagBits(4);
pub const MUTABLE_FORMAT_BIT: VkImageCreateFlagBits = VkImageCreateFlagBits(8);
pub const CUBE_COMPATIBLE_BIT: VkImageCreateFlagBits = VkImageCreateFlagBits(16);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkImageCreateFlagBits
{
type Output = VkImageCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkImageCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkImageCreateFlagBits
{
type Output = VkImageCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkImageCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkImageCreateFlagBits
{
type Output = VkImageCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkImageCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkImageCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkImageCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkImageCreateFlagBits::SPARSE_BINDING_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SPARSE_BINDING_BIT")?;
}
if self.contains(VkImageCreateFlagBits::SPARSE_RESIDENCY_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SPARSE_RESIDENCY_BIT")?;
}
if self.contains(VkImageCreateFlagBits::SPARSE_ALIASED_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SPARSE_ALIASED_BIT")?;
}
if self.contains(VkImageCreateFlagBits::MUTABLE_FORMAT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("MUTABLE_FORMAT_BIT")?;
}
if self.contains(VkImageCreateFlagBits::CUBE_COMPATIBLE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("CUBE_COMPATIBLE_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkBufferUsageFlagBits(VkFlags);
impl VkBufferUsageFlagBits
{
pub const TRANSFER_SRC_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(1);
pub const TRANSFER_DST_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(2);
pub const UNIFORM_TEXEL_BUFFER_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(4);
pub const STORAGE_TEXEL_BUFFER_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(8);
pub const UNIFORM_BUFFER_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(16);
pub const STORAGE_BUFFER_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(32);
pub const INDEX_BUFFER_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(64);
pub const VERTEX_BUFFER_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(128);
pub const INDIRECT_BUFFER_BIT: VkBufferUsageFlagBits = VkBufferUsageFlagBits(256);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkBufferUsageFlagBits
{
type Output = VkBufferUsageFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkBufferUsageFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkBufferUsageFlagBits
{
type Output = VkBufferUsageFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkBufferUsageFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkBufferUsageFlagBits
{
type Output = VkBufferUsageFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkBufferUsageFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkBufferUsageFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkBufferUsageFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkBufferUsageFlagBits::TRANSFER_SRC_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_SRC_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::TRANSFER_DST_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_DST_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::UNIFORM_TEXEL_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("UNIFORM_TEXEL_BUFFER_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::STORAGE_TEXEL_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STORAGE_TEXEL_BUFFER_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::UNIFORM_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("UNIFORM_BUFFER_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::STORAGE_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STORAGE_BUFFER_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::INDEX_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INDEX_BUFFER_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::VERTEX_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERTEX_BUFFER_BIT")?;
}
if self.contains(VkBufferUsageFlagBits::INDIRECT_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("INDIRECT_BUFFER_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkBufferCreateFlagBits(VkFlags);
impl VkBufferCreateFlagBits
{
pub const SPARSE_BINDING_BIT: VkBufferCreateFlagBits = VkBufferCreateFlagBits(1);
pub const SPARSE_RESIDENCY_BIT: VkBufferCreateFlagBits = VkBufferCreateFlagBits(2);
pub const SPARSE_ALIASED_BIT: VkBufferCreateFlagBits = VkBufferCreateFlagBits(4);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkBufferCreateFlagBits
{
type Output = VkBufferCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkBufferCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkBufferCreateFlagBits
{
type Output = VkBufferCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkBufferCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkBufferCreateFlagBits
{
type Output = VkBufferCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkBufferCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkBufferCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkBufferCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkBufferCreateFlagBits::SPARSE_BINDING_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SPARSE_BINDING_BIT")?;
}
if self.contains(VkBufferCreateFlagBits::SPARSE_RESIDENCY_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SPARSE_RESIDENCY_BIT")?;
}
if self.contains(VkBufferCreateFlagBits::SPARSE_ALIASED_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SPARSE_ALIASED_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkFenceCreateFlagBits(VkFlags);
impl VkFenceCreateFlagBits
{
pub const SIGNALED_BIT: VkFenceCreateFlagBits = VkFenceCreateFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkFenceCreateFlagBits
{
type Output = VkFenceCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkFenceCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkFenceCreateFlagBits
{
type Output = VkFenceCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkFenceCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkFenceCreateFlagBits
{
type Output = VkFenceCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkFenceCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkFenceCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkFenceCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkFenceCreateFlagBits::SIGNALED_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SIGNALED_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkSparseMemoryBindFlagBits(VkFlags);
impl VkSparseMemoryBindFlagBits
{
pub const METADATA_BIT: VkSparseMemoryBindFlagBits = VkSparseMemoryBindFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkSparseMemoryBindFlagBits
{
type Output = VkSparseMemoryBindFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkSparseMemoryBindFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkSparseMemoryBindFlagBits
{
type Output = VkSparseMemoryBindFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkSparseMemoryBindFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkSparseMemoryBindFlagBits
{
type Output = VkSparseMemoryBindFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkSparseMemoryBindFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkSparseMemoryBindFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkSparseMemoryBindFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkSparseMemoryBindFlagBits::METADATA_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("METADATA_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkSparseImageFormatFlagBits(VkFlags);
impl VkSparseImageFormatFlagBits
{
pub const SINGLE_MIPTAIL_BIT: VkSparseImageFormatFlagBits = VkSparseImageFormatFlagBits(1);
pub const ALIGNED_MIP_SIZE_BIT: VkSparseImageFormatFlagBits = VkSparseImageFormatFlagBits(2);
pub const NONSTANDARD_BLOCK_SIZE_BIT: VkSparseImageFormatFlagBits =
VkSparseImageFormatFlagBits(4);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkSparseImageFormatFlagBits
{
type Output = VkSparseImageFormatFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkSparseImageFormatFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkSparseImageFormatFlagBits
{
type Output = VkSparseImageFormatFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkSparseImageFormatFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkSparseImageFormatFlagBits
{
type Output = VkSparseImageFormatFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkSparseImageFormatFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkSparseImageFormatFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkSparseImageFormatFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkSparseImageFormatFlagBits::SINGLE_MIPTAIL_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SINGLE_MIPTAIL_BIT")?;
}
if self.contains(VkSparseImageFormatFlagBits::ALIGNED_MIP_SIZE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("ALIGNED_MIP_SIZE_BIT")?;
}
if self.contains(VkSparseImageFormatFlagBits::NONSTANDARD_BLOCK_SIZE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("NONSTANDARD_BLOCK_SIZE_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkDeviceQueueCreateFlagBits(VkFlags);
impl VkDeviceQueueCreateFlagBits
{
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkDeviceQueueCreateFlagBits
{
type Output = VkDeviceQueueCreateFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkDeviceQueueCreateFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkDeviceQueueCreateFlagBits
{
type Output = VkDeviceQueueCreateFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkDeviceQueueCreateFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkDeviceQueueCreateFlagBits
{
type Output = VkDeviceQueueCreateFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkDeviceQueueCreateFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkDeviceQueueCreateFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkDeviceQueueCreateFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkMemoryHeapFlagBits(VkFlags);
impl VkMemoryHeapFlagBits
{
pub const DEVICE_LOCAL_BIT: VkMemoryHeapFlagBits = VkMemoryHeapFlagBits(1);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkMemoryHeapFlagBits
{
type Output = VkMemoryHeapFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkMemoryHeapFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkMemoryHeapFlagBits
{
type Output = VkMemoryHeapFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkMemoryHeapFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkMemoryHeapFlagBits
{
type Output = VkMemoryHeapFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkMemoryHeapFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkMemoryHeapFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkMemoryHeapFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkMemoryHeapFlagBits::DEVICE_LOCAL_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DEVICE_LOCAL_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkMemoryPropertyFlagBits(VkFlags);
impl VkMemoryPropertyFlagBits
{
pub const DEVICE_LOCAL_BIT: VkMemoryPropertyFlagBits = VkMemoryPropertyFlagBits(1);
pub const HOST_VISIBLE_BIT: VkMemoryPropertyFlagBits = VkMemoryPropertyFlagBits(2);
pub const HOST_COHERENT_BIT: VkMemoryPropertyFlagBits = VkMemoryPropertyFlagBits(4);
pub const HOST_CACHED_BIT: VkMemoryPropertyFlagBits = VkMemoryPropertyFlagBits(8);
pub const LAZILY_ALLOCATED_BIT: VkMemoryPropertyFlagBits = VkMemoryPropertyFlagBits(16);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkMemoryPropertyFlagBits
{
type Output = VkMemoryPropertyFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkMemoryPropertyFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkMemoryPropertyFlagBits
{
type Output = VkMemoryPropertyFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkMemoryPropertyFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkMemoryPropertyFlagBits
{
type Output = VkMemoryPropertyFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkMemoryPropertyFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkMemoryPropertyFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkMemoryPropertyFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkMemoryPropertyFlagBits::DEVICE_LOCAL_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DEVICE_LOCAL_BIT")?;
}
if self.contains(VkMemoryPropertyFlagBits::HOST_VISIBLE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HOST_VISIBLE_BIT")?;
}
if self.contains(VkMemoryPropertyFlagBits::HOST_COHERENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HOST_COHERENT_BIT")?;
}
if self.contains(VkMemoryPropertyFlagBits::HOST_CACHED_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("HOST_CACHED_BIT")?;
}
if self.contains(VkMemoryPropertyFlagBits::LAZILY_ALLOCATED_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("LAZILY_ALLOCATED_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkQueueFlagBits(VkFlags);
impl VkQueueFlagBits
{
pub const GRAPHICS_BIT: VkQueueFlagBits = VkQueueFlagBits(1);
pub const COMPUTE_BIT: VkQueueFlagBits = VkQueueFlagBits(2);
pub const TRANSFER_BIT: VkQueueFlagBits = VkQueueFlagBits(4);
pub const SPARSE_BINDING_BIT: VkQueueFlagBits = VkQueueFlagBits(8);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkQueueFlagBits
{
type Output = VkQueueFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkQueueFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkQueueFlagBits
{
type Output = VkQueueFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkQueueFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkQueueFlagBits
{
type Output = VkQueueFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkQueueFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkQueueFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkQueueFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkQueueFlagBits::GRAPHICS_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("GRAPHICS_BIT")?;
}
if self.contains(VkQueueFlagBits::COMPUTE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COMPUTE_BIT")?;
}
if self.contains(VkQueueFlagBits::TRANSFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("TRANSFER_BIT")?;
}
if self.contains(VkQueueFlagBits::SPARSE_BINDING_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SPARSE_BINDING_BIT")?;
}
return f.write_str(")");
}
}
#[repr(transparent)]
#[derive(Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct VkFormatFeatureFlagBits(VkFlags);
impl VkFormatFeatureFlagBits
{
pub const SAMPLED_IMAGE_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(1);
pub const STORAGE_IMAGE_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(2);
pub const STORAGE_IMAGE_ATOMIC_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(4);
pub const UNIFORM_TEXEL_BUFFER_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(8);
pub const STORAGE_TEXEL_BUFFER_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(16);
pub const STORAGE_TEXEL_BUFFER_ATOMIC_BIT: VkFormatFeatureFlagBits =
VkFormatFeatureFlagBits(32);
pub const VERTEX_BUFFER_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(64);
pub const COLOR_ATTACHMENT_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(128);
pub const COLOR_ATTACHMENT_BLEND_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(256);
pub const DEPTH_STENCIL_ATTACHMENT_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(512);
pub const BLIT_SRC_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(1024);
pub const BLIT_DST_BIT: VkFormatFeatureFlagBits = VkFormatFeatureFlagBits(2048);
pub const SAMPLED_IMAGE_FILTER_LINEAR_BIT: VkFormatFeatureFlagBits =
VkFormatFeatureFlagBits(4096);
#[inline]
pub fn contains(&self, other: Self) -> bool
{
return (self.0 & other.0) == other.0;
}
}
impl core::ops::BitOr for VkFormatFeatureFlagBits
{
type Output = VkFormatFeatureFlagBits;
#[inline]
fn bitor(self, rhs: Self) -> Self
{
Self(self.0 | rhs.0)
}
}
impl core::ops::BitOrAssign for VkFormatFeatureFlagBits
{
#[inline]
fn bitor_assign(&mut self, rhs: Self)
{
self.0 |= rhs.0;
}
}
impl core::ops::BitAnd for VkFormatFeatureFlagBits
{
type Output = VkFormatFeatureFlagBits;
#[inline]
fn bitand(self, rhs: Self) -> Self
{
Self(self.0 & rhs.0)
}
}
impl core::ops::BitAndAssign for VkFormatFeatureFlagBits
{
#[inline]
fn bitand_assign(&mut self, rhs: Self)
{
self.0 &= rhs.0;
}
}
impl core::ops::BitXor for VkFormatFeatureFlagBits
{
type Output = VkFormatFeatureFlagBits;
#[inline]
fn bitxor(self, rhs: Self) -> Self
{
Self(self.0 ^ rhs.0)
}
}
impl core::ops::BitXorAssign for VkFormatFeatureFlagBits
{
#[inline]
fn bitxor_assign(&mut self, rhs: Self)
{
self.0 ^= rhs.0;
}
}
impl core::fmt::Debug for VkFormatFeatureFlagBits
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result
{
f.write_str("VkFormatFeatureFlagBits(")?;
#[allow(unused_mut, unused)]
let mut first = true;
if self.contains(VkFormatFeatureFlagBits::SAMPLED_IMAGE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SAMPLED_IMAGE_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::STORAGE_IMAGE_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STORAGE_IMAGE_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::STORAGE_IMAGE_ATOMIC_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STORAGE_IMAGE_ATOMIC_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::UNIFORM_TEXEL_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("UNIFORM_TEXEL_BUFFER_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::STORAGE_TEXEL_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STORAGE_TEXEL_BUFFER_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::STORAGE_TEXEL_BUFFER_ATOMIC_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("STORAGE_TEXEL_BUFFER_ATOMIC_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::VERTEX_BUFFER_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("VERTEX_BUFFER_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::COLOR_ATTACHMENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COLOR_ATTACHMENT_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::COLOR_ATTACHMENT_BLEND_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("COLOR_ATTACHMENT_BLEND_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::DEPTH_STENCIL_ATTACHMENT_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("DEPTH_STENCIL_ATTACHMENT_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::BLIT_SRC_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("BLIT_SRC_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::BLIT_DST_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("BLIT_DST_BIT")?;
}
if self.contains(VkFormatFeatureFlagBits::SAMPLED_IMAGE_FILTER_LINEAR_BIT)
{
if !first
{
f.write_str(" | ")?;
}
first = false;
f.write_str("SAMPLED_IMAGE_FILTER_LINEAR_BIT")?;
}
return f.write_str(")");
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkAllocationCallbacks
{
pub p_user_data: *mut core::ffi::c_void,
pub pfn_allocation: Option<PfnVkAllocationFunction>,
pub pfn_reallocation: Option<PfnVkReallocationFunction>,
pub pfn_free: Option<PfnVkFreeFunction>,
pub pfn_internal_allocation: Option<PfnVkInternalAllocationNotification>,
pub pfn_internal_free: Option<PfnVkInternalFreeNotification>,
}
pub trait ExtendsAllocationCallbacks
{
}
impl Default for VkAllocationCallbacks
{
fn default() -> Self
{
Self {
p_user_data: core::ptr::null_mut(),
pfn_allocation: unsafe { core::mem::zeroed() },
pfn_reallocation: unsafe { core::mem::zeroed() },
pfn_free: unsafe { core::mem::zeroed() },
pfn_internal_allocation: unsafe { core::mem::zeroed() },
pfn_internal_free: unsafe { core::mem::zeroed() },
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkWin32SurfaceCreateInfoKHR
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkWin32SurfaceCreateFlagsKHR,
pub hinstance: HINSTANCE,
pub hwnd: HWND,
}
pub trait ExtendsWin32SurfaceCreateInfoKHR
{
}
impl Default for VkWin32SurfaceCreateInfoKHR
{
fn default() -> Self
{
Self {
s_type: VkStructureType::WIN32_SURFACE_CREATE_INFO_KHR,
p_next: core::ptr::null(),
flags: VkWin32SurfaceCreateFlagsKHR::default(),
hinstance: core::ptr::null_mut(),
hwnd: core::ptr::null_mut(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSurfaceFormatKHR
{
pub format: VkFormat,
pub color_space: VkColorSpaceKHR,
}
pub trait ExtendsSurfaceFormatKHR
{
}
impl Default for VkSurfaceFormatKHR
{
fn default() -> Self
{
Self {
format: VkFormat::default(),
color_space: VkColorSpaceKHR::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSurfaceCapabilitiesKHR
{
pub min_image_count: u32,
pub max_image_count: u32,
pub current_extent: VkExtent2D,
pub min_image_extent: VkExtent2D,
pub max_image_extent: VkExtent2D,
pub max_image_array_layers: u32,
pub supported_transforms: VkSurfaceTransformFlagsKHR,
pub current_transform: VkSurfaceTransformFlagBitsKHR,
pub supported_composite_alpha: VkCompositeAlphaFlagsKHR,
pub supported_usage_flags: VkImageUsageFlags,
}
pub trait ExtendsSurfaceCapabilitiesKHR
{
}
impl Default for VkSurfaceCapabilitiesKHR
{
fn default() -> Self
{
Self {
min_image_count: 0,
max_image_count: 0,
current_extent: VkExtent2D::default(),
min_image_extent: VkExtent2D::default(),
max_image_extent: VkExtent2D::default(),
max_image_array_layers: 0,
supported_transforms: VkSurfaceTransformFlagsKHR::default(),
current_transform: VkSurfaceTransformFlagBitsKHR::default(),
supported_composite_alpha: VkCompositeAlphaFlagsKHR::default(),
supported_usage_flags: VkImageUsageFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkExtent2D
{
pub width: u32,
pub height: u32,
}
pub trait ExtendsExtent2D
{
}
impl Default for VkExtent2D
{
fn default() -> Self
{
Self {
width: 0,
height: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPresentInfoKHR
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub wait_semaphore_count: u32,
pub p_wait_semaphores: *const VkSemaphore,
pub swapchain_count: u32,
pub p_swapchains: *const VkSwapchainKHR,
pub p_image_indices: *const u32,
pub p_results: *mut VkResult,
}
pub trait ExtendsPresentInfoKHR
{
}
impl Default for VkPresentInfoKHR
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PRESENT_INFO_KHR,
p_next: core::ptr::null(),
wait_semaphore_count: 0,
p_wait_semaphores: core::ptr::null(),
swapchain_count: 0,
p_swapchains: core::ptr::null(),
p_image_indices: core::ptr::null(),
p_results: core::ptr::null_mut(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSwapchainCreateInfoKHR
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkSwapchainCreateFlagsKHR,
pub surface: VkSurfaceKHR,
pub min_image_count: u32,
pub image_format: VkFormat,
pub image_color_space: VkColorSpaceKHR,
pub image_extent: VkExtent2D,
pub image_array_layers: u32,
pub image_usage: VkImageUsageFlags,
pub image_sharing_mode: VkSharingMode,
pub queue_family_index_count: u32,
pub p_queue_family_indices: *const u32,
pub pre_transform: VkSurfaceTransformFlagBitsKHR,
pub composite_alpha: VkCompositeAlphaFlagBitsKHR,
pub present_mode: VkPresentModeKHR,
pub clipped: VkBool32,
pub old_swapchain: VkSwapchainKHR,
}
pub trait ExtendsSwapchainCreateInfoKHR
{
}
impl Default for VkSwapchainCreateInfoKHR
{
fn default() -> Self
{
Self {
s_type: VkStructureType::SWAPCHAIN_CREATE_INFO_KHR,
p_next: core::ptr::null(),
flags: VkSwapchainCreateFlagsKHR::default(),
surface: VkSurfaceKHR::default(),
min_image_count: 0,
image_format: VkFormat::default(),
image_color_space: VkColorSpaceKHR::default(),
image_extent: VkExtent2D::default(),
image_array_layers: 0,
image_usage: VkImageUsageFlags::default(),
image_sharing_mode: VkSharingMode::default(),
queue_family_index_count: 0,
p_queue_family_indices: core::ptr::null(),
pre_transform: VkSurfaceTransformFlagBitsKHR::default(),
composite_alpha: VkCompositeAlphaFlagBitsKHR::default(),
present_mode: VkPresentModeKHR::default(),
clipped: VkBool32::default(),
old_swapchain: VkSwapchainKHR::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDebugUtilsMessengerCallbackDataEXT
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkDebugUtilsMessengerCallbackDataFlagsEXT,
pub p_message_id_name: *const u8,
pub message_id_number: i32,
pub p_message: *const u8,
pub queue_label_count: u32,
pub p_queue_labels: *const VkDebugUtilsLabelEXT,
pub cmd_buf_label_count: u32,
pub p_cmd_buf_labels: *const VkDebugUtilsLabelEXT,
pub object_count: u32,
pub p_objects: *const VkDebugUtilsObjectNameInfoEXT,
}
pub trait ExtendsDebugUtilsMessengerCallbackDataEXT
{
}
impl Default for VkDebugUtilsMessengerCallbackDataEXT
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT,
p_next: core::ptr::null(),
flags: VkDebugUtilsMessengerCallbackDataFlagsEXT::default(),
p_message_id_name: core::ptr::null(),
message_id_number: 0,
p_message: core::ptr::null(),
queue_label_count: 0,
p_queue_labels: core::ptr::null(),
cmd_buf_label_count: 0,
p_cmd_buf_labels: core::ptr::null(),
object_count: 0,
p_objects: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDebugUtilsObjectNameInfoEXT
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub object_type: VkObjectType,
pub object_handle: u64,
pub p_object_name: *const u8,
}
pub trait ExtendsDebugUtilsObjectNameInfoEXT
{
}
impl Default for VkDebugUtilsObjectNameInfoEXT
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
p_next: core::ptr::null(),
object_type: VkObjectType::default(),
object_handle: 0,
p_object_name: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDebugUtilsLabelEXT
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub p_label_name: *const u8,
pub color: [f32; 4],
}
pub trait ExtendsDebugUtilsLabelEXT
{
}
impl Default for VkDebugUtilsLabelEXT
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DEBUG_UTILS_LABEL_EXT,
p_next: core::ptr::null(),
p_label_name: core::ptr::null(),
color: [0.0, 0.0, 0.0, 0.0],
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDebugUtilsMessengerCreateInfoEXT
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkDebugUtilsMessengerCreateFlagsEXT,
pub message_severity: VkDebugUtilsMessageSeverityFlagsEXT,
pub message_type: VkDebugUtilsMessageTypeFlagsEXT,
pub pfn_user_callback: Option<PfnVkDebugUtilsMessengerCallbackEXT>,
pub p_user_data: *mut core::ffi::c_void,
}
pub trait ExtendsDebugUtilsMessengerCreateInfoEXT
{
}
impl ExtendsInstanceCreateInfo for VkDebugUtilsMessengerCreateInfoEXT {}
impl Default for VkDebugUtilsMessengerCreateInfoEXT
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
p_next: core::ptr::null(),
flags: VkDebugUtilsMessengerCreateFlagsEXT::default(),
message_severity: VkDebugUtilsMessageSeverityFlagsEXT::default(),
message_type: VkDebugUtilsMessageTypeFlagsEXT::default(),
pfn_user_callback: unsafe { core::mem::zeroed() },
p_user_data: core::ptr::null_mut(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDebugUtilsObjectTagInfoEXT
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub object_type: VkObjectType,
pub object_handle: u64,
pub tag_name: u64,
pub tag_size: usize,
pub p_tag: *const core::ffi::c_void,
}
pub trait ExtendsDebugUtilsObjectTagInfoEXT
{
}
impl Default for VkDebugUtilsObjectTagInfoEXT
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DEBUG_UTILS_OBJECT_TAG_INFO_EXT,
p_next: core::ptr::null(),
object_type: VkObjectType::default(),
object_handle: 0,
tag_name: 0,
tag_size: 0,
p_tag: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBaseInStructure
{
pub s_type: VkStructureType,
pub p_next: *const VkBaseInStructure,
}
pub trait ExtendsBaseInStructure
{
}
impl Default for VkBaseInStructure
{
fn default() -> Self
{
Self {
s_type: VkStructureType::default(),
p_next: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBaseOutStructure
{
pub s_type: VkStructureType,
pub p_next: *mut VkBaseOutStructure,
}
pub trait ExtendsBaseOutStructure
{
}
impl Default for VkBaseOutStructure
{
fn default() -> Self
{
Self {
s_type: VkStructureType::default(),
p_next: core::ptr::null_mut(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkMemoryBarrier
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub src_access_mask: VkAccessFlags,
pub dst_access_mask: VkAccessFlags,
}
pub trait ExtendsMemoryBarrier
{
}
impl Default for VkMemoryBarrier
{
fn default() -> Self
{
Self {
s_type: VkStructureType::MEMORY_BARRIER,
p_next: core::ptr::null(),
src_access_mask: VkAccessFlags::default(),
dst_access_mask: VkAccessFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageMemoryBarrier
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub src_access_mask: VkAccessFlags,
pub dst_access_mask: VkAccessFlags,
pub old_layout: VkImageLayout,
pub new_layout: VkImageLayout,
pub src_queue_family_index: u32,
pub dst_queue_family_index: u32,
pub image: VkImage,
pub subresource_range: VkImageSubresourceRange,
}
pub trait ExtendsImageMemoryBarrier
{
}
impl Default for VkImageMemoryBarrier
{
fn default() -> Self
{
Self {
s_type: VkStructureType::IMAGE_MEMORY_BARRIER,
p_next: core::ptr::null(),
src_access_mask: VkAccessFlags::default(),
dst_access_mask: VkAccessFlags::default(),
old_layout: VkImageLayout::default(),
new_layout: VkImageLayout::default(),
src_queue_family_index: 0,
dst_queue_family_index: 0,
image: VkImage::default(),
subresource_range: VkImageSubresourceRange::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageSubresourceRange
{
pub aspect_mask: VkImageAspectFlags,
pub base_mip_level: u32,
pub level_count: u32,
pub base_array_layer: u32,
pub layer_count: u32,
}
pub trait ExtendsImageSubresourceRange
{
}
impl Default for VkImageSubresourceRange
{
fn default() -> Self
{
Self {
aspect_mask: VkImageAspectFlags::default(),
base_mip_level: 0,
level_count: 0,
base_array_layer: 0,
layer_count: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDrawIndirectCommand
{
pub vertex_count: u32,
pub instance_count: u32,
pub first_vertex: u32,
pub first_instance: u32,
}
pub trait ExtendsDrawIndirectCommand
{
}
impl Default for VkDrawIndirectCommand
{
fn default() -> Self
{
Self {
vertex_count: 0,
instance_count: 0,
first_vertex: 0,
first_instance: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDrawIndexedIndirectCommand
{
pub index_count: u32,
pub instance_count: u32,
pub first_index: u32,
pub vertex_offset: i32,
pub first_instance: u32,
}
pub trait ExtendsDrawIndexedIndirectCommand
{
}
impl Default for VkDrawIndexedIndirectCommand
{
fn default() -> Self
{
Self {
index_count: 0,
instance_count: 0,
first_index: 0,
vertex_offset: 0,
first_instance: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDispatchIndirectCommand
{
pub x: u32,
pub y: u32,
pub z: u32,
}
pub trait ExtendsDispatchIndirectCommand
{
}
impl Default for VkDispatchIndirectCommand
{
fn default() -> Self
{
Self { x: 0, y: 0, z: 0 }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBufferMemoryBarrier
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub src_access_mask: VkAccessFlags,
pub dst_access_mask: VkAccessFlags,
pub src_queue_family_index: u32,
pub dst_queue_family_index: u32,
pub buffer: VkBuffer,
pub offset: VkDeviceSize,
pub size: VkDeviceSize,
}
pub trait ExtendsBufferMemoryBarrier
{
}
impl Default for VkBufferMemoryBarrier
{
fn default() -> Self
{
Self {
s_type: VkStructureType::BUFFER_MEMORY_BARRIER,
p_next: core::ptr::null(),
src_access_mask: VkAccessFlags::default(),
dst_access_mask: VkAccessFlags::default(),
src_queue_family_index: 0,
dst_queue_family_index: 0,
buffer: VkBuffer::default(),
offset: VkDeviceSize::default(),
size: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkRenderPassBeginInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub render_pass: VkRenderPass,
pub framebuffer: VkFramebuffer,
pub render_area: VkRect2D,
pub clear_value_count: u32,
pub p_clear_values: *const VkClearValue,
}
pub trait ExtendsRenderPassBeginInfo
{
}
impl Default for VkRenderPassBeginInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::RENDER_PASS_BEGIN_INFO,
p_next: core::ptr::null(),
render_pass: VkRenderPass::default(),
framebuffer: VkFramebuffer::default(),
render_area: VkRect2D::default(),
clear_value_count: 0,
p_clear_values: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkClearDepthStencilValue
{
pub depth: f32,
pub stencil: u32,
}
pub trait ExtendsClearDepthStencilValue
{
}
impl Default for VkClearDepthStencilValue
{
fn default() -> Self
{
Self {
depth: 0.0,
stencil: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkRect2D
{
pub offset: VkOffset2D,
pub extent: VkExtent2D,
}
pub trait ExtendsRect2D
{
}
impl Default for VkRect2D
{
fn default() -> Self
{
Self {
offset: VkOffset2D::default(),
extent: VkExtent2D::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkOffset2D
{
pub x: i32,
pub y: i32,
}
pub trait ExtendsOffset2D
{
}
impl Default for VkOffset2D
{
fn default() -> Self
{
Self { x: 0, y: 0 }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageResolve
{
pub src_subresource: VkImageSubresourceLayers,
pub src_offset: VkOffset3D,
pub dst_subresource: VkImageSubresourceLayers,
pub dst_offset: VkOffset3D,
pub extent: VkExtent3D,
}
pub trait ExtendsImageResolve
{
}
impl Default for VkImageResolve
{
fn default() -> Self
{
Self {
src_subresource: VkImageSubresourceLayers::default(),
src_offset: VkOffset3D::default(),
dst_subresource: VkImageSubresourceLayers::default(),
dst_offset: VkOffset3D::default(),
extent: VkExtent3D::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkExtent3D
{
pub width: u32,
pub height: u32,
pub depth: u32,
}
pub trait ExtendsExtent3D
{
}
impl Default for VkExtent3D
{
fn default() -> Self
{
Self {
width: 0,
height: 0,
depth: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkOffset3D
{
pub x: i32,
pub y: i32,
pub z: i32,
}
pub trait ExtendsOffset3D
{
}
impl Default for VkOffset3D
{
fn default() -> Self
{
Self { x: 0, y: 0, z: 0 }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageSubresourceLayers
{
pub aspect_mask: VkImageAspectFlags,
pub mip_level: u32,
pub base_array_layer: u32,
pub layer_count: u32,
}
pub trait ExtendsImageSubresourceLayers
{
}
impl Default for VkImageSubresourceLayers
{
fn default() -> Self
{
Self {
aspect_mask: VkImageAspectFlags::default(),
mip_level: 0,
base_array_layer: 0,
layer_count: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkClearRect
{
pub rect: VkRect2D,
pub base_array_layer: u32,
pub layer_count: u32,
}
pub trait ExtendsClearRect
{
}
impl Default for VkClearRect
{
fn default() -> Self
{
Self {
rect: VkRect2D::default(),
base_array_layer: 0,
layer_count: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkClearAttachment
{
pub aspect_mask: VkImageAspectFlags,
pub color_attachment: u32,
pub clear_value: VkClearValue,
}
pub trait ExtendsClearAttachment
{
}
impl Default for VkClearAttachment
{
fn default() -> Self
{
Self {
aspect_mask: VkImageAspectFlags::default(),
color_attachment: 0,
clear_value: VkClearValue::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBufferImageCopy
{
pub buffer_offset: VkDeviceSize,
pub buffer_row_length: u32,
pub buffer_image_height: u32,
pub image_subresource: VkImageSubresourceLayers,
pub image_offset: VkOffset3D,
pub image_extent: VkExtent3D,
}
pub trait ExtendsBufferImageCopy
{
}
impl Default for VkBufferImageCopy
{
fn default() -> Self
{
Self {
buffer_offset: VkDeviceSize::default(),
buffer_row_length: 0,
buffer_image_height: 0,
image_subresource: VkImageSubresourceLayers::default(),
image_offset: VkOffset3D::default(),
image_extent: VkExtent3D::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageBlit
{
pub src_subresource: VkImageSubresourceLayers,
pub src_offsets: [VkOffset3D; 2],
pub dst_subresource: VkImageSubresourceLayers,
pub dst_offsets: [VkOffset3D; 2],
}
pub trait ExtendsImageBlit
{
}
impl Default for VkImageBlit
{
fn default() -> Self
{
Self {
src_subresource: VkImageSubresourceLayers::default(),
src_offsets: [VkOffset3D::default(), VkOffset3D::default()],
dst_subresource: VkImageSubresourceLayers::default(),
dst_offsets: [VkOffset3D::default(), VkOffset3D::default()],
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageCopy
{
pub src_subresource: VkImageSubresourceLayers,
pub src_offset: VkOffset3D,
pub dst_subresource: VkImageSubresourceLayers,
pub dst_offset: VkOffset3D,
pub extent: VkExtent3D,
}
pub trait ExtendsImageCopy
{
}
impl Default for VkImageCopy
{
fn default() -> Self
{
Self {
src_subresource: VkImageSubresourceLayers::default(),
src_offset: VkOffset3D::default(),
dst_subresource: VkImageSubresourceLayers::default(),
dst_offset: VkOffset3D::default(),
extent: VkExtent3D::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBufferCopy
{
pub src_offset: VkDeviceSize,
pub dst_offset: VkDeviceSize,
pub size: VkDeviceSize,
}
pub trait ExtendsBufferCopy
{
}
impl Default for VkBufferCopy
{
fn default() -> Self
{
Self {
src_offset: VkDeviceSize::default(),
dst_offset: VkDeviceSize::default(),
size: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkViewport
{
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
pub min_depth: f32,
pub max_depth: f32,
}
pub trait ExtendsViewport
{
}
impl Default for VkViewport
{
fn default() -> Self
{
Self {
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
min_depth: 0.0,
max_depth: 0.0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkCommandBufferBeginInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkCommandBufferUsageFlags,
pub p_inheritance_info: *const VkCommandBufferInheritanceInfo,
}
pub trait ExtendsCommandBufferBeginInfo
{
}
impl Default for VkCommandBufferBeginInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::COMMAND_BUFFER_BEGIN_INFO,
p_next: core::ptr::null(),
flags: VkCommandBufferUsageFlags::default(),
p_inheritance_info: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkCommandBufferInheritanceInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub render_pass: VkRenderPass,
pub subpass: u32,
pub framebuffer: VkFramebuffer,
pub occlusion_query_enable: VkBool32,
pub query_flags: VkQueryControlFlags,
pub pipeline_statistics: VkQueryPipelineStatisticFlags,
}
pub trait ExtendsCommandBufferInheritanceInfo
{
}
impl Default for VkCommandBufferInheritanceInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::COMMAND_BUFFER_INHERITANCE_INFO,
p_next: core::ptr::null(),
render_pass: VkRenderPass::default(),
subpass: 0,
framebuffer: VkFramebuffer::default(),
occlusion_query_enable: VkBool32::default(),
query_flags: VkQueryControlFlags::default(),
pipeline_statistics: VkQueryPipelineStatisticFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkCommandBufferAllocateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub command_pool: VkCommandPool,
pub level: VkCommandBufferLevel,
pub command_buffer_count: u32,
}
pub trait ExtendsCommandBufferAllocateInfo
{
}
impl Default for VkCommandBufferAllocateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::COMMAND_BUFFER_ALLOCATE_INFO,
p_next: core::ptr::null(),
command_pool: VkCommandPool::default(),
level: VkCommandBufferLevel::default(),
command_buffer_count: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkCommandPoolCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkCommandPoolCreateFlags,
pub queue_family_index: u32,
}
pub trait ExtendsCommandPoolCreateInfo
{
}
impl Default for VkCommandPoolCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::COMMAND_POOL_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkCommandPoolCreateFlags::default(),
queue_family_index: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkRenderPassCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkRenderPassCreateFlags,
pub attachment_count: u32,
pub p_attachments: *const VkAttachmentDescription,
pub subpass_count: u32,
pub p_subpasses: *const VkSubpassDescription,
pub dependency_count: u32,
pub p_dependencies: *const VkSubpassDependency,
}
pub trait ExtendsRenderPassCreateInfo
{
}
impl Default for VkRenderPassCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::RENDER_PASS_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkRenderPassCreateFlags::default(),
attachment_count: 0,
p_attachments: core::ptr::null(),
subpass_count: 0,
p_subpasses: core::ptr::null(),
dependency_count: 0,
p_dependencies: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSubpassDependency
{
pub src_subpass: u32,
pub dst_subpass: u32,
pub src_stage_mask: VkPipelineStageFlags,
pub dst_stage_mask: VkPipelineStageFlags,
pub src_access_mask: VkAccessFlags,
pub dst_access_mask: VkAccessFlags,
pub dependency_flags: VkDependencyFlags,
}
pub trait ExtendsSubpassDependency
{
}
impl Default for VkSubpassDependency
{
fn default() -> Self
{
Self {
src_subpass: 0,
dst_subpass: 0,
src_stage_mask: VkPipelineStageFlags::default(),
dst_stage_mask: VkPipelineStageFlags::default(),
src_access_mask: VkAccessFlags::default(),
dst_access_mask: VkAccessFlags::default(),
dependency_flags: VkDependencyFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSubpassDescription
{
pub flags: VkSubpassDescriptionFlags,
pub pipeline_bind_point: VkPipelineBindPoint,
pub input_attachment_count: u32,
pub p_input_attachments: *const VkAttachmentReference,
pub color_attachment_count: u32,
pub p_color_attachments: *const VkAttachmentReference,
pub p_resolve_attachments: *const VkAttachmentReference,
pub p_depth_stencil_attachment: *const VkAttachmentReference,
pub preserve_attachment_count: u32,
pub p_preserve_attachments: *const u32,
}
pub trait ExtendsSubpassDescription
{
}
impl Default for VkSubpassDescription
{
fn default() -> Self
{
Self {
flags: VkSubpassDescriptionFlags::default(),
pipeline_bind_point: VkPipelineBindPoint::default(),
input_attachment_count: 0,
p_input_attachments: core::ptr::null(),
color_attachment_count: 0,
p_color_attachments: core::ptr::null(),
p_resolve_attachments: core::ptr::null(),
p_depth_stencil_attachment: core::ptr::null(),
preserve_attachment_count: 0,
p_preserve_attachments: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkAttachmentReference
{
pub attachment: u32,
pub layout: VkImageLayout,
}
pub trait ExtendsAttachmentReference
{
}
impl Default for VkAttachmentReference
{
fn default() -> Self
{
Self {
attachment: 0,
layout: VkImageLayout::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkAttachmentDescription
{
pub flags: VkAttachmentDescriptionFlags,
pub format: VkFormat,
pub samples: VkSampleCountFlagBits,
pub load_op: VkAttachmentLoadOp,
pub store_op: VkAttachmentStoreOp,
pub stencil_load_op: VkAttachmentLoadOp,
pub stencil_store_op: VkAttachmentStoreOp,
pub initial_layout: VkImageLayout,
pub final_layout: VkImageLayout,
}
pub trait ExtendsAttachmentDescription
{
}
impl Default for VkAttachmentDescription
{
fn default() -> Self
{
Self {
flags: VkAttachmentDescriptionFlags::default(),
format: VkFormat::default(),
samples: VkSampleCountFlagBits::default(),
load_op: VkAttachmentLoadOp::default(),
store_op: VkAttachmentStoreOp::default(),
stencil_load_op: VkAttachmentLoadOp::default(),
stencil_store_op: VkAttachmentStoreOp::default(),
initial_layout: VkImageLayout::default(),
final_layout: VkImageLayout::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkFramebufferCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkFramebufferCreateFlags,
pub render_pass: VkRenderPass,
pub attachment_count: u32,
pub p_attachments: *const VkImageView,
pub width: u32,
pub height: u32,
pub layers: u32,
}
pub trait ExtendsFramebufferCreateInfo
{
}
impl Default for VkFramebufferCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::FRAMEBUFFER_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkFramebufferCreateFlags::default(),
render_pass: VkRenderPass::default(),
attachment_count: 0,
p_attachments: core::ptr::null(),
width: 0,
height: 0,
layers: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkCopyDescriptorSet
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub src_set: VkDescriptorSet,
pub src_binding: u32,
pub src_array_element: u32,
pub dst_set: VkDescriptorSet,
pub dst_binding: u32,
pub dst_array_element: u32,
pub descriptor_count: u32,
}
pub trait ExtendsCopyDescriptorSet
{
}
impl Default for VkCopyDescriptorSet
{
fn default() -> Self
{
Self {
s_type: VkStructureType::COPY_DESCRIPTOR_SET,
p_next: core::ptr::null(),
src_set: VkDescriptorSet::default(),
src_binding: 0,
src_array_element: 0,
dst_set: VkDescriptorSet::default(),
dst_binding: 0,
dst_array_element: 0,
descriptor_count: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkWriteDescriptorSet
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub dst_set: VkDescriptorSet,
pub dst_binding: u32,
pub dst_array_element: u32,
pub descriptor_count: u32,
pub descriptor_type: VkDescriptorType,
pub p_image_info: *const VkDescriptorImageInfo,
pub p_buffer_info: *const VkDescriptorBufferInfo,
pub p_texel_buffer_view: *const VkBufferView,
}
pub trait ExtendsWriteDescriptorSet
{
}
impl Default for VkWriteDescriptorSet
{
fn default() -> Self
{
Self {
s_type: VkStructureType::WRITE_DESCRIPTOR_SET,
p_next: core::ptr::null(),
dst_set: VkDescriptorSet::default(),
dst_binding: 0,
dst_array_element: 0,
descriptor_count: 0,
descriptor_type: VkDescriptorType::default(),
p_image_info: core::ptr::null(),
p_buffer_info: core::ptr::null(),
p_texel_buffer_view: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDescriptorBufferInfo
{
pub buffer: VkBuffer,
pub offset: VkDeviceSize,
pub range: VkDeviceSize,
}
pub trait ExtendsDescriptorBufferInfo
{
}
impl Default for VkDescriptorBufferInfo
{
fn default() -> Self
{
Self {
buffer: VkBuffer::default(),
offset: VkDeviceSize::default(),
range: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDescriptorImageInfo
{
pub sampler: VkSampler,
pub image_view: VkImageView,
pub image_layout: VkImageLayout,
}
pub trait ExtendsDescriptorImageInfo
{
}
impl Default for VkDescriptorImageInfo
{
fn default() -> Self
{
Self {
sampler: VkSampler::default(),
image_view: VkImageView::default(),
image_layout: VkImageLayout::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDescriptorSetAllocateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub descriptor_pool: VkDescriptorPool,
pub descriptor_set_count: u32,
pub p_set_layouts: *const VkDescriptorSetLayout,
}
pub trait ExtendsDescriptorSetAllocateInfo
{
}
impl Default for VkDescriptorSetAllocateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DESCRIPTOR_SET_ALLOCATE_INFO,
p_next: core::ptr::null(),
descriptor_pool: VkDescriptorPool::default(),
descriptor_set_count: 0,
p_set_layouts: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDescriptorPoolCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkDescriptorPoolCreateFlags,
pub max_sets: u32,
pub pool_size_count: u32,
pub p_pool_sizes: *const VkDescriptorPoolSize,
}
pub trait ExtendsDescriptorPoolCreateInfo
{
}
impl Default for VkDescriptorPoolCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DESCRIPTOR_POOL_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkDescriptorPoolCreateFlags::default(),
max_sets: 0,
pool_size_count: 0,
p_pool_sizes: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDescriptorPoolSize
{
pub kind: VkDescriptorType,
pub descriptor_count: u32,
}
pub trait ExtendsDescriptorPoolSize
{
}
impl Default for VkDescriptorPoolSize
{
fn default() -> Self
{
Self {
kind: VkDescriptorType::default(),
descriptor_count: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDescriptorSetLayoutCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkDescriptorSetLayoutCreateFlags,
pub binding_count: u32,
pub p_bindings: *const VkDescriptorSetLayoutBinding,
}
pub trait ExtendsDescriptorSetLayoutCreateInfo
{
}
impl Default for VkDescriptorSetLayoutCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkDescriptorSetLayoutCreateFlags::default(),
binding_count: 0,
p_bindings: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDescriptorSetLayoutBinding
{
pub binding: u32,
pub descriptor_type: VkDescriptorType,
pub descriptor_count: u32,
pub stage_flags: VkShaderStageFlags,
pub p_immutable_samplers: *const VkSampler,
}
pub trait ExtendsDescriptorSetLayoutBinding
{
}
impl Default for VkDescriptorSetLayoutBinding
{
fn default() -> Self
{
Self {
binding: 0,
descriptor_type: VkDescriptorType::default(),
descriptor_count: 0,
stage_flags: VkShaderStageFlags::default(),
p_immutable_samplers: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSamplerCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkSamplerCreateFlags,
pub mag_filter: VkFilter,
pub min_filter: VkFilter,
pub mipmap_mode: VkSamplerMipmapMode,
pub address_mode_u: VkSamplerAddressMode,
pub address_mode_v: VkSamplerAddressMode,
pub address_mode_w: VkSamplerAddressMode,
pub mip_lod_bias: f32,
pub anisotropy_enable: VkBool32,
pub max_anisotropy: f32,
pub compare_enable: VkBool32,
pub compare_op: VkCompareOp,
pub min_lod: f32,
pub max_lod: f32,
pub border_color: VkBorderColor,
pub unnormalized_coordinates: VkBool32,
}
pub trait ExtendsSamplerCreateInfo
{
}
impl Default for VkSamplerCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::SAMPLER_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkSamplerCreateFlags::default(),
mag_filter: VkFilter::default(),
min_filter: VkFilter::default(),
mipmap_mode: VkSamplerMipmapMode::default(),
address_mode_u: VkSamplerAddressMode::default(),
address_mode_v: VkSamplerAddressMode::default(),
address_mode_w: VkSamplerAddressMode::default(),
mip_lod_bias: 0.0,
anisotropy_enable: VkBool32::default(),
max_anisotropy: 0.0,
compare_enable: VkBool32::default(),
compare_op: VkCompareOp::default(),
min_lod: 0.0,
max_lod: 0.0,
border_color: VkBorderColor::default(),
unnormalized_coordinates: VkBool32::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineLayoutCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineLayoutCreateFlags,
pub set_layout_count: u32,
pub p_set_layouts: *const VkDescriptorSetLayout,
pub push_constant_range_count: u32,
pub p_push_constant_ranges: *const VkPushConstantRange,
}
pub trait ExtendsPipelineLayoutCreateInfo
{
}
impl Default for VkPipelineLayoutCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_LAYOUT_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineLayoutCreateFlags::default(),
set_layout_count: 0,
p_set_layouts: core::ptr::null(),
push_constant_range_count: 0,
p_push_constant_ranges: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPushConstantRange
{
pub stage_flags: VkShaderStageFlags,
pub offset: u32,
pub size: u32,
}
pub trait ExtendsPushConstantRange
{
}
impl Default for VkPushConstantRange
{
fn default() -> Self
{
Self {
stage_flags: VkShaderStageFlags::default(),
offset: 0,
size: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkComputePipelineCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineCreateFlags,
pub stage: VkPipelineShaderStageCreateInfo,
pub layout: VkPipelineLayout,
pub base_pipeline_handle: VkPipeline,
pub base_pipeline_index: i32,
}
pub trait ExtendsComputePipelineCreateInfo
{
}
impl Default for VkComputePipelineCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::COMPUTE_PIPELINE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineCreateFlags::default(),
stage: VkPipelineShaderStageCreateInfo::default(),
layout: VkPipelineLayout::default(),
base_pipeline_handle: VkPipeline::default(),
base_pipeline_index: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineShaderStageCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineShaderStageCreateFlags,
pub stage: VkShaderStageFlagBits,
pub module: VkShaderModule,
pub p_name: *const u8,
pub p_specialization_info: *const VkSpecializationInfo,
}
pub trait ExtendsPipelineShaderStageCreateInfo
{
}
impl Default for VkPipelineShaderStageCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineShaderStageCreateFlags::default(),
stage: VkShaderStageFlagBits::default(),
module: VkShaderModule::default(),
p_name: core::ptr::null(),
p_specialization_info: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSpecializationInfo
{
pub map_entry_count: u32,
pub p_map_entries: *const VkSpecializationMapEntry,
pub data_size: usize,
pub p_data: *const core::ffi::c_void,
}
pub trait ExtendsSpecializationInfo
{
}
impl Default for VkSpecializationInfo
{
fn default() -> Self
{
Self {
map_entry_count: 0,
p_map_entries: core::ptr::null(),
data_size: 0,
p_data: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSpecializationMapEntry
{
pub ant_id: u32,
pub offset: u32,
pub size: usize,
}
pub trait ExtendsSpecializationMapEntry
{
}
impl Default for VkSpecializationMapEntry
{
fn default() -> Self
{
Self {
ant_id: 0,
offset: 0,
size: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkGraphicsPipelineCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineCreateFlags,
pub stage_count: u32,
pub p_stages: *const VkPipelineShaderStageCreateInfo,
pub p_vertex_input_state: *const VkPipelineVertexInputStateCreateInfo,
pub p_input_assembly_state: *const VkPipelineInputAssemblyStateCreateInfo,
pub p_tessellation_state: *const VkPipelineTessellationStateCreateInfo,
pub p_viewport_state: *const VkPipelineViewportStateCreateInfo,
pub p_rasterization_state: *const VkPipelineRasterizationStateCreateInfo,
pub p_multisample_state: *const VkPipelineMultisampleStateCreateInfo,
pub p_depth_stencil_state: *const VkPipelineDepthStencilStateCreateInfo,
pub p_color_blend_state: *const VkPipelineColorBlendStateCreateInfo,
pub p_dynamic_state: *const VkPipelineDynamicStateCreateInfo,
pub layout: VkPipelineLayout,
pub render_pass: VkRenderPass,
pub subpass: u32,
pub base_pipeline_handle: VkPipeline,
pub base_pipeline_index: i32,
}
pub trait ExtendsGraphicsPipelineCreateInfo
{
}
impl Default for VkGraphicsPipelineCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::GRAPHICS_PIPELINE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineCreateFlags::default(),
stage_count: 0,
p_stages: core::ptr::null(),
p_vertex_input_state: core::ptr::null(),
p_input_assembly_state: core::ptr::null(),
p_tessellation_state: core::ptr::null(),
p_viewport_state: core::ptr::null(),
p_rasterization_state: core::ptr::null(),
p_multisample_state: core::ptr::null(),
p_depth_stencil_state: core::ptr::null(),
p_color_blend_state: core::ptr::null(),
p_dynamic_state: core::ptr::null(),
layout: VkPipelineLayout::default(),
render_pass: VkRenderPass::default(),
subpass: 0,
base_pipeline_handle: VkPipeline::default(),
base_pipeline_index: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineDynamicStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineDynamicStateCreateFlags,
pub dynamic_state_count: u32,
pub p_dynamic_states: *const VkDynamicState,
}
pub trait ExtendsPipelineDynamicStateCreateInfo
{
}
impl Default for VkPipelineDynamicStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_DYNAMIC_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineDynamicStateCreateFlags::default(),
dynamic_state_count: 0,
p_dynamic_states: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineColorBlendStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineColorBlendStateCreateFlags,
pub logic_op_enable: VkBool32,
pub logic_op: VkLogicOp,
pub attachment_count: u32,
pub p_attachments: *const VkPipelineColorBlendAttachmentState,
pub blend_constants: [f32; 4],
}
pub trait ExtendsPipelineColorBlendStateCreateInfo
{
}
impl Default for VkPipelineColorBlendStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineColorBlendStateCreateFlags::default(),
logic_op_enable: VkBool32::default(),
logic_op: VkLogicOp::default(),
attachment_count: 0,
p_attachments: core::ptr::null(),
blend_constants: [0.0, 0.0, 0.0, 0.0],
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineColorBlendAttachmentState
{
pub blend_enable: VkBool32,
pub src_color_blend_factor: VkBlendFactor,
pub dst_color_blend_factor: VkBlendFactor,
pub color_blend_op: VkBlendOp,
pub src_alpha_blend_factor: VkBlendFactor,
pub dst_alpha_blend_factor: VkBlendFactor,
pub alpha_blend_op: VkBlendOp,
pub color_write_mask: VkColorComponentFlags,
}
pub trait ExtendsPipelineColorBlendAttachmentState
{
}
impl Default for VkPipelineColorBlendAttachmentState
{
fn default() -> Self
{
Self {
blend_enable: VkBool32::default(),
src_color_blend_factor: VkBlendFactor::default(),
dst_color_blend_factor: VkBlendFactor::default(),
color_blend_op: VkBlendOp::default(),
src_alpha_blend_factor: VkBlendFactor::default(),
dst_alpha_blend_factor: VkBlendFactor::default(),
alpha_blend_op: VkBlendOp::default(),
color_write_mask: VkColorComponentFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineDepthStencilStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineDepthStencilStateCreateFlags,
pub depth_test_enable: VkBool32,
pub depth_write_enable: VkBool32,
pub depth_compare_op: VkCompareOp,
pub depth_bounds_test_enable: VkBool32,
pub stencil_test_enable: VkBool32,
pub front: VkStencilOpState,
pub back: VkStencilOpState,
pub min_depth_bounds: f32,
pub max_depth_bounds: f32,
}
pub trait ExtendsPipelineDepthStencilStateCreateInfo
{
}
impl Default for VkPipelineDepthStencilStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineDepthStencilStateCreateFlags::default(),
depth_test_enable: VkBool32::default(),
depth_write_enable: VkBool32::default(),
depth_compare_op: VkCompareOp::default(),
depth_bounds_test_enable: VkBool32::default(),
stencil_test_enable: VkBool32::default(),
front: VkStencilOpState::default(),
back: VkStencilOpState::default(),
min_depth_bounds: 0.0,
max_depth_bounds: 0.0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkStencilOpState
{
pub fail_op: VkStencilOp,
pub pass_op: VkStencilOp,
pub depth_fail_op: VkStencilOp,
pub compare_op: VkCompareOp,
pub compare_mask: u32,
pub write_mask: u32,
pub reference: u32,
}
pub trait ExtendsStencilOpState
{
}
impl Default for VkStencilOpState
{
fn default() -> Self
{
Self {
fail_op: VkStencilOp::default(),
pass_op: VkStencilOp::default(),
depth_fail_op: VkStencilOp::default(),
compare_op: VkCompareOp::default(),
compare_mask: 0,
write_mask: 0,
reference: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineMultisampleStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineMultisampleStateCreateFlags,
pub rasterization_samples: VkSampleCountFlagBits,
pub sample_shading_enable: VkBool32,
pub min_sample_shading: f32,
pub p_sample_mask: *const VkSampleMask,
pub alpha_to_coverage_enable: VkBool32,
pub alpha_to_one_enable: VkBool32,
}
pub trait ExtendsPipelineMultisampleStateCreateInfo
{
}
impl Default for VkPipelineMultisampleStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineMultisampleStateCreateFlags::default(),
rasterization_samples: VkSampleCountFlagBits::default(),
sample_shading_enable: VkBool32::default(),
min_sample_shading: 0.0,
p_sample_mask: core::ptr::null(),
alpha_to_coverage_enable: VkBool32::default(),
alpha_to_one_enable: VkBool32::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineRasterizationStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineRasterizationStateCreateFlags,
pub depth_clamp_enable: VkBool32,
pub rasterizer_discard_enable: VkBool32,
pub polygon_mode: VkPolygonMode,
pub cull_mode: VkCullModeFlags,
pub front_face: VkFrontFace,
pub depth_bias_enable: VkBool32,
pub depth_bias_constant_factor: f32,
pub depth_bias_clamp: f32,
pub depth_bias_slope_factor: f32,
pub line_width: f32,
}
pub trait ExtendsPipelineRasterizationStateCreateInfo
{
}
impl Default for VkPipelineRasterizationStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineRasterizationStateCreateFlags::default(),
depth_clamp_enable: VkBool32::default(),
rasterizer_discard_enable: VkBool32::default(),
polygon_mode: VkPolygonMode::default(),
cull_mode: VkCullModeFlags::default(),
front_face: VkFrontFace::default(),
depth_bias_enable: VkBool32::default(),
depth_bias_constant_factor: 0.0,
depth_bias_clamp: 0.0,
depth_bias_slope_factor: 0.0,
line_width: 0.0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineViewportStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineViewportStateCreateFlags,
pub viewport_count: u32,
pub p_viewports: *const VkViewport,
pub scissor_count: u32,
pub p_scissors: *const VkRect2D,
}
pub trait ExtendsPipelineViewportStateCreateInfo
{
}
impl Default for VkPipelineViewportStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_VIEWPORT_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineViewportStateCreateFlags::default(),
viewport_count: 0,
p_viewports: core::ptr::null(),
scissor_count: 0,
p_scissors: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineTessellationStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineTessellationStateCreateFlags,
pub patch_control_points: u32,
}
pub trait ExtendsPipelineTessellationStateCreateInfo
{
}
impl Default for VkPipelineTessellationStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_TESSELLATION_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineTessellationStateCreateFlags::default(),
patch_control_points: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineInputAssemblyStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineInputAssemblyStateCreateFlags,
pub topology: VkPrimitiveTopology,
pub primitive_restart_enable: VkBool32,
}
pub trait ExtendsPipelineInputAssemblyStateCreateInfo
{
}
impl Default for VkPipelineInputAssemblyStateCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineInputAssemblyStateCreateFlags::default(),
topology: VkPrimitiveTopology::default(),
primitive_restart_enable: VkBool32::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineVertexInputStateCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineVertexInputStateCreateFlags,
pub vertex_binding_description_count: u32,
pub p_vertex_binding_descriptions: *const VkVertexInputBindingDescription,
pub vertex_attribute_description_count: u32,
pub p_vertex_attribute_descriptions: *const VkVertexInputAttributeDescription,
}
pub trait ExtendsPipelineVertexInputStateCreateInfo
{
}
impl Default for VkPipelineVertexInputStateCreateInfo
{
fn default() -> Self
{
Self {
s_type:
VkStructureType::PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineVertexInputStateCreateFlags::default(),
vertex_binding_description_count: 0,
p_vertex_binding_descriptions: core::ptr::null(),
vertex_attribute_description_count: 0,
p_vertex_attribute_descriptions: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkVertexInputAttributeDescription
{
pub location: u32,
pub binding: u32,
pub format: VkFormat,
pub offset: u32,
}
pub trait ExtendsVertexInputAttributeDescription
{
}
impl Default for VkVertexInputAttributeDescription
{
fn default() -> Self
{
Self {
location: 0,
binding: 0,
format: VkFormat::default(),
offset: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkVertexInputBindingDescription
{
pub binding: u32,
pub stride: u32,
pub input_rate: VkVertexInputRate,
}
pub trait ExtendsVertexInputBindingDescription
{
}
impl Default for VkVertexInputBindingDescription
{
fn default() -> Self
{
Self {
binding: 0,
stride: 0,
input_rate: VkVertexInputRate::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPipelineCacheCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkPipelineCacheCreateFlags,
pub initial_data_size: usize,
pub p_initial_data: *const core::ffi::c_void,
}
pub trait ExtendsPipelineCacheCreateInfo
{
}
impl Default for VkPipelineCacheCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::PIPELINE_CACHE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkPipelineCacheCreateFlags::default(),
initial_data_size: 0,
p_initial_data: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkShaderModuleCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkShaderModuleCreateFlags,
pub code_size: usize,
pub p_code: *const u32,
}
pub trait ExtendsShaderModuleCreateInfo
{
}
impl Default for VkShaderModuleCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::SHADER_MODULE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkShaderModuleCreateFlags::default(),
code_size: 0,
p_code: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageViewCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkImageViewCreateFlags,
pub image: VkImage,
pub view_type: VkImageViewType,
pub format: VkFormat,
pub components: VkComponentMapping,
pub subresource_range: VkImageSubresourceRange,
}
pub trait ExtendsImageViewCreateInfo
{
}
impl Default for VkImageViewCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::IMAGE_VIEW_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkImageViewCreateFlags::default(),
image: VkImage::default(),
view_type: VkImageViewType::default(),
format: VkFormat::default(),
components: VkComponentMapping::default(),
subresource_range: VkImageSubresourceRange::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkComponentMapping
{
pub r: VkComponentSwizzle,
pub g: VkComponentSwizzle,
pub b: VkComponentSwizzle,
pub a: VkComponentSwizzle,
}
pub trait ExtendsComponentMapping
{
}
impl Default for VkComponentMapping
{
fn default() -> Self
{
Self {
r: VkComponentSwizzle::default(),
g: VkComponentSwizzle::default(),
b: VkComponentSwizzle::default(),
a: VkComponentSwizzle::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSubresourceLayout
{
pub offset: VkDeviceSize,
pub size: VkDeviceSize,
pub row_pitch: VkDeviceSize,
pub array_pitch: VkDeviceSize,
pub depth_pitch: VkDeviceSize,
}
pub trait ExtendsSubresourceLayout
{
}
impl Default for VkSubresourceLayout
{
fn default() -> Self
{
Self {
offset: VkDeviceSize::default(),
size: VkDeviceSize::default(),
row_pitch: VkDeviceSize::default(),
array_pitch: VkDeviceSize::default(),
depth_pitch: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageSubresource
{
pub aspect_mask: VkImageAspectFlags,
pub mip_level: u32,
pub array_layer: u32,
}
pub trait ExtendsImageSubresource
{
}
impl Default for VkImageSubresource
{
fn default() -> Self
{
Self {
aspect_mask: VkImageAspectFlags::default(),
mip_level: 0,
array_layer: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkImageCreateFlags,
pub image_type: VkImageType,
pub format: VkFormat,
pub extent: VkExtent3D,
pub mip_levels: u32,
pub array_layers: u32,
pub samples: VkSampleCountFlagBits,
pub tiling: VkImageTiling,
pub usage: VkImageUsageFlags,
pub sharing_mode: VkSharingMode,
pub queue_family_index_count: u32,
pub p_queue_family_indices: *const u32,
pub initial_layout: VkImageLayout,
}
pub trait ExtendsImageCreateInfo
{
}
impl Default for VkImageCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::IMAGE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkImageCreateFlags::default(),
image_type: VkImageType::default(),
format: VkFormat::default(),
extent: VkExtent3D::default(),
mip_levels: 0,
array_layers: 0,
samples: VkSampleCountFlagBits::default(),
tiling: VkImageTiling::default(),
usage: VkImageUsageFlags::default(),
sharing_mode: VkSharingMode::default(),
queue_family_index_count: 0,
p_queue_family_indices: core::ptr::null(),
initial_layout: VkImageLayout::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBufferViewCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkBufferViewCreateFlags,
pub buffer: VkBuffer,
pub format: VkFormat,
pub offset: VkDeviceSize,
pub range: VkDeviceSize,
}
pub trait ExtendsBufferViewCreateInfo
{
}
impl Default for VkBufferViewCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::BUFFER_VIEW_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkBufferViewCreateFlags::default(),
buffer: VkBuffer::default(),
format: VkFormat::default(),
offset: VkDeviceSize::default(),
range: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBufferCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkBufferCreateFlags,
pub size: VkDeviceSize,
pub usage: VkBufferUsageFlags,
pub sharing_mode: VkSharingMode,
pub queue_family_index_count: u32,
pub p_queue_family_indices: *const u32,
}
pub trait ExtendsBufferCreateInfo
{
}
impl Default for VkBufferCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::BUFFER_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkBufferCreateFlags::default(),
size: VkDeviceSize::default(),
usage: VkBufferUsageFlags::default(),
sharing_mode: VkSharingMode::default(),
queue_family_index_count: 0,
p_queue_family_indices: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkQueryPoolCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkQueryPoolCreateFlags,
pub query_type: VkQueryType,
pub query_count: u32,
pub pipeline_statistics: VkQueryPipelineStatisticFlags,
}
pub trait ExtendsQueryPoolCreateInfo
{
}
impl Default for VkQueryPoolCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::QUERY_POOL_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkQueryPoolCreateFlags::default(),
query_type: VkQueryType::default(),
query_count: 0,
pipeline_statistics: VkQueryPipelineStatisticFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkEventCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkEventCreateFlags,
}
pub trait ExtendsEventCreateInfo
{
}
impl Default for VkEventCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::EVENT_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkEventCreateFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSemaphoreCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkSemaphoreCreateFlags,
}
pub trait ExtendsSemaphoreCreateInfo
{
}
impl Default for VkSemaphoreCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::SEMAPHORE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkSemaphoreCreateFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkFenceCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkFenceCreateFlags,
}
pub trait ExtendsFenceCreateInfo
{
}
impl Default for VkFenceCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::FENCE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkFenceCreateFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkBindSparseInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub wait_semaphore_count: u32,
pub p_wait_semaphores: *const VkSemaphore,
pub buffer_bind_count: u32,
pub p_buffer_binds: *const VkSparseBufferMemoryBindInfo,
pub image_opaque_bind_count: u32,
pub p_image_opaque_binds: *const VkSparseImageOpaqueMemoryBindInfo,
pub image_bind_count: u32,
pub p_image_binds: *const VkSparseImageMemoryBindInfo,
pub signal_semaphore_count: u32,
pub p_signal_semaphores: *const VkSemaphore,
}
pub trait ExtendsBindSparseInfo
{
}
impl Default for VkBindSparseInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::BIND_SPARSE_INFO,
p_next: core::ptr::null(),
wait_semaphore_count: 0,
p_wait_semaphores: core::ptr::null(),
buffer_bind_count: 0,
p_buffer_binds: core::ptr::null(),
image_opaque_bind_count: 0,
p_image_opaque_binds: core::ptr::null(),
image_bind_count: 0,
p_image_binds: core::ptr::null(),
signal_semaphore_count: 0,
p_signal_semaphores: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSparseImageMemoryBindInfo
{
pub image: VkImage,
pub bind_count: u32,
pub p_binds: *const VkSparseImageMemoryBind,
}
pub trait ExtendsSparseImageMemoryBindInfo
{
}
impl Default for VkSparseImageMemoryBindInfo
{
fn default() -> Self
{
Self {
image: VkImage::default(),
bind_count: 0,
p_binds: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSparseImageMemoryBind
{
pub subresource: VkImageSubresource,
pub offset: VkOffset3D,
pub extent: VkExtent3D,
pub memory: VkDeviceMemory,
pub memory_offset: VkDeviceSize,
pub flags: VkSparseMemoryBindFlags,
}
pub trait ExtendsSparseImageMemoryBind
{
}
impl Default for VkSparseImageMemoryBind
{
fn default() -> Self
{
Self {
subresource: VkImageSubresource::default(),
offset: VkOffset3D::default(),
extent: VkExtent3D::default(),
memory: VkDeviceMemory::default(),
memory_offset: VkDeviceSize::default(),
flags: VkSparseMemoryBindFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSparseImageOpaqueMemoryBindInfo
{
pub image: VkImage,
pub bind_count: u32,
pub p_binds: *const VkSparseMemoryBind,
}
pub trait ExtendsSparseImageOpaqueMemoryBindInfo
{
}
impl Default for VkSparseImageOpaqueMemoryBindInfo
{
fn default() -> Self
{
Self {
image: VkImage::default(),
bind_count: 0,
p_binds: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSparseMemoryBind
{
pub resource_offset: VkDeviceSize,
pub size: VkDeviceSize,
pub memory: VkDeviceMemory,
pub memory_offset: VkDeviceSize,
pub flags: VkSparseMemoryBindFlags,
}
pub trait ExtendsSparseMemoryBind
{
}
impl Default for VkSparseMemoryBind
{
fn default() -> Self
{
Self {
resource_offset: VkDeviceSize::default(),
size: VkDeviceSize::default(),
memory: VkDeviceMemory::default(),
memory_offset: VkDeviceSize::default(),
flags: VkSparseMemoryBindFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSparseBufferMemoryBindInfo
{
pub buffer: VkBuffer,
pub bind_count: u32,
pub p_binds: *const VkSparseMemoryBind,
}
pub trait ExtendsSparseBufferMemoryBindInfo
{
}
impl Default for VkSparseBufferMemoryBindInfo
{
fn default() -> Self
{
Self {
buffer: VkBuffer::default(),
bind_count: 0,
p_binds: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSparseImageFormatProperties
{
pub aspect_mask: VkImageAspectFlags,
pub image_granularity: VkExtent3D,
pub flags: VkSparseImageFormatFlags,
}
pub trait ExtendsSparseImageFormatProperties
{
}
impl Default for VkSparseImageFormatProperties
{
fn default() -> Self
{
Self {
aspect_mask: VkImageAspectFlags::default(),
image_granularity: VkExtent3D::default(),
flags: VkSparseImageFormatFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSparseImageMemoryRequirements
{
pub format_properties: VkSparseImageFormatProperties,
pub image_mip_tail_first_lod: u32,
pub image_mip_tail_size: VkDeviceSize,
pub image_mip_tail_offset: VkDeviceSize,
pub image_mip_tail_stride: VkDeviceSize,
}
pub trait ExtendsSparseImageMemoryRequirements
{
}
impl Default for VkSparseImageMemoryRequirements
{
fn default() -> Self
{
Self {
format_properties: VkSparseImageFormatProperties::default(),
image_mip_tail_first_lod: 0,
image_mip_tail_size: VkDeviceSize::default(),
image_mip_tail_offset: VkDeviceSize::default(),
image_mip_tail_stride: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkMemoryRequirements
{
pub size: VkDeviceSize,
pub alignment: VkDeviceSize,
pub memory_type_bits: u32,
}
pub trait ExtendsMemoryRequirements
{
}
impl Default for VkMemoryRequirements
{
fn default() -> Self
{
Self {
size: VkDeviceSize::default(),
alignment: VkDeviceSize::default(),
memory_type_bits: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkMappedMemoryRange
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub memory: VkDeviceMemory,
pub offset: VkDeviceSize,
pub size: VkDeviceSize,
}
pub trait ExtendsMappedMemoryRange
{
}
impl Default for VkMappedMemoryRange
{
fn default() -> Self
{
Self {
s_type: VkStructureType::MAPPED_MEMORY_RANGE,
p_next: core::ptr::null(),
memory: VkDeviceMemory::default(),
offset: VkDeviceSize::default(),
size: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkMemoryAllocateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub allocation_size: VkDeviceSize,
pub memory_type_index: u32,
}
pub trait ExtendsMemoryAllocateInfo
{
}
impl Default for VkMemoryAllocateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::MEMORY_ALLOCATE_INFO,
p_next: core::ptr::null(),
allocation_size: VkDeviceSize::default(),
memory_type_index: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkSubmitInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub wait_semaphore_count: u32,
pub p_wait_semaphores: *const VkSemaphore,
pub p_wait_dst_stage_mask: *const VkPipelineStageFlags,
pub command_buffer_count: u32,
pub p_command_buffers: *const VkCommandBuffer,
pub signal_semaphore_count: u32,
pub p_signal_semaphores: *const VkSemaphore,
}
pub trait ExtendsSubmitInfo
{
}
impl Default for VkSubmitInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::SUBMIT_INFO,
p_next: core::ptr::null(),
wait_semaphore_count: 0,
p_wait_semaphores: core::ptr::null(),
p_wait_dst_stage_mask: core::ptr::null(),
command_buffer_count: 0,
p_command_buffers: core::ptr::null(),
signal_semaphore_count: 0,
p_signal_semaphores: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkLayerProperties
{
pub layer_name: [u8; 256],
pub spec_version: u32,
pub implementation_version: u32,
pub description: [u8; 256],
}
pub trait ExtendsLayerProperties
{
}
impl Default for VkLayerProperties
{
fn default() -> Self
{
Self {
layer_name: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
],
spec_version: 0,
implementation_version: 0,
description: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
],
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkExtensionProperties
{
pub extension_name: [u8; 256],
pub spec_version: u32,
}
pub trait ExtendsExtensionProperties
{
}
impl Default for VkExtensionProperties
{
fn default() -> Self
{
Self {
extension_name: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
],
spec_version: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDeviceCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkDeviceCreateFlags,
pub queue_create_info_count: u32,
pub p_queue_create_infos: *const VkDeviceQueueCreateInfo,
pub enabled_layer_count: u32,
pub pp_enabled_layer_names: *const *const u8,
pub enabled_extension_count: u32,
pub pp_enabled_extension_names: *const *const u8,
pub p_enabled_features: *const VkPhysicalDeviceFeatures,
}
pub trait ExtendsDeviceCreateInfo
{
}
impl Default for VkDeviceCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DEVICE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkDeviceCreateFlags::default(),
queue_create_info_count: 0,
p_queue_create_infos: core::ptr::null(),
enabled_layer_count: 0,
pp_enabled_layer_names: core::ptr::null(),
enabled_extension_count: 0,
pp_enabled_extension_names: core::ptr::null(),
p_enabled_features: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPhysicalDeviceFeatures
{
pub robust_buffer_access: VkBool32,
pub full_draw_index_uint_32: VkBool32,
pub image_cube_array: VkBool32,
pub independent_blend: VkBool32,
pub geometry_shader: VkBool32,
pub tessellation_shader: VkBool32,
pub sample_rate_shading: VkBool32,
pub dual_src_blend: VkBool32,
pub logic_op: VkBool32,
pub multi_draw_indirect: VkBool32,
pub draw_indirect_first_instance: VkBool32,
pub depth_clamp: VkBool32,
pub depth_bias_clamp: VkBool32,
pub fill_mode_non_solid: VkBool32,
pub depth_bounds: VkBool32,
pub wide_lines: VkBool32,
pub large_points: VkBool32,
pub alpha_to_one: VkBool32,
pub multi_viewport: VkBool32,
pub sampler_anisotropy: VkBool32,
pub texture_compression_etc_2: VkBool32,
pub texture_compression_astc_ldr: VkBool32,
pub texture_compression_bc: VkBool32,
pub occlusion_query_precise: VkBool32,
pub pipeline_statistics_query: VkBool32,
pub vertex_pipeline_stores_and_atomics: VkBool32,
pub fragment_stores_and_atomics: VkBool32,
pub shader_tessellation_and_geometry_point_size: VkBool32,
pub shader_image_gather_extended: VkBool32,
pub shader_storage_image_extended_formats: VkBool32,
pub shader_storage_image_multisample: VkBool32,
pub shader_storage_image_read_without_format: VkBool32,
pub shader_storage_image_write_without_format: VkBool32,
pub shader_uniform_buffer_array_dynamic_indexing: VkBool32,
pub shader_sampled_image_array_dynamic_indexing: VkBool32,
pub shader_storage_buffer_array_dynamic_indexing: VkBool32,
pub shader_storage_image_array_dynamic_indexing: VkBool32,
pub shader_clip_distance: VkBool32,
pub shader_cull_distance: VkBool32,
pub shader_float_64: VkBool32,
pub shader_int_64: VkBool32,
pub shader_int_16: VkBool32,
pub shader_resource_residency: VkBool32,
pub shader_resource_min_lod: VkBool32,
pub sparse_binding: VkBool32,
pub sparse_residency_buffer: VkBool32,
pub sparse_residency_image_2_d: VkBool32,
pub sparse_residency_image_3_d: VkBool32,
pub sparse_residency_2_samples: VkBool32,
pub sparse_residency_4_samples: VkBool32,
pub sparse_residency_8_samples: VkBool32,
pub sparse_residency_16_samples: VkBool32,
pub sparse_residency_aliased: VkBool32,
pub variable_multisample_rate: VkBool32,
pub inherited_queries: VkBool32,
}
pub trait ExtendsPhysicalDeviceFeatures
{
}
impl Default for VkPhysicalDeviceFeatures
{
fn default() -> Self
{
Self {
robust_buffer_access: VkBool32::default(),
full_draw_index_uint_32: VkBool32::default(),
image_cube_array: VkBool32::default(),
independent_blend: VkBool32::default(),
geometry_shader: VkBool32::default(),
tessellation_shader: VkBool32::default(),
sample_rate_shading: VkBool32::default(),
dual_src_blend: VkBool32::default(),
logic_op: VkBool32::default(),
multi_draw_indirect: VkBool32::default(),
draw_indirect_first_instance: VkBool32::default(),
depth_clamp: VkBool32::default(),
depth_bias_clamp: VkBool32::default(),
fill_mode_non_solid: VkBool32::default(),
depth_bounds: VkBool32::default(),
wide_lines: VkBool32::default(),
large_points: VkBool32::default(),
alpha_to_one: VkBool32::default(),
multi_viewport: VkBool32::default(),
sampler_anisotropy: VkBool32::default(),
texture_compression_etc_2: VkBool32::default(),
texture_compression_astc_ldr: VkBool32::default(),
texture_compression_bc: VkBool32::default(),
occlusion_query_precise: VkBool32::default(),
pipeline_statistics_query: VkBool32::default(),
vertex_pipeline_stores_and_atomics: VkBool32::default(),
fragment_stores_and_atomics: VkBool32::default(),
shader_tessellation_and_geometry_point_size: VkBool32::default(),
shader_image_gather_extended: VkBool32::default(),
shader_storage_image_extended_formats: VkBool32::default(),
shader_storage_image_multisample: VkBool32::default(),
shader_storage_image_read_without_format: VkBool32::default(),
shader_storage_image_write_without_format: VkBool32::default(),
shader_uniform_buffer_array_dynamic_indexing: VkBool32::default(),
shader_sampled_image_array_dynamic_indexing: VkBool32::default(),
shader_storage_buffer_array_dynamic_indexing: VkBool32::default(),
shader_storage_image_array_dynamic_indexing: VkBool32::default(),
shader_clip_distance: VkBool32::default(),
shader_cull_distance: VkBool32::default(),
shader_float_64: VkBool32::default(),
shader_int_64: VkBool32::default(),
shader_int_16: VkBool32::default(),
shader_resource_residency: VkBool32::default(),
shader_resource_min_lod: VkBool32::default(),
sparse_binding: VkBool32::default(),
sparse_residency_buffer: VkBool32::default(),
sparse_residency_image_2_d: VkBool32::default(),
sparse_residency_image_3_d: VkBool32::default(),
sparse_residency_2_samples: VkBool32::default(),
sparse_residency_4_samples: VkBool32::default(),
sparse_residency_8_samples: VkBool32::default(),
sparse_residency_16_samples: VkBool32::default(),
sparse_residency_aliased: VkBool32::default(),
variable_multisample_rate: VkBool32::default(),
inherited_queries: VkBool32::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkDeviceQueueCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkDeviceQueueCreateFlags,
pub queue_family_index: u32,
pub queue_count: u32,
pub p_queue_priorities: *const f32,
}
pub trait ExtendsDeviceQueueCreateInfo
{
}
impl Default for VkDeviceQueueCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::DEVICE_QUEUE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkDeviceQueueCreateFlags::default(),
queue_family_index: 0,
queue_count: 0,
p_queue_priorities: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPhysicalDeviceMemoryProperties
{
pub memory_type_count: u32,
pub memory_types: [VkMemoryType; 32],
pub memory_heap_count: u32,
pub memory_heaps: [VkMemoryHeap; 16],
}
pub trait ExtendsPhysicalDeviceMemoryProperties
{
}
impl Default for VkPhysicalDeviceMemoryProperties
{
fn default() -> Self
{
Self {
memory_type_count: 0,
memory_types: [
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
VkMemoryType::default(),
],
memory_heap_count: 0,
memory_heaps: [
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
VkMemoryHeap::default(),
],
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkMemoryHeap
{
pub size: VkDeviceSize,
pub flags: VkMemoryHeapFlags,
}
pub trait ExtendsMemoryHeap
{
}
impl Default for VkMemoryHeap
{
fn default() -> Self
{
Self {
size: VkDeviceSize::default(),
flags: VkMemoryHeapFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkMemoryType
{
pub property_flags: VkMemoryPropertyFlags,
pub heap_index: u32,
}
pub trait ExtendsMemoryType
{
}
impl Default for VkMemoryType
{
fn default() -> Self
{
Self {
property_flags: VkMemoryPropertyFlags::default(),
heap_index: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkQueueFamilyProperties
{
pub queue_flags: VkQueueFlags,
pub queue_count: u32,
pub timestamp_valid_bits: u32,
pub min_image_transfer_granularity: VkExtent3D,
}
pub trait ExtendsQueueFamilyProperties
{
}
impl Default for VkQueueFamilyProperties
{
fn default() -> Self
{
Self {
queue_flags: VkQueueFlags::default(),
queue_count: 0,
timestamp_valid_bits: 0,
min_image_transfer_granularity: VkExtent3D::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPhysicalDeviceProperties
{
pub api_version: u32,
pub driver_version: u32,
pub vendor_id: u32,
pub device_id: u32,
pub device_type: VkPhysicalDeviceType,
pub device_name: [u8; 256],
pub pipeline_cache_uuid: [u8; 16],
pub limits: VkPhysicalDeviceLimits,
pub sparse_properties: VkPhysicalDeviceSparseProperties,
}
pub trait ExtendsPhysicalDeviceProperties
{
}
impl Default for VkPhysicalDeviceProperties
{
fn default() -> Self
{
Self {
api_version: 0,
driver_version: 0,
vendor_id: 0,
device_id: 0,
device_type: VkPhysicalDeviceType::default(),
device_name: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
],
pipeline_cache_uuid: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
limits: VkPhysicalDeviceLimits::default(),
sparse_properties: VkPhysicalDeviceSparseProperties::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPhysicalDeviceSparseProperties
{
pub residency_standard_2_d_block_shape: VkBool32,
pub residency_standard_2_d_multisample_block_shape: VkBool32,
pub residency_standard_3_d_block_shape: VkBool32,
pub residency_aligned_mip_size: VkBool32,
pub residency_non_resident_strict: VkBool32,
}
pub trait ExtendsPhysicalDeviceSparseProperties
{
}
impl Default for VkPhysicalDeviceSparseProperties
{
fn default() -> Self
{
Self {
residency_standard_2_d_block_shape: VkBool32::default(),
residency_standard_2_d_multisample_block_shape: VkBool32::default(),
residency_standard_3_d_block_shape: VkBool32::default(),
residency_aligned_mip_size: VkBool32::default(),
residency_non_resident_strict: VkBool32::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkPhysicalDeviceLimits
{
pub max_image_dimension_1_d: u32,
pub max_image_dimension_2_d: u32,
pub max_image_dimension_3_d: u32,
pub max_image_dimension_cube: u32,
pub max_image_array_layers: u32,
pub max_texel_buffer_elements: u32,
pub max_uniform_buffer_range: u32,
pub max_storage_buffer_range: u32,
pub max_push_constants_size: u32,
pub max_memory_allocation_count: u32,
pub max_sampler_allocation_count: u32,
pub buffer_image_granularity: VkDeviceSize,
pub sparse_address_space_size: VkDeviceSize,
pub max_bound_descriptor_sets: u32,
pub max_per_stage_descriptor_samplers: u32,
pub max_per_stage_descriptor_uniform_buffers: u32,
pub max_per_stage_descriptor_storage_buffers: u32,
pub max_per_stage_descriptor_sampled_images: u32,
pub max_per_stage_descriptor_storage_images: u32,
pub max_per_stage_descriptor_input_attachments: u32,
pub max_per_stage_resources: u32,
pub max_descriptor_set_samplers: u32,
pub max_descriptor_set_uniform_buffers: u32,
pub max_descriptor_set_uniform_buffers_dynamic: u32,
pub max_descriptor_set_storage_buffers: u32,
pub max_descriptor_set_storage_buffers_dynamic: u32,
pub max_descriptor_set_sampled_images: u32,
pub max_descriptor_set_storage_images: u32,
pub max_descriptor_set_input_attachments: u32,
pub max_vertex_input_attributes: u32,
pub max_vertex_input_bindings: u32,
pub max_vertex_input_attribute_offset: u32,
pub max_vertex_input_binding_stride: u32,
pub max_vertex_output_components: u32,
pub max_tessellation_generation_level: u32,
pub max_tessellation_patch_size: u32,
pub max_tessellation_control_per_vertex_input_components: u32,
pub max_tessellation_control_per_vertex_output_components: u32,
pub max_tessellation_control_per_patch_output_components: u32,
pub max_tessellation_control_total_output_components: u32,
pub max_tessellation_evaluation_input_components: u32,
pub max_tessellation_evaluation_output_components: u32,
pub max_geometry_shader_invocations: u32,
pub max_geometry_input_components: u32,
pub max_geometry_output_components: u32,
pub max_geometry_output_vertices: u32,
pub max_geometry_total_output_components: u32,
pub max_fragment_input_components: u32,
pub max_fragment_output_attachments: u32,
pub max_fragment_dual_src_attachments: u32,
pub max_fragment_combined_output_resources: u32,
pub max_compute_shared_memory_size: u32,
pub max_compute_work_group_count: [u32; 3],
pub max_compute_work_group_invocations: u32,
pub max_compute_work_group_size: [u32; 3],
pub sub_pixel_precision_bits: u32,
pub sub_texel_precision_bits: u32,
pub mipmap_precision_bits: u32,
pub max_draw_indexed_index_value: u32,
pub max_draw_indirect_count: u32,
pub max_sampler_lod_bias: f32,
pub max_sampler_anisotropy: f32,
pub max_viewports: u32,
pub max_viewport_dimensions: [u32; 2],
pub viewport_bounds_range: [f32; 2],
pub viewport_sub_pixel_bits: u32,
pub min_memory_map_alignment: usize,
pub min_texel_buffer_offset_alignment: VkDeviceSize,
pub min_uniform_buffer_offset_alignment: VkDeviceSize,
pub min_storage_buffer_offset_alignment: VkDeviceSize,
pub min_texel_offset: i32,
pub max_texel_offset: u32,
pub min_texel_gather_offset: i32,
pub max_texel_gather_offset: u32,
pub min_interpolation_offset: f32,
pub max_interpolation_offset: f32,
pub sub_pixel_interpolation_offset_bits: u32,
pub max_framebuffer_width: u32,
pub max_framebuffer_height: u32,
pub max_framebuffer_layers: u32,
pub framebuffer_color_sample_counts: VkSampleCountFlags,
pub framebuffer_depth_sample_counts: VkSampleCountFlags,
pub framebuffer_stencil_sample_counts: VkSampleCountFlags,
pub framebuffer_no_attachments_sample_counts: VkSampleCountFlags,
pub max_color_attachments: u32,
pub sampled_image_color_sample_counts: VkSampleCountFlags,
pub sampled_image_integer_sample_counts: VkSampleCountFlags,
pub sampled_image_depth_sample_counts: VkSampleCountFlags,
pub sampled_image_stencil_sample_counts: VkSampleCountFlags,
pub storage_image_sample_counts: VkSampleCountFlags,
pub max_sample_mask_words: u32,
pub timestamp_compute_and_graphics: VkBool32,
pub timestamp_period: f32,
pub max_clip_distances: u32,
pub max_cull_distances: u32,
pub max_combined_clip_and_cull_distances: u32,
pub discrete_queue_priorities: u32,
pub point_size_range: [f32; 2],
pub line_width_range: [f32; 2],
pub point_size_granularity: f32,
pub line_width_granularity: f32,
pub strict_lines: VkBool32,
pub standard_sample_locations: VkBool32,
pub optimal_buffer_copy_offset_alignment: VkDeviceSize,
pub optimal_buffer_copy_row_pitch_alignment: VkDeviceSize,
pub non_coherent_atom_size: VkDeviceSize,
}
pub trait ExtendsPhysicalDeviceLimits
{
}
impl Default for VkPhysicalDeviceLimits
{
fn default() -> Self
{
Self {
max_image_dimension_1_d: 0,
max_image_dimension_2_d: 0,
max_image_dimension_3_d: 0,
max_image_dimension_cube: 0,
max_image_array_layers: 0,
max_texel_buffer_elements: 0,
max_uniform_buffer_range: 0,
max_storage_buffer_range: 0,
max_push_constants_size: 0,
max_memory_allocation_count: 0,
max_sampler_allocation_count: 0,
buffer_image_granularity: VkDeviceSize::default(),
sparse_address_space_size: VkDeviceSize::default(),
max_bound_descriptor_sets: 0,
max_per_stage_descriptor_samplers: 0,
max_per_stage_descriptor_uniform_buffers: 0,
max_per_stage_descriptor_storage_buffers: 0,
max_per_stage_descriptor_sampled_images: 0,
max_per_stage_descriptor_storage_images: 0,
max_per_stage_descriptor_input_attachments: 0,
max_per_stage_resources: 0,
max_descriptor_set_samplers: 0,
max_descriptor_set_uniform_buffers: 0,
max_descriptor_set_uniform_buffers_dynamic: 0,
max_descriptor_set_storage_buffers: 0,
max_descriptor_set_storage_buffers_dynamic: 0,
max_descriptor_set_sampled_images: 0,
max_descriptor_set_storage_images: 0,
max_descriptor_set_input_attachments: 0,
max_vertex_input_attributes: 0,
max_vertex_input_bindings: 0,
max_vertex_input_attribute_offset: 0,
max_vertex_input_binding_stride: 0,
max_vertex_output_components: 0,
max_tessellation_generation_level: 0,
max_tessellation_patch_size: 0,
max_tessellation_control_per_vertex_input_components: 0,
max_tessellation_control_per_vertex_output_components: 0,
max_tessellation_control_per_patch_output_components: 0,
max_tessellation_control_total_output_components: 0,
max_tessellation_evaluation_input_components: 0,
max_tessellation_evaluation_output_components: 0,
max_geometry_shader_invocations: 0,
max_geometry_input_components: 0,
max_geometry_output_components: 0,
max_geometry_output_vertices: 0,
max_geometry_total_output_components: 0,
max_fragment_input_components: 0,
max_fragment_output_attachments: 0,
max_fragment_dual_src_attachments: 0,
max_fragment_combined_output_resources: 0,
max_compute_shared_memory_size: 0,
max_compute_work_group_count: [0, 0, 0],
max_compute_work_group_invocations: 0,
max_compute_work_group_size: [0, 0, 0],
sub_pixel_precision_bits: 0,
sub_texel_precision_bits: 0,
mipmap_precision_bits: 0,
max_draw_indexed_index_value: 0,
max_draw_indirect_count: 0,
max_sampler_lod_bias: 0.0,
max_sampler_anisotropy: 0.0,
max_viewports: 0,
max_viewport_dimensions: [0, 0],
viewport_bounds_range: [0.0, 0.0],
viewport_sub_pixel_bits: 0,
min_memory_map_alignment: 0,
min_texel_buffer_offset_alignment: VkDeviceSize::default(),
min_uniform_buffer_offset_alignment: VkDeviceSize::default(),
min_storage_buffer_offset_alignment: VkDeviceSize::default(),
min_texel_offset: 0,
max_texel_offset: 0,
min_texel_gather_offset: 0,
max_texel_gather_offset: 0,
min_interpolation_offset: 0.0,
max_interpolation_offset: 0.0,
sub_pixel_interpolation_offset_bits: 0,
max_framebuffer_width: 0,
max_framebuffer_height: 0,
max_framebuffer_layers: 0,
framebuffer_color_sample_counts: VkSampleCountFlags::default(),
framebuffer_depth_sample_counts: VkSampleCountFlags::default(),
framebuffer_stencil_sample_counts: VkSampleCountFlags::default(),
framebuffer_no_attachments_sample_counts: VkSampleCountFlags::default(),
max_color_attachments: 0,
sampled_image_color_sample_counts: VkSampleCountFlags::default(),
sampled_image_integer_sample_counts: VkSampleCountFlags::default(),
sampled_image_depth_sample_counts: VkSampleCountFlags::default(),
sampled_image_stencil_sample_counts: VkSampleCountFlags::default(),
storage_image_sample_counts: VkSampleCountFlags::default(),
max_sample_mask_words: 0,
timestamp_compute_and_graphics: VkBool32::default(),
timestamp_period: 0.0,
max_clip_distances: 0,
max_cull_distances: 0,
max_combined_clip_and_cull_distances: 0,
discrete_queue_priorities: 0,
point_size_range: [0.0, 0.0],
line_width_range: [0.0, 0.0],
point_size_granularity: 0.0,
line_width_granularity: 0.0,
strict_lines: VkBool32::default(),
standard_sample_locations: VkBool32::default(),
optimal_buffer_copy_offset_alignment: VkDeviceSize::default(),
optimal_buffer_copy_row_pitch_alignment: VkDeviceSize::default(),
non_coherent_atom_size: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkImageFormatProperties
{
pub max_extent: VkExtent3D,
pub max_mip_levels: u32,
pub max_array_layers: u32,
pub sample_counts: VkSampleCountFlags,
pub max_resource_size: VkDeviceSize,
}
pub trait ExtendsImageFormatProperties
{
}
impl Default for VkImageFormatProperties
{
fn default() -> Self
{
Self {
max_extent: VkExtent3D::default(),
max_mip_levels: 0,
max_array_layers: 0,
sample_counts: VkSampleCountFlags::default(),
max_resource_size: VkDeviceSize::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkFormatProperties
{
pub linear_tiling_features: VkFormatFeatureFlags,
pub optimal_tiling_features: VkFormatFeatureFlags,
pub buffer_features: VkFormatFeatureFlags,
}
pub trait ExtendsFormatProperties
{
}
impl Default for VkFormatProperties
{
fn default() -> Self
{
Self {
linear_tiling_features: VkFormatFeatureFlags::default(),
optimal_tiling_features: VkFormatFeatureFlags::default(),
buffer_features: VkFormatFeatureFlags::default(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkInstanceCreateInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub flags: VkInstanceCreateFlags,
pub p_application_info: *const VkApplicationInfo,
pub enabled_layer_count: u32,
pub pp_enabled_layer_names: *const *const u8,
pub enabled_extension_count: u32,
pub pp_enabled_extension_names: *const *const u8,
}
pub trait ExtendsInstanceCreateInfo
{
}
impl Default for VkInstanceCreateInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::INSTANCE_CREATE_INFO,
p_next: core::ptr::null(),
flags: VkInstanceCreateFlags::default(),
p_application_info: core::ptr::null(),
enabled_layer_count: 0,
pp_enabled_layer_names: core::ptr::null(),
enabled_extension_count: 0,
pp_enabled_extension_names: core::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct VkApplicationInfo
{
pub s_type: VkStructureType,
pub p_next: *const core::ffi::c_void,
pub p_application_name: *const u8,
pub application_version: u32,
pub p_engine_name: *const u8,
pub engine_version: u32,
pub api_version: u32,
}
pub trait ExtendsApplicationInfo
{
}
impl Default for VkApplicationInfo
{
fn default() -> Self
{
Self {
s_type: VkStructureType::APPLICATION_INFO,
p_next: core::ptr::null(),
p_application_name: core::ptr::null(),
application_version: 0,
p_engine_name: core::ptr::null(),
engine_version: 0,
api_version: 0,
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union VkClearValue
{
pub color: VkClearColorValue,
pub depth_stencil: VkClearDepthStencilValue,
}
impl Default for VkClearValue
{
fn default() -> Self
{
unsafe { core::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union VkClearColorValue
{
pub float_32: [f32; 4],
pub int_32: [i32; 4],
pub uint_32: [u32; 4],
}
impl Default for VkClearColorValue
{
fn default() -> Self
{
unsafe { core::mem::zeroed() }
}
}
pub type PfnVkInternalFreeNotification = extern "system" fn(
p_user_data: *mut core::ffi::c_void,
size: usize,
allocation_type: VkInternalAllocationType,
allocation_scope: VkSystemAllocationScope,
);
pub type PfnVkInternalAllocationNotification = extern "system" fn(
p_user_data: *mut core::ffi::c_void,
size: usize,
allocation_type: VkInternalAllocationType,
allocation_scope: VkSystemAllocationScope,
);
pub type PfnVkFreeFunction =
extern "system" fn(p_user_data: *mut core::ffi::c_void, p_memory: *mut core::ffi::c_void);
pub type PfnVkReallocationFunction = extern "system" fn(
p_user_data: *mut core::ffi::c_void,
p_original: *mut core::ffi::c_void,
size: usize,
alignment: usize,
allocation_scope: VkSystemAllocationScope,
) -> *mut core::ffi::c_void;
pub type PfnVkAllocationFunction = extern "system" fn(
p_user_data: *mut core::ffi::c_void,
size: usize,
alignment: usize,
allocation_scope: VkSystemAllocationScope,
) -> *mut core::ffi::c_void;
pub type PfnVkDebugUtilsMessengerCallbackEXT = extern "system" fn(
message_severity: VkDebugUtilsMessageSeverityFlagBitsEXT,
message_types: VkDebugUtilsMessageTypeFlagsEXT,
p_callback_data: *const VkDebugUtilsMessengerCallbackDataEXT,
p_user_data: *mut core::ffi::c_void,
) -> VkBool32;
pub type PfnVkVoidFunction = extern "system" fn();
pub type PfnVkGetPhysicalDeviceWin32PresentationSupportKHR =
extern "system" fn(physical_device: VkPhysicalDevice, queue_family_index: u32) -> VkBool32;
pub type PfnVkCreateWin32SurfaceKHR = extern "system" fn(
instance: VkInstance,
p_create_info: *const VkWin32SurfaceCreateInfoKHR,
p_allocator: *const VkAllocationCallbacks,
p_surface: *mut VkSurfaceKHR,
) -> VkResult;
pub type PfnVkGetPhysicalDeviceSurfacePresentModesKHR = extern "system" fn(
physical_device: VkPhysicalDevice,
surface: VkSurfaceKHR,
p_present_mode_count: *mut u32,
p_present_modes: *mut VkPresentModeKHR,
) -> VkResult;
pub type PfnVkGetPhysicalDeviceSurfaceFormatsKHR = extern "system" fn(
physical_device: VkPhysicalDevice,
surface: VkSurfaceKHR,
p_surface_format_count: *mut u32,
p_surface_formats: *mut VkSurfaceFormatKHR,
) -> VkResult;
pub type PfnVkGetPhysicalDeviceSurfaceCapabilitiesKHR = extern "system" fn(
physical_device: VkPhysicalDevice,
surface: VkSurfaceKHR,
p_surface_capabilities: *mut VkSurfaceCapabilitiesKHR,
) -> VkResult;
pub type PfnVkGetPhysicalDeviceSurfaceSupportKHR = extern "system" fn(
physical_device: VkPhysicalDevice,
queue_family_index: u32,
surface: VkSurfaceKHR,
p_supported: *mut VkBool32,
) -> VkResult;
pub type PfnVkDestroySurfaceKHR = extern "system" fn(
instance: VkInstance,
surface: VkSurfaceKHR,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkQueuePresentKHR =
extern "system" fn(queue: VkQueue, p_present_info: *const VkPresentInfoKHR) -> VkResult;
pub type PfnVkAcquireNextImageKHR = extern "system" fn(
device: VkDevice,
swapchain: VkSwapchainKHR,
timeout: u64,
semaphore: VkSemaphore,
fence: VkFence,
p_image_index: *mut u32,
) -> VkResult;
pub type PfnVkGetSwapchainImagesKHR = extern "system" fn(
device: VkDevice,
swapchain: VkSwapchainKHR,
p_swapchain_image_count: *mut u32,
p_swapchain_images: *mut VkImage,
) -> VkResult;
pub type PfnVkDestroySwapchainKHR = extern "system" fn(
device: VkDevice,
swapchain: VkSwapchainKHR,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateSwapchainKHR = extern "system" fn(
device: VkDevice,
p_create_info: *const VkSwapchainCreateInfoKHR,
p_allocator: *const VkAllocationCallbacks,
p_swapchain: *mut VkSwapchainKHR,
) -> VkResult;
pub type PfnVkSubmitDebugUtilsMessageEXT = extern "system" fn(
instance: VkInstance,
message_severity: VkDebugUtilsMessageSeverityFlagBitsEXT,
message_types: VkDebugUtilsMessageTypeFlagsEXT,
p_callback_data: *const VkDebugUtilsMessengerCallbackDataEXT,
);
pub type PfnVkDestroyDebugUtilsMessengerEXT = extern "system" fn(
instance: VkInstance,
messenger: VkDebugUtilsMessengerEXT,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateDebugUtilsMessengerEXT = extern "system" fn(
instance: VkInstance,
p_create_info: *const VkDebugUtilsMessengerCreateInfoEXT,
p_allocator: *const VkAllocationCallbacks,
p_messenger: *mut VkDebugUtilsMessengerEXT,
) -> VkResult;
pub type PfnVkCmdInsertDebugUtilsLabelEXT =
extern "system" fn(command_buffer: VkCommandBuffer, p_label_info: *const VkDebugUtilsLabelEXT);
pub type PfnVkCmdEndDebugUtilsLabelEXT = extern "system" fn(command_buffer: VkCommandBuffer);
pub type PfnVkCmdBeginDebugUtilsLabelEXT =
extern "system" fn(command_buffer: VkCommandBuffer, p_label_info: *const VkDebugUtilsLabelEXT);
pub type PfnVkQueueInsertDebugUtilsLabelEXT =
extern "system" fn(queue: VkQueue, p_label_info: *const VkDebugUtilsLabelEXT);
pub type PfnVkQueueEndDebugUtilsLabelEXT = extern "system" fn(queue: VkQueue);
pub type PfnVkQueueBeginDebugUtilsLabelEXT =
extern "system" fn(queue: VkQueue, p_label_info: *const VkDebugUtilsLabelEXT);
pub type PfnVkSetDebugUtilsObjectTagEXT = extern "system" fn(
device: VkDevice,
p_tag_info: *const VkDebugUtilsObjectTagInfoEXT,
) -> VkResult;
pub type PfnVkSetDebugUtilsObjectNameEXT = extern "system" fn(
device: VkDevice,
p_name_info: *const VkDebugUtilsObjectNameInfoEXT,
) -> VkResult;
pub type PfnVkCmdExecuteCommands = extern "system" fn(
command_buffer: VkCommandBuffer,
command_buffer_count: u32,
p_command_buffers: *const VkCommandBuffer,
);
pub type PfnVkCmdEndRenderPass = extern "system" fn(command_buffer: VkCommandBuffer);
pub type PfnVkCmdNextSubpass =
extern "system" fn(command_buffer: VkCommandBuffer, contents: VkSubpassContents);
pub type PfnVkCmdBeginRenderPass = extern "system" fn(
command_buffer: VkCommandBuffer,
p_render_pass_begin: *const VkRenderPassBeginInfo,
contents: VkSubpassContents,
);
pub type PfnVkCmdPushConstants = extern "system" fn(
command_buffer: VkCommandBuffer,
layout: VkPipelineLayout,
stage_flags: VkShaderStageFlags,
offset: u32,
size: u32,
p_values: *const core::ffi::c_void,
);
pub type PfnVkCmdCopyQueryPoolResults = extern "system" fn(
command_buffer: VkCommandBuffer,
query_pool: VkQueryPool,
first_query: u32,
query_count: u32,
dst_buffer: VkBuffer,
dst_offset: VkDeviceSize,
stride: VkDeviceSize,
flags: VkQueryResultFlags,
);
pub type PfnVkCmdWriteTimestamp = extern "system" fn(
command_buffer: VkCommandBuffer,
pipeline_stage: VkPipelineStageFlagBits,
query_pool: VkQueryPool,
query: u32,
);
pub type PfnVkCmdResetQueryPool = extern "system" fn(
command_buffer: VkCommandBuffer,
query_pool: VkQueryPool,
first_query: u32,
query_count: u32,
);
pub type PfnVkCmdEndQuery =
extern "system" fn(command_buffer: VkCommandBuffer, query_pool: VkQueryPool, query: u32);
pub type PfnVkCmdBeginQuery = extern "system" fn(
command_buffer: VkCommandBuffer,
query_pool: VkQueryPool,
query: u32,
flags: VkQueryControlFlags,
);
pub type PfnVkCmdPipelineBarrier = extern "system" fn(
command_buffer: VkCommandBuffer,
src_stage_mask: VkPipelineStageFlags,
dst_stage_mask: VkPipelineStageFlags,
dependency_flags: VkDependencyFlags,
memory_barrier_count: u32,
p_memory_barriers: *const VkMemoryBarrier,
buffer_memory_barrier_count: u32,
p_buffer_memory_barriers: *const VkBufferMemoryBarrier,
image_memory_barrier_count: u32,
p_image_memory_barriers: *const VkImageMemoryBarrier,
);
pub type PfnVkCmdWaitEvents = extern "system" fn(
command_buffer: VkCommandBuffer,
event_count: u32,
p_events: *const VkEvent,
src_stage_mask: VkPipelineStageFlags,
dst_stage_mask: VkPipelineStageFlags,
memory_barrier_count: u32,
p_memory_barriers: *const VkMemoryBarrier,
buffer_memory_barrier_count: u32,
p_buffer_memory_barriers: *const VkBufferMemoryBarrier,
image_memory_barrier_count: u32,
p_image_memory_barriers: *const VkImageMemoryBarrier,
);
pub type PfnVkCmdResetEvent = extern "system" fn(
command_buffer: VkCommandBuffer,
event: VkEvent,
stage_mask: VkPipelineStageFlags,
);
pub type PfnVkCmdSetEvent = extern "system" fn(
command_buffer: VkCommandBuffer,
event: VkEvent,
stage_mask: VkPipelineStageFlags,
);
pub type PfnVkCmdResolveImage = extern "system" fn(
command_buffer: VkCommandBuffer,
src_image: VkImage,
src_image_layout: VkImageLayout,
dst_image: VkImage,
dst_image_layout: VkImageLayout,
region_count: u32,
p_regions: *const VkImageResolve,
);
pub type PfnVkCmdClearAttachments = extern "system" fn(
command_buffer: VkCommandBuffer,
attachment_count: u32,
p_attachments: *const VkClearAttachment,
rect_count: u32,
p_rects: *const VkClearRect,
);
pub type PfnVkCmdClearDepthStencilImage = extern "system" fn(
command_buffer: VkCommandBuffer,
image: VkImage,
image_layout: VkImageLayout,
p_depth_stencil: *const VkClearDepthStencilValue,
range_count: u32,
p_ranges: *const VkImageSubresourceRange,
);
pub type PfnVkCmdClearColorImage = extern "system" fn(
command_buffer: VkCommandBuffer,
image: VkImage,
image_layout: VkImageLayout,
p_color: *const VkClearColorValue,
range_count: u32,
p_ranges: *const VkImageSubresourceRange,
);
pub type PfnVkCmdFillBuffer = extern "system" fn(
command_buffer: VkCommandBuffer,
dst_buffer: VkBuffer,
dst_offset: VkDeviceSize,
size: VkDeviceSize,
data: u32,
);
pub type PfnVkCmdUpdateBuffer = extern "system" fn(
command_buffer: VkCommandBuffer,
dst_buffer: VkBuffer,
dst_offset: VkDeviceSize,
data_size: VkDeviceSize,
p_data: *const core::ffi::c_void,
);
pub type PfnVkCmdCopyImageToBuffer = extern "system" fn(
command_buffer: VkCommandBuffer,
src_image: VkImage,
src_image_layout: VkImageLayout,
dst_buffer: VkBuffer,
region_count: u32,
p_regions: *const VkBufferImageCopy,
);
pub type PfnVkCmdCopyBufferToImage = extern "system" fn(
command_buffer: VkCommandBuffer,
src_buffer: VkBuffer,
dst_image: VkImage,
dst_image_layout: VkImageLayout,
region_count: u32,
p_regions: *const VkBufferImageCopy,
);
pub type PfnVkCmdBlitImage = extern "system" fn(
command_buffer: VkCommandBuffer,
src_image: VkImage,
src_image_layout: VkImageLayout,
dst_image: VkImage,
dst_image_layout: VkImageLayout,
region_count: u32,
p_regions: *const VkImageBlit,
filter: VkFilter,
);
pub type PfnVkCmdCopyImage = extern "system" fn(
command_buffer: VkCommandBuffer,
src_image: VkImage,
src_image_layout: VkImageLayout,
dst_image: VkImage,
dst_image_layout: VkImageLayout,
region_count: u32,
p_regions: *const VkImageCopy,
);
pub type PfnVkCmdCopyBuffer = extern "system" fn(
command_buffer: VkCommandBuffer,
src_buffer: VkBuffer,
dst_buffer: VkBuffer,
region_count: u32,
p_regions: *const VkBufferCopy,
);
pub type PfnVkCmdDispatchIndirect =
extern "system" fn(command_buffer: VkCommandBuffer, buffer: VkBuffer, offset: VkDeviceSize);
pub type PfnVkCmdDispatch = extern "system" fn(
command_buffer: VkCommandBuffer,
group_count_x: u32,
group_count_y: u32,
group_count_z: u32,
);
pub type PfnVkCmdDrawIndexedIndirect = extern "system" fn(
command_buffer: VkCommandBuffer,
buffer: VkBuffer,
offset: VkDeviceSize,
draw_count: u32,
stride: u32,
);
pub type PfnVkCmdDrawIndirect = extern "system" fn(
command_buffer: VkCommandBuffer,
buffer: VkBuffer,
offset: VkDeviceSize,
draw_count: u32,
stride: u32,
);
pub type PfnVkCmdDrawIndexed = extern "system" fn(
command_buffer: VkCommandBuffer,
index_count: u32,
instance_count: u32,
first_index: u32,
vertex_offset: i32,
first_instance: u32,
);
pub type PfnVkCmdDraw = extern "system" fn(
command_buffer: VkCommandBuffer,
vertex_count: u32,
instance_count: u32,
first_vertex: u32,
first_instance: u32,
);
pub type PfnVkCmdBindVertexBuffers = extern "system" fn(
command_buffer: VkCommandBuffer,
first_binding: u32,
binding_count: u32,
p_buffers: *const VkBuffer,
p_offsets: *const VkDeviceSize,
);
pub type PfnVkCmdBindIndexBuffer = extern "system" fn(
command_buffer: VkCommandBuffer,
buffer: VkBuffer,
offset: VkDeviceSize,
index_type: VkIndexType,
);
pub type PfnVkCmdBindDescriptorSets = extern "system" fn(
command_buffer: VkCommandBuffer,
pipeline_bind_point: VkPipelineBindPoint,
layout: VkPipelineLayout,
first_set: u32,
descriptor_set_count: u32,
p_descriptor_sets: *const VkDescriptorSet,
dynamic_offset_count: u32,
p_dynamic_offsets: *const u32,
);
pub type PfnVkCmdSetStencilReference = extern "system" fn(
command_buffer: VkCommandBuffer,
face_mask: VkStencilFaceFlags,
reference: u32,
);
pub type PfnVkCmdSetStencilWriteMask = extern "system" fn(
command_buffer: VkCommandBuffer,
face_mask: VkStencilFaceFlags,
write_mask: u32,
);
pub type PfnVkCmdSetStencilCompareMask = extern "system" fn(
command_buffer: VkCommandBuffer,
face_mask: VkStencilFaceFlags,
compare_mask: u32,
);
pub type PfnVkCmdSetDepthBounds = extern "system" fn(
command_buffer: VkCommandBuffer,
min_depth_bounds: f32,
max_depth_bounds: f32,
);
pub type PfnVkCmdSetBlendConstants =
extern "system" fn(command_buffer: VkCommandBuffer, blend_constants: [f32; 4]);
pub type PfnVkCmdSetDepthBias = extern "system" fn(
command_buffer: VkCommandBuffer,
depth_bias_constant_factor: f32,
depth_bias_clamp: f32,
depth_bias_slope_factor: f32,
);
pub type PfnVkCmdSetLineWidth =
extern "system" fn(command_buffer: VkCommandBuffer, line_width: f32);
pub type PfnVkCmdSetScissor = extern "system" fn(
command_buffer: VkCommandBuffer,
first_scissor: u32,
scissor_count: u32,
p_scissors: *const VkRect2D,
);
pub type PfnVkCmdSetViewport = extern "system" fn(
command_buffer: VkCommandBuffer,
first_viewport: u32,
viewport_count: u32,
p_viewports: *const VkViewport,
);
pub type PfnVkCmdBindPipeline = extern "system" fn(
command_buffer: VkCommandBuffer,
pipeline_bind_point: VkPipelineBindPoint,
pipeline: VkPipeline,
);
pub type PfnVkResetCommandBuffer = extern "system" fn(
command_buffer: VkCommandBuffer,
flags: VkCommandBufferResetFlags,
) -> VkResult;
pub type PfnVkEndCommandBuffer = extern "system" fn(command_buffer: VkCommandBuffer) -> VkResult;
pub type PfnVkBeginCommandBuffer = extern "system" fn(
command_buffer: VkCommandBuffer,
p_begin_info: *const VkCommandBufferBeginInfo,
) -> VkResult;
pub type PfnVkFreeCommandBuffers = extern "system" fn(
device: VkDevice,
command_pool: VkCommandPool,
command_buffer_count: u32,
p_command_buffers: *const VkCommandBuffer,
);
pub type PfnVkAllocateCommandBuffers = extern "system" fn(
device: VkDevice,
p_allocate_info: *const VkCommandBufferAllocateInfo,
p_command_buffers: *mut VkCommandBuffer,
) -> VkResult;
pub type PfnVkResetCommandPool = extern "system" fn(
device: VkDevice,
command_pool: VkCommandPool,
flags: VkCommandPoolResetFlags,
) -> VkResult;
pub type PfnVkDestroyCommandPool = extern "system" fn(
device: VkDevice,
command_pool: VkCommandPool,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateCommandPool = extern "system" fn(
device: VkDevice,
p_create_info: *const VkCommandPoolCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_command_pool: *mut VkCommandPool,
) -> VkResult;
pub type PfnVkGetRenderAreaGranularity =
extern "system" fn(device: VkDevice, render_pass: VkRenderPass, p_granularity: *mut VkExtent2D);
pub type PfnVkDestroyRenderPass = extern "system" fn(
device: VkDevice,
render_pass: VkRenderPass,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateRenderPass = extern "system" fn(
device: VkDevice,
p_create_info: *const VkRenderPassCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_render_pass: *mut VkRenderPass,
) -> VkResult;
pub type PfnVkDestroyFramebuffer = extern "system" fn(
device: VkDevice,
framebuffer: VkFramebuffer,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateFramebuffer = extern "system" fn(
device: VkDevice,
p_create_info: *const VkFramebufferCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_framebuffer: *mut VkFramebuffer,
) -> VkResult;
pub type PfnVkUpdateDescriptorSets = extern "system" fn(
device: VkDevice,
descriptor_write_count: u32,
p_descriptor_writes: *const VkWriteDescriptorSet,
descriptor_copy_count: u32,
p_descriptor_copies: *const VkCopyDescriptorSet,
);
pub type PfnVkFreeDescriptorSets = extern "system" fn(
device: VkDevice,
descriptor_pool: VkDescriptorPool,
descriptor_set_count: u32,
p_descriptor_sets: *const VkDescriptorSet,
) -> VkResult;
pub type PfnVkAllocateDescriptorSets = extern "system" fn(
device: VkDevice,
p_allocate_info: *const VkDescriptorSetAllocateInfo,
p_descriptor_sets: *mut VkDescriptorSet,
) -> VkResult;
pub type PfnVkResetDescriptorPool = extern "system" fn(
device: VkDevice,
descriptor_pool: VkDescriptorPool,
flags: VkDescriptorPoolResetFlags,
) -> VkResult;
pub type PfnVkDestroyDescriptorPool = extern "system" fn(
device: VkDevice,
descriptor_pool: VkDescriptorPool,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateDescriptorPool = extern "system" fn(
device: VkDevice,
p_create_info: *const VkDescriptorPoolCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_descriptor_pool: *mut VkDescriptorPool,
) -> VkResult;
pub type PfnVkDestroyDescriptorSetLayout = extern "system" fn(
device: VkDevice,
descriptor_set_layout: VkDescriptorSetLayout,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateDescriptorSetLayout = extern "system" fn(
device: VkDevice,
p_create_info: *const VkDescriptorSetLayoutCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_set_layout: *mut VkDescriptorSetLayout,
) -> VkResult;
pub type PfnVkDestroySampler = extern "system" fn(
device: VkDevice,
sampler: VkSampler,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateSampler = extern "system" fn(
device: VkDevice,
p_create_info: *const VkSamplerCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_sampler: *mut VkSampler,
) -> VkResult;
pub type PfnVkDestroyPipelineLayout = extern "system" fn(
device: VkDevice,
pipeline_layout: VkPipelineLayout,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreatePipelineLayout = extern "system" fn(
device: VkDevice,
p_create_info: *const VkPipelineLayoutCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_pipeline_layout: *mut VkPipelineLayout,
) -> VkResult;
pub type PfnVkDestroyPipeline = extern "system" fn(
device: VkDevice,
pipeline: VkPipeline,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateComputePipelines = extern "system" fn(
device: VkDevice,
pipeline_cache: VkPipelineCache,
create_info_count: u32,
p_create_infos: *const VkComputePipelineCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_pipelines: *mut VkPipeline,
) -> VkResult;
pub type PfnVkCreateGraphicsPipelines = extern "system" fn(
device: VkDevice,
pipeline_cache: VkPipelineCache,
create_info_count: u32,
p_create_infos: *const VkGraphicsPipelineCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_pipelines: *mut VkPipeline,
) -> VkResult;
pub type PfnVkMergePipelineCaches = extern "system" fn(
device: VkDevice,
dst_cache: VkPipelineCache,
src_cache_count: u32,
p_src_caches: *const VkPipelineCache,
) -> VkResult;
pub type PfnVkGetPipelineCacheData = extern "system" fn(
device: VkDevice,
pipeline_cache: VkPipelineCache,
p_data_size: *mut usize,
p_data: *mut core::ffi::c_void,
) -> VkResult;
pub type PfnVkDestroyPipelineCache = extern "system" fn(
device: VkDevice,
pipeline_cache: VkPipelineCache,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreatePipelineCache = extern "system" fn(
device: VkDevice,
p_create_info: *const VkPipelineCacheCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_pipeline_cache: *mut VkPipelineCache,
) -> VkResult;
pub type PfnVkDestroyShaderModule = extern "system" fn(
device: VkDevice,
shader_module: VkShaderModule,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateShaderModule = extern "system" fn(
device: VkDevice,
p_create_info: *const VkShaderModuleCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_shader_module: *mut VkShaderModule,
) -> VkResult;
pub type PfnVkDestroyImageView = extern "system" fn(
device: VkDevice,
image_view: VkImageView,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateImageView = extern "system" fn(
device: VkDevice,
p_create_info: *const VkImageViewCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_view: *mut VkImageView,
) -> VkResult;
pub type PfnVkGetImageSubresourceLayout = extern "system" fn(
device: VkDevice,
image: VkImage,
p_subresource: *const VkImageSubresource,
p_layout: *mut VkSubresourceLayout,
);
pub type PfnVkDestroyImage =
extern "system" fn(device: VkDevice, image: VkImage, p_allocator: *const VkAllocationCallbacks);
pub type PfnVkCreateImage = extern "system" fn(
device: VkDevice,
p_create_info: *const VkImageCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_image: *mut VkImage,
) -> VkResult;
pub type PfnVkDestroyBufferView = extern "system" fn(
device: VkDevice,
buffer_view: VkBufferView,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateBufferView = extern "system" fn(
device: VkDevice,
p_create_info: *const VkBufferViewCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_view: *mut VkBufferView,
) -> VkResult;
pub type PfnVkDestroyBuffer = extern "system" fn(
device: VkDevice,
buffer: VkBuffer,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateBuffer = extern "system" fn(
device: VkDevice,
p_create_info: *const VkBufferCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_buffer: *mut VkBuffer,
) -> VkResult;
pub type PfnVkGetQueryPoolResults = extern "system" fn(
device: VkDevice,
query_pool: VkQueryPool,
first_query: u32,
query_count: u32,
data_size: usize,
p_data: *mut core::ffi::c_void,
stride: VkDeviceSize,
flags: VkQueryResultFlags,
) -> VkResult;
pub type PfnVkDestroyQueryPool = extern "system" fn(
device: VkDevice,
query_pool: VkQueryPool,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateQueryPool = extern "system" fn(
device: VkDevice,
p_create_info: *const VkQueryPoolCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_query_pool: *mut VkQueryPool,
) -> VkResult;
pub type PfnVkResetEvent = extern "system" fn(device: VkDevice, event: VkEvent) -> VkResult;
pub type PfnVkSetEvent = extern "system" fn(device: VkDevice, event: VkEvent) -> VkResult;
pub type PfnVkGetEventStatus = extern "system" fn(device: VkDevice, event: VkEvent) -> VkResult;
pub type PfnVkDestroyEvent =
extern "system" fn(device: VkDevice, event: VkEvent, p_allocator: *const VkAllocationCallbacks);
pub type PfnVkCreateEvent = extern "system" fn(
device: VkDevice,
p_create_info: *const VkEventCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_event: *mut VkEvent,
) -> VkResult;
pub type PfnVkDestroySemaphore = extern "system" fn(
device: VkDevice,
semaphore: VkSemaphore,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkCreateSemaphore = extern "system" fn(
device: VkDevice,
p_create_info: *const VkSemaphoreCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_semaphore: *mut VkSemaphore,
) -> VkResult;
pub type PfnVkWaitForFences = extern "system" fn(
device: VkDevice,
fence_count: u32,
p_fences: *const VkFence,
wait_all: VkBool32,
timeout: u64,
) -> VkResult;
pub type PfnVkGetFenceStatus = extern "system" fn(device: VkDevice, fence: VkFence) -> VkResult;
pub type PfnVkResetFences =
extern "system" fn(device: VkDevice, fence_count: u32, p_fences: *const VkFence) -> VkResult;
pub type PfnVkDestroyFence =
extern "system" fn(device: VkDevice, fence: VkFence, p_allocator: *const VkAllocationCallbacks);
pub type PfnVkCreateFence = extern "system" fn(
device: VkDevice,
p_create_info: *const VkFenceCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_fence: *mut VkFence,
) -> VkResult;
pub type PfnVkQueueBindSparse = extern "system" fn(
queue: VkQueue,
bind_info_count: u32,
p_bind_info: *const VkBindSparseInfo,
fence: VkFence,
) -> VkResult;
pub type PfnVkGetPhysicalDeviceSparseImageFormatProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
format: VkFormat,
kind: VkImageType,
samples: VkSampleCountFlagBits,
usage: VkImageUsageFlags,
tiling: VkImageTiling,
p_property_count: *mut u32,
p_properties: *mut VkSparseImageFormatProperties,
);
pub type PfnVkGetImageSparseMemoryRequirements = extern "system" fn(
device: VkDevice,
image: VkImage,
p_sparse_memory_requirement_count: *mut u32,
p_sparse_memory_requirements: *mut VkSparseImageMemoryRequirements,
);
pub type PfnVkGetImageMemoryRequirements = extern "system" fn(
device: VkDevice,
image: VkImage,
p_memory_requirements: *mut VkMemoryRequirements,
);
pub type PfnVkGetBufferMemoryRequirements = extern "system" fn(
device: VkDevice,
buffer: VkBuffer,
p_memory_requirements: *mut VkMemoryRequirements,
);
pub type PfnVkBindImageMemory = extern "system" fn(
device: VkDevice,
image: VkImage,
memory: VkDeviceMemory,
memory_offset: VkDeviceSize,
) -> VkResult;
pub type PfnVkBindBufferMemory = extern "system" fn(
device: VkDevice,
buffer: VkBuffer,
memory: VkDeviceMemory,
memory_offset: VkDeviceSize,
) -> VkResult;
pub type PfnVkGetDeviceMemoryCommitment = extern "system" fn(
device: VkDevice,
memory: VkDeviceMemory,
p_committed_memory_in_bytes: *mut VkDeviceSize,
);
pub type PfnVkInvalidateMappedMemoryRanges = extern "system" fn(
device: VkDevice,
memory_range_count: u32,
p_memory_ranges: *const VkMappedMemoryRange,
) -> VkResult;
pub type PfnVkFlushMappedMemoryRanges = extern "system" fn(
device: VkDevice,
memory_range_count: u32,
p_memory_ranges: *const VkMappedMemoryRange,
) -> VkResult;
pub type PfnVkUnmapMemory = extern "system" fn(device: VkDevice, memory: VkDeviceMemory);
pub type PfnVkMapMemory = extern "system" fn(
device: VkDevice,
memory: VkDeviceMemory,
offset: VkDeviceSize,
size: VkDeviceSize,
flags: VkMemoryMapFlags,
pp_data: *mut *mut core::ffi::c_void,
) -> VkResult;
pub type PfnVkFreeMemory = extern "system" fn(
device: VkDevice,
memory: VkDeviceMemory,
p_allocator: *const VkAllocationCallbacks,
);
pub type PfnVkAllocateMemory = extern "system" fn(
device: VkDevice,
p_allocate_info: *const VkMemoryAllocateInfo,
p_allocator: *const VkAllocationCallbacks,
p_memory: *mut VkDeviceMemory,
) -> VkResult;
pub type PfnVkDeviceWaitIdle = extern "system" fn(device: VkDevice) -> VkResult;
pub type PfnVkQueueWaitIdle = extern "system" fn(queue: VkQueue) -> VkResult;
pub type PfnVkQueueSubmit = extern "system" fn(
queue: VkQueue,
submit_count: u32,
p_submits: *const VkSubmitInfo,
fence: VkFence,
) -> VkResult;
pub type PfnVkGetDeviceQueue = extern "system" fn(
device: VkDevice,
queue_family_index: u32,
queue_index: u32,
p_queue: *mut VkQueue,
);
pub type PfnVkEnumerateDeviceLayerProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
p_property_count: *mut u32,
p_properties: *mut VkLayerProperties,
) -> VkResult;
pub type PfnVkEnumerateInstanceLayerProperties = extern "system" fn(
p_property_count: *mut u32,
p_properties: *mut VkLayerProperties,
) -> VkResult;
pub type PfnVkEnumerateDeviceExtensionProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
p_layer_name: *const u8,
p_property_count: *mut u32,
p_properties: *mut VkExtensionProperties,
) -> VkResult;
pub type PfnVkEnumerateInstanceExtensionProperties = extern "system" fn(
p_layer_name: *const u8,
p_property_count: *mut u32,
p_properties: *mut VkExtensionProperties,
) -> VkResult;
pub type PfnVkDestroyDevice =
extern "system" fn(device: VkDevice, p_allocator: *const VkAllocationCallbacks);
pub type PfnVkCreateDevice = extern "system" fn(
physical_device: VkPhysicalDevice,
p_create_info: *const VkDeviceCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_device: *mut VkDevice,
) -> VkResult;
pub type PfnVkGetDeviceProcAddr =
extern "system" fn(device: VkDevice, p_name: *const u8) -> Option<PfnVkVoidFunction>;
pub type PfnVkGetInstanceProcAddr =
extern "system" fn(instance: VkInstance, p_name: *const u8) -> Option<PfnVkVoidFunction>;
pub type PfnVkGetPhysicalDeviceMemoryProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
p_memory_properties: *mut VkPhysicalDeviceMemoryProperties,
);
pub type PfnVkGetPhysicalDeviceQueueFamilyProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
p_queue_family_property_count: *mut u32,
p_queue_family_properties: *mut VkQueueFamilyProperties,
);
pub type PfnVkGetPhysicalDeviceProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
p_properties: *mut VkPhysicalDeviceProperties,
);
pub type PfnVkGetPhysicalDeviceImageFormatProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
format: VkFormat,
kind: VkImageType,
tiling: VkImageTiling,
usage: VkImageUsageFlags,
flags: VkImageCreateFlags,
p_image_format_properties: *mut VkImageFormatProperties,
) -> VkResult;
pub type PfnVkGetPhysicalDeviceFormatProperties = extern "system" fn(
physical_device: VkPhysicalDevice,
format: VkFormat,
p_format_properties: *mut VkFormatProperties,
);
pub type PfnVkGetPhysicalDeviceFeatures = extern "system" fn(
physical_device: VkPhysicalDevice,
p_features: *mut VkPhysicalDeviceFeatures,
);
pub type PfnVkEnumeratePhysicalDevices = extern "system" fn(
instance: VkInstance,
p_physical_device_count: *mut u32,
p_physical_devices: *mut VkPhysicalDevice,
) -> VkResult;
pub type PfnVkDestroyInstance =
extern "system" fn(instance: VkInstance, p_allocator: *const VkAllocationCallbacks);
pub type PfnVkCreateInstance = extern "system" fn(
p_create_info: *const VkInstanceCreateInfo,
p_allocator: *const VkAllocationCallbacks,
p_instance: *mut VkInstance,
) -> VkResult;
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
/// UsageProfilingResponse : Response containing the number of profiled hosts for each hour for a given organization.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UsageProfilingResponse {
/// Get hourly usage for profiled hosts.
#[serde(rename = "usage", skip_serializing_if = "Option::is_none")]
pub usage: Option<Vec<crate::models::UsageProfilingHour>>,
}
impl UsageProfilingResponse {
/// Response containing the number of profiled hosts for each hour for a given organization.
pub fn new() -> UsageProfilingResponse {
UsageProfilingResponse {
usage: None,
}
}
}
|
//! Components for the LIS3DSH sensor.
//!
//! SPI Interface
//!
//! Usage
//! -----
//! ```rust
//! let lis3dsh = components::lis3dsh::Lis3dshSpiComponent::new().finalize(
//! components::lis3dsh_spi_component_helper!(
//! // spi type
//! stm32f407vg::spi::Spi,
//! // chip select
//! stm32f407vg::gpio::PinId::PE03,
//! // spi mux
//! spi_mux
//! )
//! );
//! ```
use my_capsules::lis3dsh::Lis3dshSpi;
use capsules::virtual_spi::VirtualSpiMasterDevice;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use kernel::component::Component;
use kernel::hil::spi;
use kernel::static_init_half;
// オブジェクト用の静的空間を設定
#[macro_export]
macro_rules! lis3dsh_spi_component_helper {
($A:ty, $select: expr, $spi_mux: expr) => {{
use my_capsules::lis3dsh::Lis3dshSpi;
use capsules::virtual_spi::VirtualSpiMasterDevice;
use core::mem::MaybeUninit;
let mut lis3dsh_spi: &'static capsules::virtual_spi::VirtualSpiMasterDevice<'static, $A> =
components::spi::SpiComponent::new($spi_mux, $select)
.finalize(components::spi_component_helper!($A));
static mut lis3dshspi: MaybeUninit<Lis3dshSpi<'static>> = MaybeUninit::uninit();
(&mut lis3dsh_spi, &mut lis3dshspi)
};};
}
pub struct Lis3dshSpiComponent<S: 'static + spi::SpiMaster> {
_select: PhantomData<S>,
}
impl<S: 'static + spi::SpiMaster> Lis3dshSpiComponent<S> {
pub fn new() -> Lis3dshSpiComponent<S> {
Lis3dshSpiComponent {
_select: PhantomData,
}
}
}
impl<S: 'static + spi::SpiMaster> Component for Lis3dshSpiComponent<S> {
type StaticInput = (
&'static VirtualSpiMasterDevice<'static, S>,
&'static mut MaybeUninit<Lis3dshSpi<'static>>,
);
type Output = &'static Lis3dshSpi<'static>;
unsafe fn finalize(self, static_buffer: Self::StaticInput) -> Self::Output {
let lis3dsh = static_init_half!(
static_buffer.1,
Lis3dshSpi<'static>,
Lis3dshSpi::new(
static_buffer.0,
&mut my_capsules::lis3dsh::TXBUFFER,
&mut my_capsules::lis3dsh::RXBUFFER
)
);
static_buffer.0.set_client(lis3dsh);
lis3dsh
}
} |
// #![allow(dead_code)]
// #![allow(unused_must_use)]
// #![allow(unused_imports)]
// #![allow(unused_variables)]
#![allow(warnings)]
#![feature(box_syntax)]
#![cfg_attr(rustfmt, rustfmt_skip)]
pub mod fragment_shaders;
pub mod linux_display_opengl;
pub mod vertex_shaders;
pub mod types;
|
use clap::{App, Arg, ArgMatches};
use conv;
use std::ops::Deref;
pub fn build_app<'a>(name: &str) -> ArgMatches<'a> {
App::new(format!("{} - Конвертер кодировок текста", name).as_ref())
.version("1.0.0")
.author("Sergey Kacheev <uo0@ya.ru>")
.about(
format!("\n\
Конвертер текстов между кодировками {:?}\n\
По умолчанию утилита читает stdin и выводит результат на stdout\n\
Если указан флаг 'safety', то при первой ошибке декодирования\n\
символа источника утилита завершает свою работу.
",
conv::SUPPORTED_CODES.deref()
).as_ref()
)
.arg(Arg::with_name("from")
.short("f")
.long("from")
.required(true)
.takes_value(true)
.help("Кодировка источника"))
.arg(Arg::with_name("to")
.short("t")
.long("to")
.required(true)
.takes_value(true)
.help("Кодировка результата"),
)
.arg(Arg::with_name("output")
.short("o")
.long("output")
.takes_value(true)
.help("Имя фала для записи результата")
)
.arg(Arg::with_name("safely")
.short("s")
.long("safely")
.takes_value(false)
.help("Прекратить конвертацию при первой ошибке")
)
.arg(Arg::with_name("replace")
.short("r")
.long("replace")
.takes_value(true)
.help("Символ для замены ошибок декодирования 8 битных кодировок (по умолчанию '?')")
)
.arg(Arg::with_name("SOURCE")
.help("Файл для конвертации")
).get_matches()
}
|
struct Person {
name: String,
age: i32
}
impl Person {
fn sayhi(&self) -> String {
format!("Meu nome é {} eu tenho {} anos\n", self.name, self.age)
}
}
fn main() {
let person = Person { name: "Vilmar Catafesta".to_string(), age: 53};
print!("{}\n", person.sayhi())
}
|
use anyhow::Error;
use fehler::throws;
use std::io;
use std::io::prelude::*;
mod document;
#[cfg(test)]
mod tests;
pub use crate::document::Document;
#[throws(_)]
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let doc = Document::parse(&input)?;
doc.to_writer(&mut io::stdout())?;
}
|
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0
use forkable_jellyfish_merkle::proof::SparseMerkleProof;
use serde::{Deserialize, Serialize};
use starcoin_config::ChainNetwork;
use starcoin_crypto::{hash::PlainCryptoHash, HashValue};
use starcoin_rpc_api::node::NodeInfo;
use starcoin_state_api::StateWithProof;
use starcoin_types::block::{Block, BlockHeader};
use starcoin_types::peer_info::{PeerId, PeerInfo};
use starcoin_types::{account_address::AccountAddress, transaction::SignedUserTransaction, U256};
use starcoin_wallet_api::WalletAccount;
use std::collections::HashMap;
//TODO add a derive to auto generate View Object
#[derive(Debug, Serialize, Deserialize)]
pub struct AccountWithStateView {
pub account: WalletAccount,
// hex encoded bytes
pub auth_key_prefix: String,
pub sequence_number: Option<u64>,
pub balances: HashMap<String, u64>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AccountView {
pub sequence_number: Option<u64>,
pub balance: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct StateWithProofView {
pub state: String,
pub account_proof: SparseMerkleProof,
pub account_state_proof: SparseMerkleProof,
}
impl From<StateWithProof> for StateWithProofView {
fn from(state_proof: StateWithProof) -> Self {
let account_state = hex::encode(state_proof.state.unwrap());
Self {
state: account_state,
account_proof: state_proof.proof.account_proof,
account_state_proof: state_proof.proof.account_state_proof,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BlockHeaderView {
pub parent_hash: HashValue,
pub number: u64,
pub id: HashValue,
pub author: AccountAddress,
pub accumulator_root: HashValue,
pub state_root: HashValue,
pub gas_used: u64,
}
impl From<Block> for BlockHeaderView {
fn from(block: Block) -> Self {
BlockHeaderView::from(block.header)
}
}
impl From<BlockHeader> for BlockHeaderView {
fn from(header: BlockHeader) -> Self {
Self {
parent_hash: header.parent_hash,
number: header.number,
id: header.id(),
author: header.author,
accumulator_root: header.accumulator_root,
state_root: header.state_root,
gas_used: header.gas_used,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TransactionView {
pub id: HashValue,
pub sender: AccountAddress,
pub sequence_number: u64,
pub gas_unit_price: u64,
pub max_gas_amount: u64,
}
impl From<SignedUserTransaction> for TransactionView {
fn from(txn: SignedUserTransaction) -> Self {
Self {
id: txn.raw_txn().crypto_hash(),
sender: txn.sender(),
sequence_number: txn.sequence_number(),
gas_unit_price: txn.gas_unit_price(),
max_gas_amount: txn.max_gas_amount(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PeerInfoView {
pub peer_id: PeerId,
pub latest_header: BlockHeaderView,
pub total_difficulty: U256,
}
impl From<PeerInfo> for PeerInfoView {
fn from(peer_info: PeerInfo) -> Self {
Self {
peer_id: peer_info.peer_id,
latest_header: peer_info.latest_header.into(),
total_difficulty: peer_info.total_difficulty,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NodeInfoView {
pub peer_info: PeerInfoView,
pub self_address: String,
pub net: ChainNetwork,
}
impl From<NodeInfo> for NodeInfoView {
fn from(node_info: NodeInfo) -> Self {
Self {
peer_info: node_info.peer_info.into(),
self_address: node_info.self_address,
net: node_info.net,
}
}
}
|
use crate::bytes::JsonBytes;
use crate::{BlockNumber, Capacity, EpochNumber, ProposalShortId, Timestamp, Unsigned, Version};
use ckb_core::block::{Block as CoreBlock, BlockBuilder};
use ckb_core::header::{Header as CoreHeader, HeaderBuilder, Seal as CoreSeal};
use ckb_core::script::{Script as CoreScript, ScriptHashType as CoreScriptHashType};
use ckb_core::transaction::{
CellInput as CoreCellInput, CellOutPoint as CoreCellOutPoint, CellOutput as CoreCellOutput,
OutPoint as CoreOutPoint, Transaction as CoreTransaction, TransactionBuilder,
Witness as CoreWitness,
};
use ckb_core::uncle::UncleBlock as CoreUncleBlock;
use numext_fixed_hash::H256;
use numext_fixed_uint::U256;
use serde_derive::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub enum ScriptHashType {
Data,
Type,
}
impl Default for ScriptHashType {
fn default() -> Self {
ScriptHashType::Data
}
}
impl From<ScriptHashType> for CoreScriptHashType {
fn from(json: ScriptHashType) -> Self {
match json {
ScriptHashType::Data => CoreScriptHashType::Data,
ScriptHashType::Type => CoreScriptHashType::Type,
}
}
}
impl From<CoreScriptHashType> for ScriptHashType {
fn from(core: CoreScriptHashType) -> ScriptHashType {
match core {
CoreScriptHashType::Data => ScriptHashType::Data,
CoreScriptHashType::Type => ScriptHashType::Type,
}
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct Script {
pub args: Vec<JsonBytes>,
pub code_hash: H256,
pub hash_type: ScriptHashType,
}
impl From<Script> for CoreScript {
fn from(json: Script) -> Self {
let Script {
args,
code_hash,
hash_type,
} = json;
CoreScript::new(
args.into_iter().map(JsonBytes::into_bytes).collect(),
code_hash,
hash_type.into(),
)
}
}
impl From<CoreScript> for Script {
fn from(core: CoreScript) -> Script {
let (args, code_hash, hash_type) = core.destruct();
Script {
code_hash,
args: args.into_iter().map(JsonBytes::from_bytes).collect(),
hash_type: hash_type.into(),
}
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct CellOutput {
pub capacity: Capacity,
pub data_hash: H256,
pub lock: Script,
#[serde(rename = "type")]
pub type_: Option<Script>,
}
impl From<CoreCellOutput> for CellOutput {
fn from(core: CoreCellOutput) -> CellOutput {
let (capacity, data_hash, lock, type_) = core.destruct();
CellOutput {
capacity: Capacity(capacity),
data_hash,
lock: lock.into(),
type_: type_.map(Into::into),
}
}
}
impl From<CellOutput> for CoreCellOutput {
fn from(json: CellOutput) -> Self {
let CellOutput {
capacity,
data_hash,
lock,
type_,
} = json;
let type_ = match type_ {
Some(type_) => Some(type_.into()),
None => None,
};
CoreCellOutput::new(capacity.0, data_hash, lock.into(), type_)
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct CellOutPoint {
pub tx_hash: H256,
pub index: Unsigned,
}
impl From<CoreCellOutPoint> for CellOutPoint {
fn from(core: CoreCellOutPoint) -> CellOutPoint {
let (tx_hash, index) = core.destruct();
CellOutPoint {
tx_hash,
index: Unsigned(u64::from(index)),
}
}
}
impl From<CellOutPoint> for CoreCellOutPoint {
fn from(json: CellOutPoint) -> Self {
let CellOutPoint { tx_hash, index } = json;
CoreCellOutPoint {
tx_hash,
index: index.0 as u32,
}
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct OutPoint {
pub cell: Option<CellOutPoint>,
pub block_hash: Option<H256>,
}
impl From<CoreOutPoint> for OutPoint {
fn from(core: CoreOutPoint) -> OutPoint {
let (block_hash, cell) = core.destruct();
OutPoint {
cell: cell.map(Into::into),
block_hash: block_hash.map(Into::into),
}
}
}
impl From<OutPoint> for CoreOutPoint {
fn from(json: OutPoint) -> Self {
let OutPoint { cell, block_hash } = json;
CoreOutPoint {
cell: cell.map(Into::into),
block_hash,
}
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct CellInput {
pub previous_output: OutPoint,
pub since: Unsigned,
}
impl From<CoreCellInput> for CellInput {
fn from(core: CoreCellInput) -> CellInput {
let (previous_output, since) = core.destruct();
CellInput {
previous_output: previous_output.into(),
since: Unsigned(since),
}
}
}
impl From<CellInput> for CoreCellInput {
fn from(json: CellInput) -> Self {
let CellInput {
previous_output,
since,
} = json;
CoreCellInput::new(previous_output.into(), since.0)
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct Witness {
data: Vec<JsonBytes>,
}
impl<'a> From<&'a CoreWitness> for Witness {
fn from(core: &CoreWitness) -> Witness {
Witness {
data: core.iter().cloned().map(JsonBytes::from_bytes).collect(),
}
}
}
impl From<Witness> for CoreWitness {
fn from(json: Witness) -> Self {
json.data.into_iter().map(JsonBytes::into_bytes).collect()
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct Transaction {
pub version: Version,
pub deps: Vec<OutPoint>,
pub inputs: Vec<CellInput>,
pub outputs: Vec<CellOutput>,
pub outputs_data: Vec<JsonBytes>,
pub witnesses: Vec<Witness>,
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct TransactionView {
#[serde(flatten)]
pub inner: Transaction,
pub hash: H256,
}
impl<'a> From<&'a CoreTransaction> for Transaction {
fn from(core: &CoreTransaction) -> Self {
Self {
version: Version(core.version()),
deps: core.deps().iter().cloned().map(Into::into).collect(),
inputs: core.inputs().iter().cloned().map(Into::into).collect(),
outputs: core.outputs().iter().cloned().map(Into::into).collect(),
outputs_data: core
.outputs_data()
.iter()
.cloned()
.map(JsonBytes::from_bytes)
.collect(),
witnesses: core.witnesses().iter().map(Into::into).collect(),
}
}
}
impl<'a> From<&'a CoreTransaction> for TransactionView {
fn from(core: &CoreTransaction) -> Self {
Self {
hash: core.hash().to_owned(),
inner: core.into(),
}
}
}
impl From<Transaction> for CoreTransaction {
fn from(json: Transaction) -> Self {
let Transaction {
version,
deps,
inputs,
outputs,
outputs_data,
witnesses,
} = json;
TransactionBuilder::default()
.version(version.0)
.deps(deps)
.inputs(inputs)
.outputs(outputs)
.outputs_data(outputs_data.into_iter().map(JsonBytes::into_bytes))
.witnesses(witnesses)
.build()
}
}
impl From<TransactionView> for CoreTransaction {
fn from(json: TransactionView) -> Self {
json.inner.into()
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct Seal {
pub nonce: Unsigned,
pub proof: JsonBytes,
}
impl From<CoreSeal> for Seal {
fn from(core: CoreSeal) -> Seal {
let (nonce, proof) = core.destruct();
Seal {
nonce: Unsigned(nonce),
proof: JsonBytes::from_bytes(proof),
}
}
}
impl From<Seal> for CoreSeal {
fn from(json: Seal) -> Self {
let Seal { nonce, proof } = json;
CoreSeal::new(nonce.0, proof.into_bytes())
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct Header {
pub version: Version,
pub parent_hash: H256,
pub timestamp: Timestamp,
pub number: BlockNumber,
pub epoch: EpochNumber,
pub transactions_root: H256,
pub witnesses_root: H256,
pub proposals_hash: H256,
pub difficulty: U256,
pub uncles_hash: H256,
pub uncles_count: Unsigned,
pub dao: JsonBytes,
pub seal: Seal,
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct HeaderView {
#[serde(flatten)]
pub inner: Header,
pub hash: H256,
}
impl<'a> From<&'a CoreHeader> for Header {
fn from(core: &CoreHeader) -> Self {
Self {
version: Version(core.version()),
parent_hash: core.parent_hash().to_owned(),
timestamp: Timestamp(core.timestamp()),
number: BlockNumber(core.number()),
epoch: EpochNumber(core.epoch()),
transactions_root: core.transactions_root().to_owned(),
witnesses_root: core.witnesses_root().to_owned(),
proposals_hash: core.proposals_hash().to_owned(),
difficulty: core.difficulty().to_owned(),
uncles_hash: core.uncles_hash().to_owned(),
uncles_count: Unsigned(u64::from(core.uncles_count())),
dao: JsonBytes::from_bytes(core.dao().to_owned()),
seal: core.seal().to_owned().into(),
}
}
}
impl<'a> From<&'a CoreHeader> for HeaderView {
fn from(core: &CoreHeader) -> Self {
Self {
hash: core.hash().to_owned(),
inner: core.into(),
}
}
}
impl From<Header> for CoreHeader {
fn from(json: Header) -> Self {
let Header {
version,
parent_hash,
timestamp,
number,
epoch,
transactions_root,
witnesses_root,
proposals_hash,
difficulty,
uncles_hash,
uncles_count,
seal,
dao,
} = json;
HeaderBuilder::default()
.version(version.0)
.parent_hash(parent_hash)
.timestamp(timestamp.0)
.number(number.0)
.epoch(epoch.0)
.transactions_root(transactions_root)
.witnesses_root(witnesses_root)
.proposals_hash(proposals_hash)
.difficulty(difficulty)
.uncles_hash(uncles_hash)
.uncles_count(uncles_count.0 as u32)
.seal(seal.into())
.dao(dao.into_bytes())
.build()
}
}
impl From<HeaderView> for CoreHeader {
fn from(json: HeaderView) -> Self {
json.inner.into()
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct UncleBlock {
pub header: Header,
pub proposals: Vec<ProposalShortId>,
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct UncleBlockView {
pub header: HeaderView,
pub proposals: Vec<ProposalShortId>,
}
impl<'a> From<&'a CoreUncleBlock> for UncleBlock {
fn from(core: &CoreUncleBlock) -> Self {
Self {
header: core.header().into(),
proposals: core.proposals().iter().cloned().map(Into::into).collect(),
}
}
}
impl<'a> From<&'a CoreUncleBlock> for UncleBlockView {
fn from(core: &CoreUncleBlock) -> Self {
Self {
header: core.header().into(),
proposals: core.proposals().iter().cloned().map(Into::into).collect(),
}
}
}
impl From<UncleBlock> for CoreUncleBlock {
fn from(json: UncleBlock) -> Self {
let UncleBlock { header, proposals } = json;
CoreUncleBlock::new(
header.into(),
proposals.into_iter().map(Into::into).collect::<Vec<_>>(),
)
}
}
impl From<UncleBlockView> for CoreUncleBlock {
fn from(json: UncleBlockView) -> Self {
let UncleBlockView { header, proposals } = json;
CoreUncleBlock::new(
header.into(),
proposals.into_iter().map(Into::into).collect::<Vec<_>>(),
)
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct Block {
pub header: Header,
pub uncles: Vec<UncleBlock>,
pub transactions: Vec<Transaction>,
pub proposals: Vec<ProposalShortId>,
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)]
pub struct BlockView {
pub header: HeaderView,
pub uncles: Vec<UncleBlockView>,
pub transactions: Vec<TransactionView>,
pub proposals: Vec<ProposalShortId>,
}
impl<'a> From<&'a CoreBlock> for Block {
fn from(core: &CoreBlock) -> Self {
Self {
header: core.header().into(),
uncles: core.uncles().iter().map(Into::into).collect(),
transactions: core.transactions().iter().map(Into::into).collect(),
proposals: core.proposals().iter().cloned().map(Into::into).collect(),
}
}
}
impl<'a> From<&'a CoreBlock> for BlockView {
fn from(core: &CoreBlock) -> Self {
Self {
header: core.header().into(),
uncles: core.uncles().iter().map(Into::into).collect(),
transactions: core.transactions().iter().map(Into::into).collect(),
proposals: core.proposals().iter().cloned().map(Into::into).collect(),
}
}
}
impl From<Block> for CoreBlock {
fn from(json: Block) -> Self {
let Block {
header,
uncles,
transactions,
proposals,
} = json;
BlockBuilder::default()
.header(header)
.uncles(uncles)
.transactions(transactions)
.proposals(proposals)
.build()
}
}
impl From<BlockView> for CoreBlock {
fn from(json: BlockView) -> Self {
let BlockView {
header,
uncles,
transactions,
proposals,
} = json;
BlockBuilder::default()
.header(header)
.uncles(uncles)
.transactions(transactions)
.proposals(proposals)
.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
use ckb_core::script::ScriptHashType;
use ckb_core::transaction::ProposalShortId as CoreProposalShortId;
use ckb_core::{Bytes, Capacity};
use proptest::{collection::size_range, prelude::*};
fn mock_script(arg: Bytes) -> CoreScript {
CoreScript::new(vec![arg], H256::default(), ScriptHashType::Data)
}
fn mock_cell_output(data: Bytes, arg: Bytes) -> CoreCellOutput {
CoreCellOutput::new(
Capacity::zero(),
CoreCellOutput::calculate_data_hash(&data),
CoreScript::default(),
Some(mock_script(arg)),
)
}
fn mock_cell_input() -> CoreCellInput {
CoreCellInput::new(CoreOutPoint::default(), 0)
}
fn mock_full_tx(data: Bytes, arg: Bytes) -> CoreTransaction {
TransactionBuilder::default()
.deps(vec![CoreOutPoint::default()])
.inputs(vec![mock_cell_input()])
.outputs(vec![mock_cell_output(data.clone(), arg.clone())])
.outputs_data(vec![data])
.witness(vec![arg])
.build()
}
fn mock_uncle() -> CoreUncleBlock {
CoreUncleBlock::new(
HeaderBuilder::default().build(),
vec![CoreProposalShortId::default()],
)
}
fn mock_full_block(data: Bytes, arg: Bytes) -> CoreBlock {
BlockBuilder::default()
.transactions(vec![mock_full_tx(data, arg)])
.uncles(vec![mock_uncle()])
.proposals(vec![CoreProposalShortId::default()])
.build()
}
fn _test_block_convert(data: Bytes, arg: Bytes) -> Result<(), TestCaseError> {
let block = mock_full_block(data, arg);
let json_block: Block = (&block).into();
let encoded = serde_json::to_string(&json_block).unwrap();
let decode: Block = serde_json::from_str(&encoded).unwrap();
let decode_block: CoreBlock = decode.into();
prop_assert_eq!(decode_block, block);
Ok(())
}
proptest! {
#[test]
fn test_block_convert(
data in any_with::<Vec<u8>>(size_range(80).lift()),
arg in any_with::<Vec<u8>>(size_range(80).lift()),
) {
_test_block_convert(Bytes::from(data), Bytes::from(arg))?;
}
}
}
|
//! You can choose between multiple backends to store your session data. The easiest to manage is
//! `SignedCookieBackend`. You need to compile with the `redis-backend` feature to use the Redis
//! backend.
mod signedcookie;
pub use self::signedcookie::SignedCookieBackend;
#[cfg(feature = "redis-backend")]
mod redis;
#[cfg(feature = "redis-backend")]
pub use self::redis::RedisBackend;
|
use ash::version::DeviceV1_0;
use ash::{vk, Device};
use handlegraph::handle::NodeId;
use rustc_hash::FxHashSet;
use std::ops::RangeInclusive;
use nalgebra_glm as glm;
use anyhow::*;
use crate::view::View;
use crate::vulkan::context::NodeRendererType;
use crate::vulkan::GfaestusVk;
use crate::{geometry::Point, vulkan::texture::GradientTexture};
use crate::vulkan::render_pass::Framebuffers;
pub mod base;
pub mod overlay;
pub mod vertices;
pub use base::*;
pub use overlay::*;
pub use vertices::*;
pub struct NodePipelines {
pub pipelines: OverlayPipelines,
selection_descriptors: SelectionDescriptors,
pub vertices: NodeVertices,
device: Device,
renderer_type: NodeRendererType,
}
impl NodePipelines {
pub fn new(app: &GfaestusVk, selection_buffer: vk::Buffer) -> Result<Self> {
let vk_context = app.vk_context();
let device = vk_context.device();
let renderer_type = vk_context.renderer_config.nodes;
log::warn!("node_renderer_type: {:?}", renderer_type);
let vertices = NodeVertices::new(renderer_type);
let selection_descriptors =
SelectionDescriptors::new(app, selection_buffer, 1)?;
let pipelines = OverlayPipelines::new(
app,
renderer_type,
selection_descriptors.layout,
)?;
Ok(Self {
pipelines,
vertices,
selection_descriptors,
device: device.clone(),
renderer_type,
})
}
pub fn device(&self) -> &Device {
&self.device
}
pub fn has_overlay(&self) -> bool {
self.pipelines.overlay_set_id.is_some()
}
pub fn draw(
&mut self,
cmd_buf: vk::CommandBuffer,
render_pass: vk::RenderPass,
framebuffers: &Framebuffers,
viewport_dims: [f32; 2],
node_width: f32,
view: View,
offset: Point,
background_color: rgb::RGB<f32>,
overlay_id: usize,
color_scheme: &GradientTexture,
) -> Result<()> {
self.pipelines.write_overlay(overlay_id, color_scheme)?;
let overlay = self.pipelines.overlays.get(&overlay_id).unwrap();
let device = &self.pipelines.device;
let clear_values = {
let bg = background_color;
[
vk::ClearValue {
color: vk::ClearColorValue {
float32: [bg.r, bg.g, bg.b, 1.0],
},
},
vk::ClearValue {
color: vk::ClearColorValue {
uint32: [0, 0, 0, 0],
},
},
vk::ClearValue {
color: vk::ClearColorValue {
float32: [0.0, 0.0, 0.0, 1.0],
},
},
]
};
let extent = vk::Extent2D {
width: viewport_dims[0] as u32,
height: viewport_dims[1] as u32,
};
let render_pass_begin_info = vk::RenderPassBeginInfo::builder()
.render_pass(render_pass)
.framebuffer(framebuffers.nodes)
.render_area(vk::Rect2D {
offset: vk::Offset2D { x: 0, y: 0 },
extent,
})
.clear_values(&clear_values)
.build();
unsafe {
device.cmd_begin_render_pass(
cmd_buf,
&render_pass_begin_info,
vk::SubpassContents::INLINE,
)
};
self.pipelines.bind_pipeline(device, cmd_buf, overlay.kind);
let vx_bufs = [self.vertices.vertex_buffer];
let offsets = [0];
unsafe {
device.cmd_bind_vertex_buffers(cmd_buf, 0, &vx_bufs, &offsets);
}
self.pipelines.bind_descriptor_sets(
device,
cmd_buf,
overlay_id,
self.selection_descriptors.descriptor_set,
)?;
let push_constants = NodePushConstants::new(
[offset.x, offset.y],
viewport_dims,
view,
node_width,
7,
);
let pc_bytes = push_constants.bytes();
let layout = self.pipelines.pipeline_layout_kind(overlay.kind);
unsafe {
use vk::ShaderStageFlags as Flags;
let mut stages = Flags::VERTEX | Flags::FRAGMENT;
if self.renderer_type == NodeRendererType::TessellationQuads {
stages |= Flags::TESSELLATION_CONTROL
| Flags::TESSELLATION_EVALUATION;
}
device.cmd_push_constants(cmd_buf, layout, stages, 0, &pc_bytes)
};
unsafe {
device.cmd_draw(cmd_buf, self.vertices.vertex_count as u32, 1, 0, 0)
};
// End render pass
unsafe { device.cmd_end_render_pass(cmd_buf) };
Ok(())
}
pub fn destroy(&mut self, app: &super::super::GfaestusVk) {
let device = &self.device;
unsafe {
device.destroy_descriptor_set_layout(
self.selection_descriptors.layout,
None,
);
device
.destroy_descriptor_pool(self.selection_descriptors.pool, None);
}
self.vertices.destroy(app).unwrap();
self.pipelines.destroy(&app.allocator).unwrap();
}
}
pub struct SelectionDescriptors {
pool: vk::DescriptorPool,
layout: vk::DescriptorSetLayout,
// TODO should be one per swapchain image
descriptor_set: vk::DescriptorSet,
// should not be owned by this, but MainView
// buffer: vk::Buffer,
}
impl SelectionDescriptors {
fn new(
app: &GfaestusVk,
buffer: vk::Buffer,
image_count: u32,
// msaa_samples: vk::SampleCountFlags,
) -> Result<Self> {
let vk_context = app.vk_context();
let device = vk_context.device();
let layout = Self::create_descriptor_set_layout(device)?;
let descriptor_pool = {
let pool_size = vk::DescriptorPoolSize {
ty: vk::DescriptorType::STORAGE_BUFFER,
descriptor_count: image_count,
};
let pool_sizes = [pool_size];
let pool_info = vk::DescriptorPoolCreateInfo::builder()
.pool_sizes(&pool_sizes)
.max_sets(image_count)
.build();
unsafe { device.create_descriptor_pool(&pool_info, None) }
}?;
let descriptor_sets = {
let layouts = vec![layout];
let alloc_info = vk::DescriptorSetAllocateInfo::builder()
.descriptor_pool(descriptor_pool)
.set_layouts(&layouts)
.build();
unsafe { device.allocate_descriptor_sets(&alloc_info) }
}?;
for set in descriptor_sets.iter() {
let buf_info = vk::DescriptorBufferInfo::builder()
.buffer(buffer)
.offset(0)
.range(vk::WHOLE_SIZE)
.build();
let buf_infos = [buf_info];
let descriptor_write = vk::WriteDescriptorSet::builder()
.dst_set(*set)
.dst_binding(0)
.dst_array_element(0)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.buffer_info(&buf_infos)
.build();
let descriptor_writes = [descriptor_write];
unsafe { device.update_descriptor_sets(&descriptor_writes, &[]) }
}
Ok(Self {
pool: descriptor_pool,
layout,
// TODO should be one per swapchain image
descriptor_set: descriptor_sets[0],
// should not be owned by this, but MainView
// buffer,
})
}
fn layout_binding() -> vk::DescriptorSetLayoutBinding {
use vk::ShaderStageFlags as Stages;
vk::DescriptorSetLayoutBinding::builder()
.binding(0)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.descriptor_count(1)
.stage_flags(Stages::FRAGMENT)
.build()
}
fn create_descriptor_set_layout(
device: &Device,
) -> Result<vk::DescriptorSetLayout> {
let binding = Self::layout_binding();
let bindings = [binding];
let layout_info = vk::DescriptorSetLayoutCreateInfo::builder()
.bindings(&bindings)
.build();
let layout =
unsafe { device.create_descriptor_set_layout(&layout_info, None) }?;
Ok(layout)
}
}
pub struct NodeIdBuffer {
pub buffer: vk::Buffer,
memory: vk::DeviceMemory,
size: vk::DeviceSize,
pub width: u32,
pub height: u32,
elem_size: u32,
}
impl NodeIdBuffer {
pub fn read_rect(
&self,
device: &Device,
x_range: RangeInclusive<u32>,
y_range: RangeInclusive<u32>,
) -> FxHashSet<NodeId> {
let min_x = (*x_range.start()).max(0);
let max_x = (*x_range.end()).min(self.width - 1);
let min_y = (*y_range.start()).max(0);
let max_y = (*y_range.end()).min(self.height - 1);
let mut values: FxHashSet<NodeId> = FxHashSet::default();
let rows = min_y..=max_y;
let row_width = (max_x - min_x) as usize;
unsafe {
let data_ptr = device
.map_memory(
self.memory,
0,
self.size,
vk::MemoryMapFlags::empty(),
)
.unwrap();
for y in rows {
let row_start = ((y * self.width) + min_x) as usize;
let val_ptr = (data_ptr as *const u32).add(row_start);
let slice = std::slice::from_raw_parts(val_ptr, row_width);
values.extend(slice.iter().filter_map(|&id| {
if id == 0 {
None
} else {
Some(NodeId::from(id as u64))
}
}));
}
device.unmap_memory(self.memory);
}
values
}
pub fn read(&self, device: &Device, x: u32, y: u32) -> Option<u32> {
if x >= self.width || y >= self.height {
return None;
}
let value = unsafe {
let data_ptr = device
.map_memory(
self.memory,
0,
self.size,
vk::MemoryMapFlags::empty(),
)
.unwrap();
let x_offset = |x: u32, o: i32| -> u32 {
let x = x as i32;
(x + o).clamp(0, (self.width - 1) as i32) as u32
};
let y_offset = |y: u32, o: i32| -> u32 {
let y = y as i32;
(y + o).clamp(0, (self.height - 1) as i32) as u32
};
let to_ix =
|x: u32, y: u32| -> usize { (y * self.width + x) as usize };
let index = (y * self.width + x) as usize;
let ix_l = to_ix(x_offset(x, -1), y);
let ix_r = to_ix(x_offset(x, 1), y);
let ix_u = to_ix(x, y_offset(y, -1));
let ix_d = to_ix(x, y_offset(y, 1));
let indices = [index, ix_l, ix_r, ix_u, ix_d];
let mut value = 0;
for &ix in indices.iter() {
let val_ptr = (data_ptr as *const u32).add(ix);
value = val_ptr.read();
if value != 0 {
break;
}
}
device.unmap_memory(self.memory);
value
};
if value == 0 {
None
} else {
Some(value)
}
}
pub fn new(
app: &GfaestusVk,
width: u32,
height: u32,
id_format: vk::Format,
) -> Result<Self> {
use std::mem;
let elem_size = match id_format {
vk::Format::R32_UINT => Ok(mem::size_of::<u32>()),
vk::Format::R32G32_UINT => Ok(mem::size_of::<[u32; 2]>()),
vk::Format::R32G32B32_UINT => Ok(mem::size_of::<[u32; 3]>()),
vk::Format::R32G32B32A32_UINT => Ok(mem::size_of::<[u32; 4]>()),
_ => Err(anyhow!("Incompatible ID format")),
}?;
let img_size = (width * height * elem_size as u32) as vk::DeviceSize;
let usage = vk::BufferUsageFlags::TRANSFER_DST
| vk::BufferUsageFlags::STORAGE_BUFFER;
let mem_props = vk::MemoryPropertyFlags::HOST_VISIBLE
| vk::MemoryPropertyFlags::HOST_COHERENT
| vk::MemoryPropertyFlags::HOST_CACHED;
let (buffer, memory, size) =
app.create_buffer(img_size, usage, mem_props)?;
app.set_debug_object_name(buffer, "Node ID Buffer")?;
Ok(Self {
buffer,
memory,
size,
width,
height,
elem_size: elem_size as u32,
})
}
pub fn destroy(&mut self, device: &Device) {
unsafe {
device.destroy_buffer(self.buffer, None);
device.free_memory(self.memory, None);
}
self.buffer = vk::Buffer::null();
self.memory = vk::DeviceMemory::null();
self.size = 0 as vk::DeviceSize;
self.width = 0;
self.height = 0;
}
pub fn recreate(
&mut self,
app: &GfaestusVk,
width: u32,
height: u32,
) -> Result<()> {
if self.width * self.height == width * height {
return Ok(());
}
self.destroy(app.vk_context().device());
let img_size = (width * height * self.elem_size) as vk::DeviceSize;
let usage = vk::BufferUsageFlags::TRANSFER_DST
| vk::BufferUsageFlags::STORAGE_BUFFER;
let mem_props = vk::MemoryPropertyFlags::HOST_VISIBLE
| vk::MemoryPropertyFlags::HOST_COHERENT;
let (buffer, memory, size) =
app.create_buffer(img_size, usage, mem_props)?;
app.set_debug_object_name(buffer, "Node ID Buffer")?;
self.buffer = buffer;
self.memory = memory;
self.size = size;
self.width = width;
self.height = height;
Ok(())
}
}
pub struct NodePushConstants {
view_transform: glm::Mat4,
node_width: f32,
scale: f32,
viewport_dims: [f32; 2],
texture_period: u32,
}
impl NodePushConstants {
#[inline]
pub fn new(
offset: [f32; 2],
viewport_dims: [f32; 2],
view: crate::view::View,
node_width: f32,
texture_period: u32,
) -> Self {
use crate::view;
let model_mat = glm::mat4(
1.0, 0.0, 0.0, offset[0], 0.0, 1.0, 0.0, offset[1], 0.0, 0.0, 1.0,
0.0, 0.0, 0.0, 0.0, 1.0,
);
let view_mat = view.to_scaled_matrix();
let width = viewport_dims[0];
let height = viewport_dims[1];
let viewport_mat = view::viewport_scale(width, height);
let matrix = viewport_mat * view_mat * model_mat;
Self {
view_transform: matrix,
node_width,
viewport_dims,
scale: view.scale,
texture_period,
}
}
#[inline]
pub fn bytes(&self) -> [u8; 84] {
use crate::view;
let mut bytes = [0u8; 84];
let view_transform_array = view::mat4_to_array(&self.view_transform);
{
let mut offset = 0;
let mut add_float = |f: f32| {
let f_bytes = f.to_ne_bytes();
for i in 0..4 {
bytes[offset] = f_bytes[i];
offset += 1;
}
};
for i in 0..4 {
let row = view_transform_array[i];
for j in 0..4 {
let val = row[j];
add_float(val);
}
}
add_float(self.node_width);
add_float(self.scale);
add_float(self.viewport_dims[0]);
add_float(self.viewport_dims[1]);
}
let u_bytes = self.texture_period.to_ne_bytes();
let mut offset = 80;
for i in 0..4 {
bytes[offset] = u_bytes[i];
offset += 1;
}
bytes
}
}
|
use crate::hittable::HitRecord;
use crate::material::{Material, MaterialType, Scatter};
use crate::ray::Ray;
use crate::texture::{Texture, TextureColor};
use crate::vec::Vec3;
use rand::rngs::SmallRng;
use std::sync::Arc;
// Isotropic
#[derive(Debug, Clone)]
pub struct Isotropic {
pub albedo: Texture,
}
impl Isotropic {
pub fn new(albedo: Texture) -> Arc<MaterialType> {
Arc::new(MaterialType::from(Isotropic { albedo: albedo }))
}
}
impl Material for Isotropic {
fn scatter(&self, rayin: &Ray, hit: &HitRecord, rng: &mut SmallRng) -> Option<Scatter> {
let ray = Ray {
origin: rayin.origin,
direction: Vec3::random_in_unit_sphere(rng),
time: rayin.time,
};
let attenuation = self.albedo.value(hit.u, hit.v, hit.point);
Some(Scatter {
ray: ray,
attenuation: attenuation,
pdf: None,
})
}
}
|
use std::f64::consts::PI;
#[allow(
dead_code,
non_camel_case_types,
non_snake_case,
non_upper_case_globals,
unused_variables
)]
mod ffi_bindgen {
include!(concat!(env!("OUT_DIR"), "/bindings_libint2.rs"));
}
#[allow(dead_code, unused_variables)]
fn compute_eri(
am1: i32,
am2: i32,
am3: i32,
am4: i32,
alpha1: f64,
alpha2: f64,
alpha3: f64,
alpha4: f64,
ra: &[f64; 3],
rb: &[f64; 3],
rc: &[f64; 3],
rd: &[f64; 3],
) -> f64 {
let gammap = alpha1 + alpha2;
let px = (alpha1 * ra[0] + alpha2 * rb[0]) / gammap;
let py = (alpha1 * ra[1] + alpha2 * rb[1]) / gammap;
let pz = (alpha1 * ra[2] + alpha2 * rb[2]) / gammap;
let pax = px - ra[0];
let pay = py - ra[1];
let paz = pz - ra[2];
let pbx = px - rb[0];
let pby = py - rb[1];
let pbz = pz - rb[2];
let ab2 = (ra[0] - rb[0]) * (ra[0] - rb[0])
+ (ra[1] - rb[1]) * (ra[1] - rb[1])
+ (ra[2] - rb[2]) * (ra[2] - rb[2]);
let gammaq = alpha3 + alpha4;
let gammapq = gammap * gammaq / (gammap + gammaq);
let qx = (alpha3 * rc[0] + alpha4 * rd[0]) / gammaq;
let qy = (alpha3 * rc[1] + alpha4 * rd[1]) / gammaq;
let qz = (alpha3 * rc[2] + alpha4 * rd[2]) / gammaq;
let qcx = qx - rc[0];
let qcy = qy - rc[1];
let qcz = qz - rc[2];
let qdx = qx - rd[0];
let qdy = qy - rd[1];
let qdz = qz - rd[2];
let cd2 = (rc[0] - rd[0]) * (rc[0] - rd[0])
+ (rc[1] - rd[1]) * (rc[1] - rd[1])
+ (rc[2] - rd[2]) * (rc[2] - rd[2]);
let pqx = px - qx;
let pqy = py - qy;
let pqz = pz - qz;
let pq2 = pqx * pqx + pqy * pqy + pqz * pqz;
let wx = (gammap * px + gammaq * qx) / (gammap + gammaq);
let wy = (gammap * py + gammaq * qy) / (gammap + gammaq);
let wz = (gammap * pz + gammaq * qz) / (gammap + gammaq);
let k1 = (-alpha1 * alpha2 * ab2 / gammap).exp();
let k2 = (-alpha3 * alpha4 * cd2 / gammaq).exp();
let pfac = 2.0 * PI.powf(2.5) * k1 * k2 / (gammap * gammaq * (gammap + gammaq).sqrt());
let am = am1 + am2 + am3 + am4;
// TODO Boys
let erieval = ffi_bindgen::Libint_t {
PA_x: [pax],
PA_y: [pay],
PA_z: [paz],
PB_x: [pbx],
PB_y: [pby],
PB_z: [pbz],
AB_x: [ra[0] - rb[0]],
AB_y: [ra[1] - rb[1]],
AB_z: [ra[2] - rb[2]],
oo2z: [0.5 / gammap],
QC_x: [qcx],
QC_y: [qcy],
QC_z: [qcz],
CD_x: [rc[0] - rd[0]],
CD_y: [rc[1] - rd[1]],
CD_z: [rc[2] - rd[2]],
oo2e: [0.5 / gammaq],
WP_x: [wx - px],
WP_y: [wy - py],
WP_z: [wz - pz],
WQ_x: [wx - qx],
WQ_y: [wy - qy],
WQ_z: [wz - qz],
oo2ze: [0.5 / (gammap + gammaq)],
roz: [gammapq / gammap],
roe: [gammapq / gammaq],
contrdepth: 1,
stack: unsafe { std::mem::zeroed() },
vstack: unsafe { std::mem::zeroed() },
targets: unsafe { std::mem::zeroed() },
veclen: ffi_bindgen::LIBINT2_MAX_VECLEN as i32,
..Default::default()
};
let f = unsafe { ffi_bindgen::libint2_build_eri }[am1 as usize][am2 as usize][am3 as usize]
[am4 as usize]
.unwrap();
let erieval_ref = &erieval;
let f2 = unsafe { f(erieval_ref) };
0.0
}
#[cxx::bridge]
mod ffi {
struct LibintContraction {
l: i32,
pure: bool,
coeff: Vec<f64>,
}
struct LibintShell {
alpha: Vec<f64>,
contr: Vec<LibintContraction>,
// origin: [f64; 3],
origin: Vec<f64>,
}
enum LibintOperator {
Overlap,
Kinetic,
Nuclear,
ErfNuclear,
ErfcNuclear,
EMultipole1,
EMultipole2,
EMultipole3,
SphEMultipole,
Delta,
Coulomb,
Cgtg,
CgtgTimesCoulomb,
DelCgtgSquared,
R12,
ErfCoulomb,
ErfcCoulomb,
Stg,
StgTimesCoulomb,
}
unsafe extern "C++" {
include!("/usr/include/libint2/engine.h");
#[namespace = "libint2"]
type Engine;
include!("libint2/include/libint2_wrapper.hpp");
fn libint2_init();
fn libint2_finalize();
fn libint2_test_c_api(
am1: i32,
am2: i32,
am3: i32,
am4: i32,
alpha1: f64,
alpha2: f64,
alpha3: f64,
alpha4: f64,
A: &Vec<f64>,
B: &Vec<f64>,
C: &Vec<f64>,
D: &Vec<f64>,
);
fn libint2_calc_boys_reference_single(T: f64, m: usize) -> f64;
fn libint2_calc_boys_chebyshev7(T: f64, max_m: usize) -> UniquePtr<CxxVector<f64>>;
fn libint2_create_engine(
op: LibintOperator,
max_nprim: usize,
max_l: i32,
) -> UniquePtr<Engine>;
}
}
// fn create_engine(oper: Operator, max_nprim: u64, max_l: i32) -> Engine {}
#[cfg(test)]
mod tests {
use super::*;
// use std::cmp;
#[test]
fn test_c_api() {
//! A partial translation of the test at
//! https://github.com/evaleev/libint/blob/3bf3a07b58650fe2ed4cd3dc6517d741562e1249/tests/unit/test-c-api.cc#L23.
ffi::libint2_init();
let am1 = 1;
let am2 = 1;
let am3 = 1;
let am4 = 1;
let alpha1 = 1.1;
let alpha2 = 2.3;
let alpha3 = 3.4;
let alpha4 = 4.8;
let A = vec![0.0, 1.0, 2.0];
let B = vec![1.0, 2.0, 0.0];
let C = vec![2.0, 0.0, 1.0];
let D = vec![0.0, 1.0, 2.0];
ffi::libint2_test_c_api(
am1, am2, am3, am4, alpha1, alpha2, alpha3, alpha4, &A, &B, &C, &D,
);
// let sh1 = ffi::LibintShell {
// alpha: vec![alpha1],
// contr: vec![ffi::LibintContraction {
// l: am1,
// pure: false,
// coeff: vec![1.0],
// }],
// origin: vec![0.0, 1.0, 2.0],
// };
// let sh2 = ffi::LibintShell {
// alpha: vec![alpha2],
// contr: vec![ffi::LibintContraction {
// l: am2,
// pure: false,
// coeff: vec![1.0],
// }],
// origin: vec![1.0, 2.0, 0.0],
// };
// let sh3 = ffi::LibintShell {
// alpha: vec![alpha3],
// contr: vec![ffi::LibintContraction {
// l: am3,
// pure: false,
// coeff: vec![1.0],
// }],
// origin: vec![2.0, 0.0, 1.0],
// };
// let sh4 = ffi::LibintShell {
// alpha: vec![alpha4],
// contr: vec![ffi::LibintContraction {
// l: am4,
// pure: false,
// coeff: vec![1.0],
// }],
// origin: vec![0.0, 1.0, 2.0],
// };
// let shls = vec![sh1, sh2, sh3, sh4];
// let max_am = cmp::max(cmp::max(am1, am2), cmp::max(am3, am4));
// let engine = create_engine(Operator::Coulomb, 1, max_am);
// let result = engine.compute(&shls);
ffi::libint2_finalize();
}
#[test]
fn test_calc_boys() {
println!("{}", ffi::libint2_calc_boys_reference_single(2.0, 2));
println!(
"{:#?}",
ffi::libint2_calc_boys_chebyshev7(2.0, 2)
.iter()
.collect::<Vec<_>>()
);
}
}
|
use ability::{Ability, AbilityFactory};
#[derive(Clone)]
pub struct Player {
name: String,
strength: Ability,
dexterity: Ability,
constitution: Ability,
intelligence: Ability,
wisdom: Ability,
charisma: Ability
}
pub struct PlayerBuilder {
name: String,
strength: Ability,
dexterity: Ability,
constitution: Ability,
intelligence: Ability,
wisdom: Ability,
charisma: Ability
}
impl Player {
pub fn get_name(&self) -> &String {
&self.name
}
pub fn get_strength(&self) -> &Ability {
&self.strength
}
pub fn get_dexterity(&self) -> &Ability {
&self.dexterity
}
pub fn get_constitution(&self) -> &Ability {
&self.constitution
}
pub fn get_intelligence(&self) -> &Ability {
&self.intelligence
}
pub fn get_wisdom(&self) -> &Ability {
&self.wisdom
}
pub fn get_charisma(&self) -> &Ability {
&self.charisma
}
}
impl PlayerBuilder {
pub fn new() -> PlayerBuilder {
PlayerBuilder {
name: "None".to_string(),
strength: AbilityFactory::new().finalize(),
dexterity: AbilityFactory::new().finalize(),
constitution: AbilityFactory::new().finalize(),
intelligence: AbilityFactory::new().finalize(),
wisdom: AbilityFactory::new().finalize(),
charisma: AbilityFactory::new().finalize()
}
}
pub fn name(&mut self, name: String) -> &mut PlayerBuilder {
self.name = name;
self
}
pub fn strength(&mut self, strength: Ability) -> &mut PlayerBuilder {
self.strength = strength;
self
}
pub fn dexterity(&mut self, dexterity: Ability) -> &mut PlayerBuilder {
self.dexterity = dexterity;
self
}
pub fn constitution(&mut self, constitution: Ability) -> &mut PlayerBuilder {
self.constitution = constitution;
self
}
pub fn intelligence(&mut self, intelligence: Ability) -> &mut PlayerBuilder {
self.intelligence = intelligence;
self
}
pub fn wisdom(&mut self, wisdom: Ability) -> &mut PlayerBuilder {
self.wisdom = wisdom;
self
}
pub fn charisma(&mut self, charisma: Ability) -> &mut PlayerBuilder {
self.charisma = charisma;
self
}
pub fn finalize(&mut self) -> Player {
Player {
name: self.name.clone(),
strength: self.strength.clone(),
dexterity: self.dexterity.clone(),
constitution: self.constitution.clone(),
intelligence: self.intelligence.clone(),
wisdom: self.wisdom.clone(),
charisma: self.charisma.clone()
}
}
}
|
use method::Method;
use response::Response;
use address::Address;
#[derive(Debug)]
pub struct LogEntry {
pub address: Address,
pub method: Method,
pub response: Response,
}
impl LogEntry {
pub fn is_valid(&self) -> bool {
self.address.is_valid()
&& self.method.is_valid()
&& self.response.is_valid()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_empty() {
let entry = LogEntry {
address: Address::from(""),
method: Method::from(""),
response: Response::from("")
};
assert_eq!(entry.is_valid(), false);
}
#[test]
fn empty_address() {
let entry = LogEntry {
address: Address::from(""),
method: Method::from("GET"),
response: Response::from("200")
};
assert_eq!(entry.is_valid(), false);
}
#[test]
fn empty_method() {
let entry = LogEntry {
address: Address::from("1.1.1.1"),
method: Method::from(""),
response: Response::from("200")
};
assert_eq!(entry.is_valid(), false);
}
#[test]
fn empty_response() {
let entry = LogEntry {
address: Address::from("1.1.1.1"),
method: Method::from("GET"),
response: Response::from("")
};
assert_eq!(entry.is_valid(), false);
}
#[test]
fn valid() {
let entry = LogEntry {
address: Address::from("1.1.1.1"),
method: Method::from("GET"),
response: Response::from("200")
};
assert_eq!(entry.is_valid(), true);
}
}
|
//!
//!
#[derive(Debug, Clone)]
pub struct Permutation {
state: Vec<usize>,
status: Status,
dim: usize,
n: usize,
end: Vec<usize>,
}
#[derive(Debug, Clone)]
enum Status {
Ini,
Run,
End
}
impl Permutation {
pub fn new( dim: usize, n: usize ) -> Permutation {
Permutation {
state: (0..dim).collect(),
status: Status::Ini,
dim, n,
end: (n-dim..n).rev().collect(),
}
}
fn has_duplication(&self) -> bool {
let mut list: Vec<bool> = vec![ false; self.n ];
for &i in self.state.iter() {
if list[i] {
return true;
} else {
list[i] = true;
}
}
false
}
}
#[cfg(feature = "streaming")]
mod streaming_iterator {
use super::{Permutation, Status};
use streaming_iterator::StreamingIterator;
impl StreamingIterator for Permutation {
type Item = [usize];
fn advance(&mut self) {
match self.status {
Status::Ini => { self.status = Status::Run; },
Status::Run => {
if self.state == self.end {
self.status = Status::End;
} else { while {
self.state[self.dim-1] += 1;
for idx in (1..self.dim).rev() {
if self.state[idx] == self.n {
self.state[idx] = 0;
self.state[idx-1] += 1;
}
}
self.has_duplication()
} {} }
},
Status::End => {},
}
}
fn get(&self) -> Option<&[usize]> {
match self.status {
Status::Ini => None,
Status::Run => Some(&self.state),
Status::End => None,
}
}
fn size_hint(&self) -> (usize,Option<usize>) {
let size = (self.n-self.dim+1..self.n+1).fold(1, |prod, i| prod * i);
( 0, Some(size) )
}
}
}
#[cfg(not(feature = "streaming"))]
mod iterator {
use super::{Permutation, Status};
use std::iter::Iterator;
impl Iterator for Permutation {
type Item = Vec<usize>;
fn next(&mut self) -> Option<Vec<usize>> {
match self.status {
Status::Ini => { self.status = Status::Run; },
Status::Run => {
if self.state == self.end {
self.status = Status::End;
} else { while {
self.state[self.dim-1] += 1;
for idx in (1..self.dim).rev() {
if self.state[idx] == self.n {
self.state[idx] = 0;
self.state[idx-1] += 1;
}
}
self.has_duplication()
} {} }
},
Status::End => {},
}
match self.status {
Status::Ini => None,
Status::Run => Some(self.state.clone()),
Status::End => None,
}
}
fn size_hint(&self) -> (usize,Option<usize>) {
let size = (self.n-self.dim+1..self.n+1).fold(1, |prod, i| prod * i);
( 0, Some(size) )
}
}
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn permutation() {
let dim = 2;
let n = 8;
let mut iter = Permutation::new( dim, n );
let mut count = 0;
while let Some(idx) = iter.next() {
count += 1;
println!("{:?}", idx);
}
assert_eq!( count, n * (n-1) );
}
#[test]
fn datial() {
let dim = 3;
let n = 4;
let mut iter = Permutation::new( dim, n );
assert_eq!( iter.next().unwrap(), &[0,1,2] );
assert_eq!( iter.next().unwrap(), &[0,1,3] );
assert_eq!( iter.next().unwrap(), &[0,2,1] );
assert_eq!( iter.next().unwrap(), &[0,2,3] );
assert_eq!( iter.next().unwrap(), &[0,3,1] );
assert_eq!( iter.next().unwrap(), &[0,3,2] );
assert_eq!( iter.next().unwrap(), &[1,0,2] );
assert_eq!( iter.next().unwrap(), &[1,0,3] );
assert_eq!( iter.next().unwrap(), &[1,2,0] );
assert_eq!( iter.next().unwrap(), &[1,2,3] );
assert_eq!( iter.next().unwrap(), &[1,3,0] );
assert_eq!( iter.next().unwrap(), &[1,3,2] );
assert_eq!( iter.next().unwrap(), &[2,0,1] );
assert_eq!( iter.next().unwrap(), &[2,0,3] );
assert_eq!( iter.next().unwrap(), &[2,1,0] );
assert_eq!( iter.next().unwrap(), &[2,1,3] );
assert_eq!( iter.next().unwrap(), &[2,3,0] );
assert_eq!( iter.next().unwrap(), &[2,3,1] );
assert_eq!( iter.next().unwrap(), &[3,0,1] );
assert_eq!( iter.next().unwrap(), &[3,0,2] );
assert_eq!( iter.next().unwrap(), &[3,1,0] );
assert_eq!( iter.next().unwrap(), &[3,1,2] );
assert_eq!( iter.next().unwrap(), &[3,2,0] );
assert_eq!( iter.next().unwrap(), &[3,2,1] );
assert_eq!( iter.next(), None );
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.