text stringlengths 8 4.13M |
|---|
use std::str::FromStr;
use pesel::pesel::{PESEL as PESEL, PeselGender};
fn main() {
let pesel_number ="44051401458";
let pesel = PESEL::from_str(pesel_number);
match pesel {
Ok(t) => println!("{}", t),
_ => panic!("invalid PESEL provided")
}
println!("--- PESEL generation ----");
let generated_pesel = PESEL::new(1980, 05, 26, PeselGender::Male );
match generated_pesel {
Ok(pesel_number) => println!("generated_pesel: {}", pesel_number),
_ => println!("unable to create PESEL for specified date")
}
}
|
use super::Primitive;
use gl::types::*;
pub trait BufferData {
fn prototype() -> Vec<(Primitive, GLuint)>;
}
macro_rules! bufferdata_impl {
($ty:ty, $name:ident;) => {
impl BufferData for $ty {
fn prototype() -> Vec<(Primitive, GLuint)> {
vec![(Primitive::$name, 1)]
}
}
};
($ty:ty, $name:ident; $($t:tt)+) => {
bufferdata_impl!{$ty, $name;}
bufferdata_impl!{$($t)+}
};
(2, $ty:ty, $name:ident; $($t:tt)*) => {
impl BufferData for [$ty; 2] {
fn prototype() -> Vec<(Primitive, GLuint)> {
vec![(Primitive::$name, 2)]
}
}
bufferdata_impl!{$ty, $name; $($t)*}
};
(3, $ty:ty, $name:ident; $($t:tt)*) => {
impl BufferData for [$ty; 3] {
fn prototype() -> Vec<(Primitive, GLuint)> {
vec![(Primitive::$name, 3)]
}
}
bufferdata_impl!{2, $ty, $name; $($t)*}
};
(4, $ty:ty, $name:ident; $($t:tt)*) => {
impl BufferData for [$ty; 4] {
fn prototype() -> Vec<(Primitive, GLuint)> {
vec![(Primitive::$name, 4)]
}
}
bufferdata_impl!{3, $ty, $name; $($t)*}
};
}
bufferdata_impl!{
4, i32, Int;
4, u32, UInt;
4, f32, Float;
4, f64, Double;
}
|
pub struct Solution;
impl Solution {
pub fn candy(ratings: Vec<i32>) -> i32 {
let mut count = vec![1; ratings.len()];
for i in 1..ratings.len() {
if ratings[i] > ratings[i - 1] {
count[i] = count[i - 1] + 1;
}
}
for i in (1..ratings.len()).rev() {
if ratings[i - 1] > ratings[i] {
count[i - 1] = count[i - 1].max(count[i] + 1);
}
}
count.iter().sum()
}
}
#[test]
fn test0135() {
assert_eq!(Solution::candy(vec![1, 0, 2]), 5);
assert_eq!(Solution::candy(vec![1, 2, 2]), 4);
assert_eq!(Solution::candy(vec![1, 2, 3, 1, 0]), 9);
assert_eq!(Solution::candy(vec![1, 3, 4, 5, 2]), 11);
}
|
use crate::filter::{account_id_query, with_db, SongLogQuery};
use model::{Account, Score, ScoreId};
use mysql::MySqlPool;
use repository::ScoreByAccountAndSha256;
use warp::filters::BoxedFilter;
use warp::path;
use warp::{Filter, Rejection, Reply};
pub fn route(db_pool: &MySqlPool) -> BoxedFilter<(impl Reply,)> {
warp::get()
.and(path("score"))
.and(with_db(db_pool))
.and(account_id_query(db_pool))
.and(warp::query::<SongLogQuery>())
.and_then(handler)
.boxed()
}
async fn handler<C: ScoreByAccountAndSha256>(
mut repos: C,
account: Account,
query: SongLogQuery,
) -> Result<impl Reply, Rejection> {
let score_id = ScoreId::new(query.sha256, query.play_mode);
log::info!("account: {:?}, score_id: {:?}", account, score_id);
let score_with_log = repos
.score_with_log(&account, &score_id)
.unwrap_or(Score::default());
log::debug!("log: {:?}", score_with_log);
Ok(serde_json::to_string(&score_with_log).unwrap())
}
|
use super::{genericalias, type_};
use crate::{
atomic_func,
builtins::{PyFrozenSet, PyStr, PyTuple, PyTupleRef, PyType},
class::PyClassImpl,
common::hash,
convert::{ToPyObject, ToPyResult},
function::PyComparisonValue,
protocol::{PyMappingMethods, PyNumberMethods},
types::{AsMapping, AsNumber, Comparable, GetAttr, Hashable, PyComparisonOp, Representable},
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
};
use once_cell::sync::Lazy;
use std::fmt;
const CLS_ATTRS: &[&str] = &["__module__"];
#[pyclass(module = "types", name = "UnionType", traverse)]
pub struct PyUnion {
args: PyTupleRef,
parameters: PyTupleRef,
}
impl fmt::Debug for PyUnion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("UnionObject")
}
}
impl PyPayload for PyUnion {
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.union_type
}
}
impl PyUnion {
pub fn new(args: PyTupleRef, vm: &VirtualMachine) -> Self {
let parameters = make_parameters(&args, vm);
Self { args, parameters }
}
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
fn repr_item(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
if obj.is(vm.ctx.types.none_type) {
return Ok("None".to_string());
}
if vm
.get_attribute_opt(obj.clone(), identifier!(vm, __origin__))?
.is_some()
&& vm
.get_attribute_opt(obj.clone(), identifier!(vm, __args__))?
.is_some()
{
return Ok(obj.repr(vm)?.as_str().to_string());
}
match (
vm.get_attribute_opt(obj.clone(), identifier!(vm, __qualname__))?
.and_then(|o| o.downcast_ref::<PyStr>().map(|n| n.as_str().to_string())),
vm.get_attribute_opt(obj.clone(), identifier!(vm, __module__))?
.and_then(|o| o.downcast_ref::<PyStr>().map(|m| m.as_str().to_string())),
) {
(None, _) | (_, None) => Ok(obj.repr(vm)?.as_str().to_string()),
(Some(qualname), Some(module)) => Ok(if module == "builtins" {
qualname
} else {
format!("{module}.{qualname}")
}),
}
}
Ok(self
.args
.iter()
.map(|o| repr_item(o.clone(), vm))
.collect::<PyResult<Vec<_>>>()?
.join(" | "))
}
}
#[pyclass(
flags(BASETYPE),
with(Hashable, Comparable, AsMapping, AsNumber, Representable)
)]
impl PyUnion {
#[pygetset(magic)]
fn parameters(&self) -> PyObjectRef {
self.parameters.clone().into()
}
#[pygetset(magic)]
fn args(&self) -> PyObjectRef {
self.args.clone().into()
}
#[pymethod(magic)]
fn instancecheck(zelf: PyRef<Self>, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
if zelf
.args
.iter()
.any(|x| x.class().is(vm.ctx.types.generic_alias_type))
{
Err(vm.new_type_error(
"isinstance() argument 2 cannot be a parameterized generic".to_owned(),
))
} else {
obj.is_instance(zelf.args().as_object(), vm)
}
}
#[pymethod(magic)]
fn subclasscheck(zelf: PyRef<Self>, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
if zelf
.args
.iter()
.any(|x| x.class().is(vm.ctx.types.generic_alias_type))
{
Err(vm.new_type_error(
"issubclass() argument 2 cannot be a parameterized generic".to_owned(),
))
} else {
obj.is_subclass(zelf.args().as_object(), vm)
}
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
type_::or_(zelf, other, vm)
}
}
pub fn is_unionable(obj: PyObjectRef, vm: &VirtualMachine) -> bool {
obj.class().is(vm.ctx.types.none_type)
|| obj.payload_if_subclass::<PyType>(vm).is_some()
|| obj.class().is(vm.ctx.types.generic_alias_type)
|| obj.class().is(vm.ctx.types.union_type)
}
fn make_parameters(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupleRef {
let parameters = genericalias::make_parameters(args, vm);
dedup_and_flatten_args(¶meters, vm)
}
fn flatten_args(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupleRef {
let mut total_args = 0;
for arg in args {
if let Some(pyref) = arg.downcast_ref::<PyUnion>() {
total_args += pyref.args.len();
} else {
total_args += 1;
};
}
let mut flattened_args = Vec::with_capacity(total_args);
for arg in args {
if let Some(pyref) = arg.downcast_ref::<PyUnion>() {
flattened_args.extend(pyref.args.iter().cloned());
} else if vm.is_none(arg) {
flattened_args.push(vm.ctx.types.none_type.to_owned().into());
} else {
flattened_args.push(arg.clone());
};
}
PyTuple::new_ref(flattened_args, &vm.ctx)
}
fn dedup_and_flatten_args(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupleRef {
let args = flatten_args(args, vm);
let mut new_args: Vec<PyObjectRef> = Vec::with_capacity(args.len());
for arg in &*args {
if !new_args.iter().any(|param| {
param
.rich_compare_bool(arg, PyComparisonOp::Eq, vm)
.expect("types are always comparable")
}) {
new_args.push(arg.clone());
}
}
new_args.shrink_to_fit();
PyTuple::new_ref(new_args, &vm.ctx)
}
pub fn make_union(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyObjectRef {
let args = dedup_and_flatten_args(args, vm);
match args.len() {
1 => args.fast_getitem(0),
_ => PyUnion::new(args, vm).to_pyobject(vm),
}
}
impl PyUnion {
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let new_args = genericalias::subs_parameters(
|vm| self.repr(vm),
self.args.clone(),
self.parameters.clone(),
needle,
vm,
)?;
let mut res;
if new_args.len() == 0 {
res = make_union(&new_args, vm);
} else {
res = new_args.fast_getitem(0);
for arg in new_args.iter().skip(1) {
res = vm._or(&res, arg)?;
}
}
Ok(res)
}
}
impl AsMapping for PyUnion {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: Lazy<PyMappingMethods> = Lazy::new(|| PyMappingMethods {
subscript: atomic_func!(|mapping, needle, vm| {
PyUnion::mapping_downcast(mapping).getitem(needle.to_owned(), vm)
}),
..PyMappingMethods::NOT_IMPLEMENTED
});
&AS_MAPPING
}
}
impl AsNumber for PyUnion {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
or: Some(|a, b, vm| PyUnion::or(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}
impl Comparable for PyUnion {
fn cmp(
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
op.eq_only(|| {
let other = class_or_notimplemented!(Self, other);
let a = PyFrozenSet::from_iter(vm, zelf.args.into_iter().cloned())?;
let b = PyFrozenSet::from_iter(vm, other.args.into_iter().cloned())?;
Ok(PyComparisonValue::Implemented(
a.into_pyobject(vm).as_object().rich_compare_bool(
b.into_pyobject(vm).as_object(),
PyComparisonOp::Eq,
vm,
)?,
))
})
}
}
impl Hashable for PyUnion {
#[inline]
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
let set = PyFrozenSet::from_iter(vm, zelf.args.into_iter().cloned())?;
PyFrozenSet::hash(&set.into_ref(&vm.ctx), vm)
}
}
impl GetAttr for PyUnion {
fn getattro(zelf: &Py<Self>, attr: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
for &exc in CLS_ATTRS {
if *exc == attr.to_string() {
return zelf.as_object().generic_getattr(attr, vm);
}
}
zelf.as_object().get_attr(attr, vm)
}
}
impl Representable for PyUnion {
#[inline]
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
zelf.repr(vm)
}
}
pub fn init(context: &Context) {
let union_type = &context.types.union_type;
PyUnion::extend_class(context, union_type);
}
|
use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use crate::parser::*;
use ast::*;
use anyhow::{anyhow, Context, Result};
struct Writer {
path: PathBuf,
file: File,
depth: usize,
}
impl Writer {
fn new(path: PathBuf) -> Result<Writer> {
let file = File::create(path.clone())?;
Ok(Writer {
path: path,
file: file,
depth: 0,
})
}
fn open<F>(&mut self, tag: &str, f: F) -> Result<()>
where
F: FnOnce(&mut Writer) -> Result<()>,
{
self.write(format!("<{}>", tag).as_str())?;
self.depth += 1;
f(self)?;
self.depth -= 1;
self.write(format!("</{}>", tag).as_str())
}
fn tag(&mut self, tag: &str, s: &str) -> Result<()> {
let spacer = " ".repeat(self.depth);
writeln!(self.file, "{}<{}> {} </{}>", spacer, tag, s, tag)
.with_context(|| format!("failed to write xml file : {}", self.path.display()))
}
fn keyword(&mut self, s: &str) -> Result<()> {
self.tag("keyword", s)
}
fn symbol(&mut self, s: &str) -> Result<()> {
self.tag("symbol", s)
}
fn identifier(&mut self, s: &str) -> Result<()> {
self.tag("identifier", s)
}
fn typ(&mut self, ty: &Type) -> Result<()> {
match ty {
Type::Int | Type::Char | Type::Boolean => self.keyword(&ty.display()),
Type::Class(name) => self.identifier(&name),
}
}
fn write(&mut self, s: &str) -> Result<()> {
let spacer = " ".repeat(self.depth);
writeln!(self.file, "{}{}", spacer, s)
.with_context(|| format!("failed to write xml file : {}", self.path.display()))
}
fn flush(&mut self) -> Result<()> {
self.file
.flush()
.with_context(|| format!("failed to flush xml file : {}", self.path.display()))
}
}
pub fn write_asts(asts: ASTs) -> Result<()> {
let path = asts.source.ast_xml_filename()?;
let mut w = Writer::new(path)?;
write_class(&mut w, &asts.class)?;
w.flush()
}
fn write_class(f: &mut Writer, cls: &Class) -> Result<()> {
f.open("class", |f| {
f.keyword("class")?;
f.identifier(&cls.name)?;
f.symbol("{")?;
cls.vars
.iter()
.map(|var| write_class_var_dec(f, var))
.collect::<Result<()>>()?;
cls.subroutines
.iter()
.map(|sub| write_subroutine_dec(f, sub))
.collect::<Result<()>>()?;
f.symbol("}")
})
}
fn write_class_var_dec(f: &mut Writer, var: &ClassVarDec) -> Result<()> {
f.open("classVarDec", |f| {
f.keyword(&var.modifier.display())?;
f.typ(&var.typ)?;
let (head, rest) = var
.names
.split_first()
.ok_or_else(|| anyhow!("write_class_var_dec: empty vars"))?;
f.identifier(head)?;
rest.iter()
.map(|name| f.symbol(",").and(f.identifier(&name)))
.collect::<Result<()>>()?;
f.symbol(";")
})
}
fn write_subroutine_dec(f: &mut Writer, sub: &SubroutineDec) -> Result<()> {
f.open("subroutineDec", |f| {
f.keyword(&sub.modifier.display())?;
match sub.typ {
ReturnType::Void => f.keyword("void"),
ReturnType::Type(ref ty) => f.typ(ty),
}?;
f.identifier(&sub.name)?;
write_parameters(f, &sub.parameters)?;
write_subroutine_body(f, &sub.body)
})
}
fn write_parameters(f: &mut Writer, params: &Vec<ParameterDec>) -> Result<()> {
f.symbol("(")?;
f.open("parameterList", |f| {
params
.split_first()
.map(|(head, rest)| {
write_parameter(f, head)?;
rest.iter()
.map(|param| f.symbol(",").and(write_parameter(f, param)))
.collect::<Result<()>>()
})
.unwrap_or(Ok(()))
})?;
f.symbol(")")
}
fn write_parameter(f: &mut Writer, param: &ParameterDec) -> Result<()> {
f.typ(¶m.typ)?;
f.identifier(¶m.name)
}
fn write_subroutine_body(f: &mut Writer, body: &SubroutineBody) -> Result<()> {
f.open("subroutineBody", |f| {
f.symbol("{")?;
body.vars
.iter()
.map(|var| write_var_dec(f, var))
.collect::<Result<()>>()?;
write_statements(f, &body.statements)?;
f.symbol("}")
})
}
fn write_var_dec(f: &mut Writer, var: &VarDec) -> Result<()> {
f.open("varDec", |f| {
f.keyword("var")?;
f.typ(&var.typ)?;
let (head, rest) = var
.names
.split_first()
.ok_or_else(|| anyhow!("write_var_dec: empty vars"))?;
f.identifier(head)?;
rest.iter()
.map(|name| f.symbol(",").and(f.identifier(&name)))
.collect::<Result<()>>()?;
f.symbol(";")
})
}
fn write_statements(f: &mut Writer, statements: &Statements) -> Result<()> {
f.open("statements", |f| {
statements
.statements
.iter()
.map(|stmt| write_statement(f, stmt))
.collect::<Result<()>>()
})
}
fn write_statement(f: &mut Writer, stmt: &Statement) -> Result<()> {
match stmt {
Statement::Let(stmt) => write_let_stmt(f, stmt),
Statement::If(stmt) => write_if_stmt(f, stmt),
Statement::While(stmt) => write_while_stmt(f, stmt),
Statement::Do(stmt) => write_do_stmt(f, stmt),
Statement::Return(stmt) => write_return_stmt(f, stmt),
}
}
fn write_let_stmt(f: &mut Writer, stmt: &LetStatement) -> Result<()> {
f.open("letStatement", |f| {
f.keyword("let")?;
f.identifier(&stmt.name)?;
stmt.accessor
.as_ref()
.map(|expr| {
f.symbol("[")?;
write_expr(f, &expr)?;
f.symbol("]")
})
.unwrap_or(Ok(()))?;
f.symbol("=")?;
write_expr(f, &stmt.expr)?;
f.symbol(";")
})
}
fn write_if_stmt(f: &mut Writer, stmt: &IfStatement) -> Result<()> {
f.open("ifStatement", |f| {
f.keyword("if")?;
f.symbol("(")?;
write_expr(f, &stmt.cond)?;
f.symbol(")")?;
f.symbol("{")?;
write_statements(f, &stmt.statements)?;
stmt.else_branch
.as_ref()
.map(|els| {
f.symbol("}")?;
f.keyword("else")?;
f.symbol("{")?;
write_statements(f, &els)
})
.unwrap_or(Ok(()))?;
f.symbol("}")
})
}
fn write_while_stmt(f: &mut Writer, stmt: &WhileStatement) -> Result<()> {
f.open("whileStatement", |f| {
f.keyword("while")?;
f.symbol("(")?;
write_expr(f, &stmt.cond)?;
f.symbol(")")?;
f.symbol("{")?;
write_statements(f, &stmt.statements)?;
f.symbol("}")
})
}
fn write_do_stmt(f: &mut Writer, stmt: &DoStatement) -> Result<()> {
f.open("doStatement", |f| {
f.keyword("do")?;
write_call(f, &stmt.call)?;
f.symbol(";")
})
}
fn write_return_stmt(f: &mut Writer, stmt: &ReturnStatement) -> Result<()> {
f.open("returnStatement", |f| {
f.keyword("return")?;
stmt.expr
.as_ref()
.map(|expr| write_expr(f, &expr))
.unwrap_or(Ok(()))?;
f.symbol(";")
})
}
fn write_expr(f: &mut Writer, expr: &Expr) -> Result<()> {
f.open("expression", |f| {
write_term(f, &expr.lhs)?;
let mut rhs = &expr.rhs;
while let Some((op, e)) = rhs.as_ref() {
f.symbol(&op.display())?;
write_term(f, &e.lhs)?;
rhs = &e.rhs;
}
Ok(())
})
}
/** write expr tree with operator priority
fn write_expr(f: &mut Writer, expr: &Expr) -> Result<()> {
f.open("expression", |f| {
write_term(f, &expr.lhs)?;
expr.rhs
.as_ref()
.as_ref()
.map(|(op, e)| {
f.symbol(&op.display())?;
write_expr(f, &e)
})
.unwrap_or(Ok(()))
})
}
*/
fn write_term(f: &mut Writer, term: &Term) -> Result<()> {
f.open("term", |f| match term {
Term::Integer(n) => f.tag("integerConstant", &n.to_string()),
Term::Str(s) => f.tag("stringConstant", &s),
Term::Keyword(kwd) => f.keyword(&kwd.display()),
Term::Var(ident) => f.identifier(ident),
Term::IndexAccess(ident, expr) => {
f.identifier(ident)?;
f.symbol("[")?;
write_expr(f, expr)?;
f.symbol("]")
}
Term::Call(call) => write_call(f, call),
Term::Expr(expr) => {
f.symbol("(")?;
write_expr(f, expr)?;
f.symbol(")")
}
Term::Unary(unaryop, term) => {
f.symbol(&unaryop.display())?;
write_term(f, term)
}
})
}
fn write_call(f: &mut Writer, call: &SubroutineCall) -> Result<()> {
call.reciever
.as_ref()
.map(|recv| {
f.identifier(&recv)?;
f.symbol(".")
})
.unwrap_or(Ok(()))?;
f.identifier(&call.name)?;
f.symbol("(")?;
f.open("expressionList", |f| {
call.exprs
.split_first()
.map(|(head, rest)| {
write_expr(f, head)?;
rest.iter()
.map(|param| f.symbol(",").and(write_expr(f, param)))
.collect::<Result<()>>()
})
.unwrap_or(Ok(()))
})?;
f.symbol(")")
}
|
use std::io;
use std::net::Shutdown;
use std::os::unix::net;
use std::os::unix::prelude::*;
use std::path::Path;
use libc;
use mio::event::Evented;
use mio::unix::EventedFd;
use mio::{Poll, Token, Ready, PollOpt};
use cvt;
use socket::{sockaddr_un, Socket};
/// A Unix datagram socket.
#[derive(Debug)]
pub struct UnixDatagram {
inner: net::UnixDatagram,
}
impl UnixDatagram {
/// Creates a Unix datagram socket bound to the given path.
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
UnixDatagram::_bind(path.as_ref())
}
fn _bind(path: &Path) -> io::Result<UnixDatagram> {
unsafe {
let (addr, len) = try!(sockaddr_un(path));
let fd = try!(Socket::new(libc::SOCK_DGRAM));
let addr = &addr as *const _ as *const _;
try!(cvt(libc::bind(fd.fd(), addr, len)));
Ok(UnixDatagram::from_raw_fd(fd.into_fd()))
}
}
/// Consumes a standard library `UnixDatagram` and returns a wrapped
/// `UnixDatagram` compatible with mio.
///
/// The returned stream is moved into nonblocking mode and is otherwise
/// ready to get associated with an event loop.
pub fn from_datagram(stream: net::UnixDatagram) -> io::Result<UnixDatagram> {
try!(stream.set_nonblocking(true));
Ok(UnixDatagram { inner: stream })
}
/// Create an unnamed pair of connected sockets.
///
/// Returns two `UnixDatagrams`s which are connected to each other.
pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
unsafe {
let (a, b) = try!(Socket::pair(libc::SOCK_DGRAM));
Ok((UnixDatagram::from_raw_fd(a.into_fd()),
UnixDatagram::from_raw_fd(b.into_fd())))
}
}
/// Creates a Unix Datagram socket which is not bound to any address.
pub fn unbound() -> io::Result<UnixDatagram> {
let stream = try!(net::UnixDatagram::unbound());
try!(stream.set_nonblocking(true));
Ok(UnixDatagram { inner: stream })
}
/// Connects the socket to the specified address.
///
/// The `send` method may be used to send data to the specified address.
/// `recv` and `recv_from` will only receive data from that address.
pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self.inner.connect(path)
}
/// Creates a new independently owned handle to the underlying socket.
///
/// The returned `UnixListener` is a reference to the same socket that this
/// object references. Both handles can be used to accept incoming
/// connections and options set on one listener will affect the other.
pub fn try_clone(&self) -> io::Result<UnixDatagram> {
self.inner.try_clone().map(|i| {
UnixDatagram { inner: i }
})
}
/// Returns the address of this socket.
pub fn local_addr(&self) -> io::Result<net::SocketAddr> {
self.inner.local_addr()
}
/// Returns the address of this socket's peer.
///
/// The `connect` method will connect the socket to a peer.
pub fn peer_addr(&self) -> io::Result<net::SocketAddr> {
self.inner.peer_addr()
}
/// Receives data from the socket.
///
/// On success, returns the number of bytes read and the address from
/// whence the data came.
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, net::SocketAddr)> {
self.inner.recv_from(buf)
}
/// Receives data from the socket.
///
/// On success, returns the number of bytes read.
pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.recv(buf)
}
/// Sends data on the socket to the specified address.
///
/// On success, returns the number of bytes written.
pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
self.inner.send_to(buf, path)
}
/// Sends data on the socket to the socket's peer.
///
/// The peer address may be set by the `connect` method, and this method
/// will return an error if the socket has not already been connected.
///
/// On success, returns the number of bytes written.
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
self.inner.send(buf)
}
/// Returns the value of the `SO_ERROR` option.
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner.take_error()
}
/// Shut down the read, write, or both halves of this connection.
///
/// This function will cause all pending and future I/O calls on the
/// specified portions to immediately return with an appropriate value
/// (see the documentation of `Shutdown`).
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.inner.shutdown(how)
}
}
impl Evented for UnixDatagram {
fn register(&self,
poll: &Poll,
token: Token,
events: Ready,
opts: PollOpt) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).register(poll, token, events, opts)
}
fn reregister(&self,
poll: &Poll,
token: Token,
events: Ready,
opts: PollOpt) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).deregister(poll)
}
}
impl AsRawFd for UnixDatagram {
fn as_raw_fd(&self) -> i32 {
self.inner.as_raw_fd()
}
}
impl IntoRawFd for UnixDatagram {
fn into_raw_fd(self) -> i32 {
self.inner.into_raw_fd()
}
}
impl FromRawFd for UnixDatagram {
unsafe fn from_raw_fd(fd: i32) -> UnixDatagram {
UnixDatagram { inner: net::UnixDatagram::from_raw_fd(fd) }
}
}
|
use actix_web::middleware::Logger;
use actix_web::{error, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use env_logger::Env;
mod expressiontree;
mod parser;
use parser::parse;
use std::env;
use std::io::{self, BufRead};
use serde::Serialize;
#[derive(Serialize)]
struct Roll {
outcome: expressiontree::DiceExpression,
formula: String,
result: Vec<i64>,
size: usize,
number_of_rolls: usize,
trivial: bool,
}
async fn roll(req: HttpRequest) -> impl Responder {
let expression = req.match_info().get("roll").unwrap_or("d6");
let parsed_expression = parse(expression);
match parsed_expression {
Ok(expression) => {
if expression.size() <= 2001 {
let outcome = expression.outcome();
let roll = Roll {
outcome: outcome.clone(),
formula: format!("{}", outcome),
result: outcome.roll(),
size: outcome.size(),
number_of_rolls: outcome.number_of_rolls(),
trivial: outcome.trivial(),
};
Ok(HttpResponse::Ok().json(roll))
} else {
Err(error::ErrorBadRequest("Expression too large"))
}
}
Err(_) => Err(error::ErrorBadRequest("Could not parse expression")),
}
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
if env::args().any(|s| s == "cmd") {
println!("CMD mode");
let stdin = io::stdin();
for line in stdin.lock().lines() {
if let Ok(result) = parse(&line.unwrap()) {
let roll = result.outcome();
let serialized = serde_json::to_string(&roll).unwrap();
println!("{} = {:?} , size: {}", serialized, roll.roll(), roll.size());
}
}
Ok(())
} else {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
HttpServer::new(|| {
App::new()
.wrap(Logger::default())
.route(r"/roll/{roll}", web::get().to(roll))
})
.bind("127.0.0.1:6810")?
.run()
.await
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![feature(async_await, await_macro, futures_api)]
use carnelian::{
App, AppAssistant, ViewAssistant, ViewAssistantContext, ViewAssistantPtr, ViewKey, ViewMessages,
};
use failure::{Error, ResultExt};
use fidl::endpoints::{RequestStream, ServiceMarker};
use fidl_fidl_examples_echo::{EchoMarker, EchoRequest, EchoRequestStream};
use fidl_fuchsia_ui_gfx::{self as gfx, ColorRgba};
use fuchsia_async::{self as fasync, Interval};
use fuchsia_scenic::{Material, Rectangle, SessionPtr, ShapeNode};
use fuchsia_zircon::{ClockId, Duration, Time};
use futures::prelude::*;
use std::f32::consts::PI;
struct SpinningSquareAppAssistant;
impl AppAssistant for SpinningSquareAppAssistant {
fn setup(&mut self) -> Result<(), Error> {
Ok(())
}
fn create_view_assistant(&mut self, session: &SessionPtr) -> Result<ViewAssistantPtr, Error> {
Ok(Box::new(SpinningSquareViewAssistant {
background_node: ShapeNode::new(session.clone()),
spinning_square_node: ShapeNode::new(session.clone()),
start: Time::get(ClockId::Monotonic),
}))
}
/// Return the list of names of services this app wants to provide
fn outgoing_services_names(&self) -> Vec<&'static str> {
[EchoMarker::NAME].to_vec()
}
/// Handle a request to connect to a service provided by this app
fn handle_service_connection_request(
&mut self,
_service_name: &str,
channel: fasync::Channel,
) -> Result<(), Error> {
Self::create_echo_server(channel, false);
Ok(())
}
}
impl SpinningSquareAppAssistant {
fn create_echo_server(channel: fasync::Channel, quiet: bool) {
fasync::spawn_local(
async move {
let mut stream = EchoRequestStream::from_channel(channel);
while let Some(EchoRequest::EchoString { value, responder }) =
await!(stream.try_next()).context("error running echo server")?
{
if !quiet {
println!("Spinning Square received echo request for string {:?}", value);
}
responder
.send(value.as_ref().map(|s| &**s))
.context("error sending response")?;
if !quiet {
println!("echo response sent successfully");
}
}
Ok(())
}
.unwrap_or_else(|e: failure::Error| eprintln!("{:?}", e)),
);
}
}
struct SpinningSquareViewAssistant {
background_node: ShapeNode,
spinning_square_node: ShapeNode,
start: Time,
}
impl SpinningSquareViewAssistant {
fn setup_timer(key: ViewKey) {
let timer = Interval::new(Duration::from_millis(10));
let f = timer
.map(move |_| {
App::with(|app| {
app.send_message(key, &ViewMessages::Update);
});
})
.collect::<()>();
fasync::spawn_local(f);
}
}
impl ViewAssistant for SpinningSquareViewAssistant {
fn setup(&mut self, context: &ViewAssistantContext) -> Result<(), Error> {
context.import_node.resource().set_event_mask(gfx::METRICS_EVENT_MASK);
context.import_node.add_child(&self.background_node);
let material = Material::new(context.session.clone());
material.set_color(ColorRgba { red: 0xb7, green: 0x41, blue: 0x0e, alpha: 0xff });
self.background_node.set_material(&material);
context.import_node.add_child(&self.spinning_square_node);
let material = Material::new(context.session.clone());
material.set_color(ColorRgba { red: 0xff, green: 0x00, blue: 0xff, alpha: 0xff });
self.spinning_square_node.set_material(&material);
Self::setup_timer(context.key);
Ok(())
}
fn update(&mut self, context: &ViewAssistantContext) -> Result<(), Error> {
const SPEED: f32 = 0.25;
const SECONDS_PER_NANOSECOND: f32 = 1e-9;
let center_x = context.size.width * 0.5;
let center_y = context.size.height * 0.5;
self.background_node.set_shape(&Rectangle::new(
context.session.clone(),
context.size.width,
context.size.height,
));
self.background_node.set_translation(center_x, center_y, 0.0);
let square_size = context.size.width.min(context.size.height) * 0.6;
let t = ((Time::get(ClockId::Monotonic).nanos() - self.start.nanos()) as f32
* SECONDS_PER_NANOSECOND
* SPEED)
% 1.0;
let angle = t * PI * 2.0;
self.spinning_square_node.set_shape(&Rectangle::new(
context.session.clone(),
square_size,
square_size,
));
self.spinning_square_node.set_translation(center_x, center_y, -8.0);
self.spinning_square_node.set_rotation(0.0, 0.0, (angle * 0.5).sin(), (angle * 0.5).cos());
Ok(())
}
}
fn main() -> Result<(), Error> {
let assistant = SpinningSquareAppAssistant {};
App::run(Box::new(assistant))
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type CoreDragDropManager = *mut ::core::ffi::c_void;
pub type CoreDragInfo = *mut ::core::ffi::c_void;
pub type CoreDragOperation = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct CoreDragUIContentMode(pub u32);
impl CoreDragUIContentMode {
pub const Auto: Self = Self(0u32);
pub const Deferred: Self = Self(1u32);
}
impl ::core::marker::Copy for CoreDragUIContentMode {}
impl ::core::clone::Clone for CoreDragUIContentMode {
fn clone(&self) -> Self {
*self
}
}
pub type CoreDragUIOverride = *mut ::core::ffi::c_void;
pub type CoreDropOperationTargetRequestedEventArgs = *mut ::core::ffi::c_void;
pub type ICoreDropOperationTarget = *mut ::core::ffi::c_void;
|
extern crate chrono;
use signal::Signal;
use self::chrono::prelude::{DateTime, Utc};
mod once;
pub use signal::detector::once::Once;
mod always;
pub use signal::detector::always::Always;
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum DetectSignalError {
IndicatorError
}
pub trait DetectSignal {
fn detect_signal(&self, datetime: &DateTime<Utc>) -> Result<Option<Signal>, DetectSignalError>;
}
|
use std::collections::HashMap;
fn main() {
let mut mem: HashMap<i32, i32> = HashMap::new();
let mut result = 0i32;
let mut count = 0i32;
loop {
count = count + 1;
let gen_fib = fib_gen(count, &mut mem);
if gen_fib % 2 == 0 {
result += gen_fib;
}
if gen_fib > 4000000 {
break;
}
}
println!("{}", result);
}
fn fib_gen(num: i32, mem: &mut HashMap<i32, i32>) -> i32 {
if num <= 1 {
return 1;
}
if let Some(val) = mem.get(&num) {
return *val;
}
let num_a = fib_gen(num - 1, mem);
let num_b = fib_gen(num - 2, mem);
mem.insert(num - 1, num_a);
mem.insert(num - 2, num_b);
return num_a + num_b;
}
|
#![feature(proc_macro_diagnostic)]
mod autodiff;
mod reader;
extern crate proc_macro;
use reader::Reader;
use autodiff::solver::Solver;
use proc_macro::TokenStream;
use quote::quote;
use syn::*;
use syn::fold::Fold;
#[proc_macro_attribute]
pub fn into_backward(attr: TokenStream, item: TokenStream) -> TokenStream {
let mut needs_grad: Vec<String> = vec!["input".to_string()];
let attribute_args = parse_macro_input!(attr as AttributeArgs);
for attribute in attribute_args {
if let NestedMeta::Meta(meta) = attribute {
if let Meta::Path(path) = meta {
let ident = path.segments.last().unwrap().ident.to_string();
needs_grad.push("self . ".to_string() + &ident);
} else {
panic!("Unsupported attribute argument, expected field name!")
}
} else {
panic!("Unsupported attribute argument, expected field name!")
}
}
let mut item_fn = parse::<ItemFn>(item).unwrap();
let mut reader = Reader::new();
item_fn = reader.fold_item_fn(item_fn);
let arg = reader.get_output_arg();
let mut solver = Solver::new();
let backwards_block = solver.solve(arg, "output_grad".parse().unwrap(), needs_grad);
let expanded = quote! {
#item_fn
fn backward(&mut self, input: Tensor, output_grad: Tensor) -> Tensor {
#backwards_block
}
};
TokenStream::from(expanded)
} |
use crate::expression::{Binary, Call, ConditionalBinary, ConditionalExpression, Expr};
/// Expression distinguishes InfluxQL [`ConditionalExpression`] or [`Expr`]
/// nodes when visiting a [`ConditionalExpression`] tree. See [`walk_expression`].
#[derive(Debug)]
pub enum Expression<'a> {
/// Specifies a conditional expression.
Conditional(&'a ConditionalExpression),
/// Specifies an arithmetic expression.
Arithmetic(&'a Expr),
}
/// ExpressionMut is the same as [`Expression`] with the exception that
/// it provides mutable access to the nodes of the tree.
#[derive(Debug)]
pub enum ExpressionMut<'a> {
/// Specifies a conditional expression.
Conditional(&'a mut ConditionalExpression),
/// Specifies an arithmetic expression.
Arithmetic(&'a mut Expr),
}
/// Perform a depth-first traversal of an expression tree.
pub fn walk_expression<'a, B>(
node: &'a ConditionalExpression,
visit: &mut impl FnMut(Expression<'a>) -> std::ops::ControlFlow<B>,
) -> std::ops::ControlFlow<B> {
match node {
ConditionalExpression::Expr(n) => walk_expr(n, &mut |n| visit(Expression::Arithmetic(n)))?,
ConditionalExpression::Binary(ConditionalBinary { lhs, rhs, .. }) => {
walk_expression(lhs, visit)?;
walk_expression(rhs, visit)?;
}
ConditionalExpression::Grouped(n) => walk_expression(n, visit)?,
}
visit(Expression::Conditional(node))
}
/// Perform a depth-first traversal of a mutable arithmetic or conditional expression tree.
pub fn walk_expression_mut<B>(
node: &mut ConditionalExpression,
visit: &mut impl FnMut(ExpressionMut<'_>) -> std::ops::ControlFlow<B>,
) -> std::ops::ControlFlow<B> {
match node {
ConditionalExpression::Expr(n) => {
walk_expr_mut(n, &mut |n| visit(ExpressionMut::Arithmetic(n)))?
}
ConditionalExpression::Binary(ConditionalBinary { lhs, rhs, .. }) => {
walk_expression_mut(lhs, visit)?;
walk_expression_mut(rhs, visit)?;
}
ConditionalExpression::Grouped(n) => walk_expression_mut(n, visit)?,
}
visit(ExpressionMut::Conditional(node))
}
/// Perform a depth-first traversal of the arithmetic expression tree.
pub fn walk_expr<'a, B>(
expr: &'a Expr,
visit: &mut impl FnMut(&'a Expr) -> std::ops::ControlFlow<B>,
) -> std::ops::ControlFlow<B> {
match expr {
Expr::Binary(Binary { lhs, rhs, .. }) => {
walk_expr(lhs, visit)?;
walk_expr(rhs, visit)?;
}
Expr::Nested(n) => walk_expr(n, visit)?,
Expr::Call(Call { args, .. }) => {
args.iter().try_for_each(|n| walk_expr(n, visit))?;
}
Expr::VarRef { .. }
| Expr::BindParameter(_)
| Expr::Literal(_)
| Expr::Wildcard(_)
| Expr::Distinct(_) => {}
}
visit(expr)
}
/// Perform a depth-first traversal of a mutable arithmetic expression tree.
pub fn walk_expr_mut<B>(
expr: &mut Expr,
visit: &mut impl FnMut(&mut Expr) -> std::ops::ControlFlow<B>,
) -> std::ops::ControlFlow<B> {
match expr {
Expr::Binary(Binary { lhs, rhs, .. }) => {
walk_expr_mut(lhs, visit)?;
walk_expr_mut(rhs, visit)?;
}
Expr::Nested(n) => walk_expr_mut(n, visit)?,
Expr::Call(Call { args, .. }) => {
args.iter_mut().try_for_each(|n| walk_expr_mut(n, visit))?;
}
Expr::VarRef { .. }
| Expr::BindParameter(_)
| Expr::Literal(_)
| Expr::Wildcard(_)
| Expr::Distinct(_) => {}
}
visit(expr)
}
#[cfg(test)]
mod test {
use crate::expression::walk::{walk_expr_mut, walk_expression_mut, ExpressionMut};
use crate::expression::{
arithmetic_expression, conditional_expression, ConditionalBinary, ConditionalExpression,
ConditionalOperator, Expr, VarRef,
};
use crate::literal::Literal;
#[test]
fn test_walk_expression() {
fn walk_expression(s: &str) -> String {
let (_, ref expr) = conditional_expression(s).unwrap();
let mut calls = Vec::new();
let mut call_no = 0;
super::walk_expression::<()>(expr, &mut |n| {
calls.push(format!("{call_no}: {n:?}"));
call_no += 1;
std::ops::ControlFlow::Continue(())
});
calls.join("\n")
}
insta::assert_display_snapshot!(walk_expression("5 + 6 = 2 + 9"));
insta::assert_display_snapshot!(walk_expression("time > now() + 1h"));
}
#[test]
fn test_walk_expression_mut_modify() {
let (_, ref mut expr) = conditional_expression("foo + bar + 5 =~ /str/").unwrap();
walk_expression_mut::<()>(expr, &mut |e| {
match e {
ExpressionMut::Arithmetic(n) => match n {
Expr::VarRef(VarRef { name, .. }) => *name = format!("c_{name}").into(),
Expr::Literal(Literal::Integer(v)) => *v *= 10,
Expr::Literal(Literal::Regex(v)) => *v = format!("c_{}", v.0).into(),
_ => {}
},
ExpressionMut::Conditional(n) => {
if let ConditionalExpression::Binary(ConditionalBinary { op, .. }) = n {
*op = ConditionalOperator::NotEqRegex
}
}
}
std::ops::ControlFlow::Continue(())
});
assert_eq!(expr.to_string(), "c_foo + c_bar + 50 !~ /c_str/")
}
#[test]
fn test_walk_expr() {
fn walk_expr(s: &str) -> String {
let (_, expr) = arithmetic_expression(s).unwrap();
let mut calls = Vec::new();
let mut call_no = 0;
super::walk_expr::<()>(&expr, &mut |n| {
calls.push(format!("{call_no}: {n:?}"));
call_no += 1;
std::ops::ControlFlow::Continue(())
});
calls.join("\n")
}
insta::assert_display_snapshot!(walk_expr("5 + 6"));
insta::assert_display_snapshot!(walk_expr("now() + 1h"));
}
#[test]
fn test_walk_expr_mut() {
fn walk_expr_mut(s: &str) -> String {
let (_, mut expr) = arithmetic_expression(s).unwrap();
let mut calls = Vec::new();
let mut call_no = 0;
super::walk_expr_mut::<()>(&mut expr, &mut |n| {
calls.push(format!("{call_no}: {n:?}"));
call_no += 1;
std::ops::ControlFlow::Continue(())
});
calls.join("\n")
}
insta::assert_display_snapshot!(walk_expr_mut("5 + 6"));
insta::assert_display_snapshot!(walk_expr_mut("now() + 1h"));
}
#[test]
fn test_walk_expr_mut_modify() {
let (_, mut expr) = arithmetic_expression("foo + bar + 5").unwrap();
walk_expr_mut::<()>(&mut expr, &mut |e| {
match e {
Expr::VarRef(VarRef { name, .. }) => *name = format!("c_{name}").into(),
Expr::Literal(Literal::Integer(v)) => *v *= 10,
_ => {}
}
std::ops::ControlFlow::Continue(())
});
assert_eq!(expr.to_string(), "c_foo + c_bar + 50")
}
}
|
mod server;
mod frame;
mod peer;
pub use server::*;
pub use frame::*;
pub use peer::*;
use std::net::{SocketAddr, Ipv4Addr};
#[derive(Debug)]
pub struct SendLANEvent {
from: SocketAddr,
src_ip: Ipv4Addr,
dst_ip: Ipv4Addr,
packet: Vec<u8>,
}
#[derive(Debug)]
pub enum Event {
Close(SocketAddr),
SendLAN(SendLANEvent),
SendClient(SocketAddr, Vec<u8>),
}
pub fn log_err<T, E>(result: std::result::Result<T, E>, msg: &str) {
if result.is_err() {
log::error!("{}", msg)
}
}
pub fn log_warn<T, E>(result: std::result::Result<T, E>, msg: &str) {
if result.is_err() {
log::warn!("{}", msg)
}
}
|
use chrono::prelude::*;
use serde_json::Value;
use morgan_client::rpc_client::RpcClient;
use morgan_tokenbot::drone::run_local_drone;
use morgan_interface::pubkey::Pubkey;
use morgan_interface::signature::KeypairUtil;
use morgan_wallet::wallet::{
process_command, request_and_confirm_airdrop, WalletCommand, WalletConfig,
};
use std::fs::remove_dir_all;
use std::sync::mpsc::channel;
#[cfg(test)]
use morgan::verifier::new_validator_for_tests;
fn check_balance(expected_balance: u64, client: &RpcClient, pubkey: &Pubkey) {
let balance = client.retry_get_balance(pubkey, 1).unwrap().unwrap();
assert_eq!(balance, expected_balance);
}
#[test]
fn test_wallet_timestamp_tx() {
let (server, leader_data, alice, ledger_path) = new_validator_for_tests();
let bob_pubkey = Pubkey::new_rand();
let (sender, receiver) = channel();
run_local_drone(alice, sender, None);
let drone_addr = receiver.recv().unwrap();
let rpc_client = RpcClient::new_socket(leader_data.rpc);
let mut config_payer = WalletConfig::default();
config_payer.drone_port = drone_addr.port();
config_payer.json_rpc_url =
format!("http://{}:{}", leader_data.rpc.ip(), leader_data.rpc.port());
let mut config_witness = WalletConfig::default();
config_witness.drone_port = config_payer.drone_port;
config_witness.json_rpc_url = config_payer.json_rpc_url.clone();
assert_ne!(
config_payer.keypair.pubkey(),
config_witness.keypair.pubkey()
);
request_and_confirm_airdrop(&rpc_client, &drone_addr, &config_payer.keypair.pubkey(), 50)
.unwrap();
check_balance(50, &rpc_client, &config_payer.keypair.pubkey());
// Make transaction (from config_payer to bob_pubkey) requiring timestamp from config_witness
let date_string = "\"2018-09-19T17:30:59Z\"";
let dt: DateTime<Utc> = serde_json::from_str(&date_string).unwrap();
config_payer.command = WalletCommand::Pay(
10,
bob_pubkey,
Some(dt),
Some(config_witness.keypair.pubkey()),
None,
None,
);
let sig_response = process_command(&config_payer);
let object: Value = serde_json::from_str(&sig_response.unwrap()).unwrap();
let process_id_str = object.get("processId").unwrap().as_str().unwrap();
let process_id_vec = bs58::decode(process_id_str)
.into_vec()
.expect("base58-encoded public key");
let process_id = Pubkey::new(&process_id_vec);
check_balance(40, &rpc_client, &config_payer.keypair.pubkey()); // config_payer balance
check_balance(10, &rpc_client, &process_id); // contract balance
check_balance(0, &rpc_client, &bob_pubkey); // recipient balance
// Sign transaction by config_witness
config_witness.command = WalletCommand::TimeElapsed(bob_pubkey, process_id, dt);
process_command(&config_witness).unwrap();
check_balance(40, &rpc_client, &config_payer.keypair.pubkey()); // config_payer balance
check_balance(0, &rpc_client, &process_id); // contract balance
check_balance(10, &rpc_client, &bob_pubkey); // recipient balance
server.close().unwrap();
remove_dir_all(ledger_path).unwrap();
}
#[test]
fn test_wallet_witness_tx() {
let (server, leader_data, alice, ledger_path) = new_validator_for_tests();
let bob_pubkey = Pubkey::new_rand();
let (sender, receiver) = channel();
run_local_drone(alice, sender, None);
let drone_addr = receiver.recv().unwrap();
let rpc_client = RpcClient::new_socket(leader_data.rpc);
let mut config_payer = WalletConfig::default();
config_payer.drone_port = drone_addr.port();
config_payer.json_rpc_url =
format!("http://{}:{}", leader_data.rpc.ip(), leader_data.rpc.port());
let mut config_witness = WalletConfig::default();
config_witness.drone_port = config_payer.drone_port;
config_witness.json_rpc_url = config_payer.json_rpc_url.clone();
assert_ne!(
config_payer.keypair.pubkey(),
config_witness.keypair.pubkey()
);
request_and_confirm_airdrop(&rpc_client, &drone_addr, &config_payer.keypair.pubkey(), 50)
.unwrap();
// Make transaction (from config_payer to bob_pubkey) requiring witness signature from config_witness
config_payer.command = WalletCommand::Pay(
10,
bob_pubkey,
None,
None,
Some(vec![config_witness.keypair.pubkey()]),
None,
);
let sig_response = process_command(&config_payer);
let object: Value = serde_json::from_str(&sig_response.unwrap()).unwrap();
let process_id_str = object.get("processId").unwrap().as_str().unwrap();
let process_id_vec = bs58::decode(process_id_str)
.into_vec()
.expect("base58-encoded public key");
let process_id = Pubkey::new(&process_id_vec);
check_balance(40, &rpc_client, &config_payer.keypair.pubkey()); // config_payer balance
check_balance(10, &rpc_client, &process_id); // contract balance
check_balance(0, &rpc_client, &bob_pubkey); // recipient balance
// Sign transaction by config_witness
config_witness.command = WalletCommand::Witness(bob_pubkey, process_id);
process_command(&config_witness).unwrap();
check_balance(40, &rpc_client, &config_payer.keypair.pubkey()); // config_payer balance
check_balance(0, &rpc_client, &process_id); // contract balance
check_balance(10, &rpc_client, &bob_pubkey); // recipient balance
server.close().unwrap();
remove_dir_all(ledger_path).unwrap();
}
#[test]
fn test_wallet_cancel_tx() {
let (server, leader_data, alice, ledger_path) = new_validator_for_tests();
let bob_pubkey = Pubkey::new_rand();
let (sender, receiver) = channel();
run_local_drone(alice, sender, None);
let drone_addr = receiver.recv().unwrap();
let rpc_client = RpcClient::new_socket(leader_data.rpc);
let mut config_payer = WalletConfig::default();
config_payer.drone_port = drone_addr.port();
config_payer.json_rpc_url =
format!("http://{}:{}", leader_data.rpc.ip(), leader_data.rpc.port());
let mut config_witness = WalletConfig::default();
config_witness.drone_port = config_payer.drone_port;
config_witness.json_rpc_url = config_payer.json_rpc_url.clone();
assert_ne!(
config_payer.keypair.pubkey(),
config_witness.keypair.pubkey()
);
request_and_confirm_airdrop(&rpc_client, &drone_addr, &config_payer.keypair.pubkey(), 50)
.unwrap();
// Make transaction (from config_payer to bob_pubkey) requiring witness signature from config_witness
config_payer.command = WalletCommand::Pay(
10,
bob_pubkey,
None,
None,
Some(vec![config_witness.keypair.pubkey()]),
Some(config_payer.keypair.pubkey()),
);
let sig_response = process_command(&config_payer).unwrap();
let object: Value = serde_json::from_str(&sig_response).unwrap();
let process_id_str = object.get("processId").unwrap().as_str().unwrap();
let process_id_vec = bs58::decode(process_id_str)
.into_vec()
.expect("base58-encoded public key");
let process_id = Pubkey::new(&process_id_vec);
check_balance(40, &rpc_client, &config_payer.keypair.pubkey()); // config_payer balance
check_balance(10, &rpc_client, &process_id); // contract balance
check_balance(0, &rpc_client, &bob_pubkey); // recipient balance
// Sign transaction by config_witness
config_payer.command = WalletCommand::Cancel(process_id);
process_command(&config_payer).unwrap();
check_balance(50, &rpc_client, &config_payer.keypair.pubkey()); // config_payer balance
check_balance(0, &rpc_client, &process_id); // contract balance
check_balance(0, &rpc_client, &bob_pubkey); // recipient balance
server.close().unwrap();
remove_dir_all(ledger_path).unwrap();
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::registry::service_context::ServiceContext,
failure::Error,
fidl::endpoints::create_request_stream,
fidl_fuchsia_ui_input::MediaButtonsEvent,
fidl_fuchsia_ui_policy::{
DeviceListenerRegistryMarker, MediaButtonsListenerMarker, MediaButtonsListenerRequest,
},
fuchsia_async as fasync,
futures::StreamExt,
parking_lot::RwLock,
std::sync::Arc,
};
/// Method for listening to media button changes. Changes will be reported back
/// on the supplied sender.
pub fn monitor_mic_mute(
service_context_handle: Arc<RwLock<ServiceContext>>,
sender: futures::channel::mpsc::UnboundedSender<MediaButtonsEvent>,
) -> Result<(), Error> {
let service_result = service_context_handle.read().connect::<DeviceListenerRegistryMarker>();
let presenter_service = match service_result {
Ok(service) => service,
Err(err) => {
return Err(err);
}
};
let (client_end, mut stream) = create_request_stream::<MediaButtonsListenerMarker>().unwrap();
presenter_service
.register_media_buttons_listener(client_end)
.expect("Could not register as listener for media buttons");
fasync::spawn(async move {
while let Some(Ok(media_request)) = stream.next().await {
// Support future expansion of FIDL
#[allow(unreachable_patterns)]
match media_request {
MediaButtonsListenerRequest::OnMediaButtonsEvent { event, control_handle: _ } => {
sender.unbounded_send(event).ok();
}
_ => {}
}
}
});
return Ok(());
}
|
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryInto;
use std::ops::Range;
use futures_core::future::BoxFuture;
use sha1::Sha1;
use crate::connection::{Connect, Connection};
use crate::executor::Executor;
use crate::mysql::protocol::{
AuthPlugin, AuthSwitch, Capabilities, ComPing, Handshake, HandshakeResponse, Quit
};
use crate::mysql::stream::MySqlStream;
use crate::mysql::util::xor_eq;
use crate::mysql::{rsa, tls};
use crate::url::Url;
// Size before a packet is split
pub(super) const MAX_PACKET_SIZE: u32 = 1024;
pub(super) const COLLATE_UTF8MB4_UNICODE_CI: u8 = 224;
/// An asynchronous connection to a [`MySql`] database.
///
/// The connection string expected by `MySqlConnection` should be a MySQL connection
/// string, as documented at
/// <https://dev.mysql.com/doc/refman/8.0/en/connecting-using-uri-or-key-value-pairs.html#connecting-using-uri>
///
/// ### TLS Support (requires `tls` feature)
/// This connection type supports some of the same flags as the `mysql` CLI application for SSL
/// connections, but they must be specified via the query segment of the connection string
/// rather than as program arguments.
///
/// The same options for `--ssl-mode` are supported as the `ssl-mode` query parameter:
/// <https://dev.mysql.com/doc/refman/8.0/en/connection-options.html#option_general_ssl-mode>
///
/// ```text
/// mysql://<user>[:<password>]@<host>[:<port>]/<database>[?ssl-mode=<ssl-mode>[&ssl-ca=<path>]]
/// ```
/// where
/// ```text
/// ssl-mode = DISABLED | PREFERRED | REQUIRED | VERIFY_CA | VERIFY_IDENTITY
/// path = percent (URL) encoded path on the local machine
/// ```
///
/// If the `tls` feature is not enabled, `ssl-mode=DISABLED` and `ssl-mode=PREFERRED` are no-ops and
/// `ssl-mode=REQUIRED`, `ssl-mode=VERIFY_CA` and `ssl-mode=VERIFY_IDENTITY` are forbidden
/// (attempting to connect with these will return an error).
///
/// If the `tls` feature is enabled, an upgrade to TLS is attempted on every connection by default
/// (equivalent to `ssl-mode=PREFERRED`). If the server does not support TLS (because `--ssl=0` was
/// passed to the server or an invalid certificate or key was used:
/// <https://dev.mysql.com/doc/refman/8.0/en/using-encrypted-connections.html>)
/// then it falls back to an unsecured connection and logs a warning.
///
/// Add `ssl-mode=REQUIRED` to your connection string to emit an error if the TLS upgrade fails.
///
/// However, like with `mysql` the server certificate is **not** checked for validity by default.
///
/// Specifying `ssl-mode=VERIFY_CA` will cause the TLS upgrade to verify the server's SSL
/// certificate against a local CA root certificate; this is not the system root certificate
/// but is instead expected to be specified as a local path with the `ssl-ca` query parameter
/// (percent-encoded so the URL remains valid).
///
/// If you're running MySQL locally it might look something like this (for `VERIFY_CA`):
/// ```text
/// mysql://root:password@localhost/my_database?ssl-mode=VERIFY_CA&ssl-ca=%2Fvar%2Flib%2Fmysql%2Fca.pem
/// ```
///
/// `%2F` is the percent-encoding for forward slash (`/`). In the example we give `/var/lib/mysql/ca.pem`
/// as the CA certificate path, which is generated by the MySQL server automatically if
/// no certificate is manually specified. Note that the path may vary based on the default `my.cnf`
/// packaged with MySQL for your Linux distribution. Also note that unlike MySQL, MariaDB does *not*
/// generate certificates automatically and they must always be passed in to enable TLS.
///
/// If `ssl-ca` is not specified or the file cannot be read, then an error is returned.
/// `ssl-ca` implies `ssl-mode=VERIFY_CA` so you only actually need to specify the former
/// but you may prefer having both to be more explicit.
///
/// If `ssl-mode=VERIFY_IDENTITY` is specified, in addition to checking the certificate as with
/// `ssl-mode=VERIFY_CA`, the hostname in the connection string will be verified
/// against the hostname in the server certificate, so they must be the same for the TLS
/// upgrade to succeed. `ssl-ca` must still be specified.
pub struct MySqlConnection {
pub(super) stream: MySqlStream,
pub(super) is_ready: bool,
pub(super) cache_statement: HashMap<Box<str>, u32>,
// Work buffer for the value ranges of the current row
// This is used as the backing memory for each Row's value indexes
pub(super) current_row_values: Vec<Option<Range<usize>>>,
}
fn to_asciz(s: &str) -> Vec<u8> {
let mut z = String::with_capacity(s.len() + 1);
z.push_str(s);
z.push('\0');
z.into_bytes()
}
async fn rsa_encrypt_with_nonce(
stream: &mut MySqlStream,
public_key_request_id: u8,
password: &str,
nonce: &[u8],
) -> crate::Result<Vec<u8>> {
// https://mariadb.com/kb/en/caching_sha2_password-authentication-plugin/
if stream.is_tls() {
// If in a TLS stream, send the password directly in clear text
return Ok(to_asciz(password));
}
// client sends a public key request
stream.send(&[public_key_request_id][..], false).await?;
// server sends a public key response
let packet = stream.receive().await?;
let rsa_pub_key = &packet[1..];
// xor the password with the given nonce
let mut pass = to_asciz(password);
xor_eq(&mut pass, nonce);
// client sends an RSA encrypted password
rsa::encrypt::<Sha1>(rsa_pub_key, &pass)
}
async fn make_auth_response(
stream: &mut MySqlStream,
plugin: &AuthPlugin,
password: &str,
nonce: &[u8],
) -> crate::Result<Vec<u8>> {
if password.is_empty() {
// Empty password should not be sent
return Ok(vec![]);
}
match plugin {
AuthPlugin::CachingSha2Password | AuthPlugin::MySqlNativePassword => {
Ok(plugin.scramble(password, nonce))
}
AuthPlugin::Sha256Password => rsa_encrypt_with_nonce(stream, 0x01, password, nonce).await,
}
}
async fn establish(stream: &mut MySqlStream, url: &Url) -> crate::Result<()> {
// https://dev.mysql.com/doc/dev/mysql-server/8.0.12/page_protocol_connection_phase.html
// https://mariadb.com/kb/en/connection/
// Read a [Handshake] packet. When connecting to the database server, this is immediately
// received from the database server.
let handshake = Handshake::read(stream.receive().await?)?;
let mut auth_plugin = handshake.auth_plugin;
let mut auth_plugin_data = handshake.auth_plugin_data;
stream.capabilities &= handshake.server_capabilities;
stream.capabilities |= Capabilities::PROTOCOL_41;
log::trace!("using capability flags: {:?}", stream.capabilities);
// Depending on the ssl-mode and capabilities we should upgrade
// our connection to TLS
tls::upgrade_if_needed(stream, url).await?;
// Send a [HandshakeResponse] packet. This is returned in response to the [Handshake] packet
// that is immediately received.
let password = &*url.password().unwrap_or_default();
let auth_response =
make_auth_response(stream, &auth_plugin, password, &auth_plugin_data).await?;
stream
.send(
HandshakeResponse {
client_collation: COLLATE_UTF8MB4_UNICODE_CI,
max_packet_size: MAX_PACKET_SIZE,
username: &url.username().unwrap_or(Cow::Borrowed("root")),
database: url.database(),
auth_plugin: &auth_plugin,
auth_response: &auth_response,
},
false,
)
.await?;
loop {
// After sending the handshake response with our assumed auth method the server
// will send OK, fail, or tell us to change auth methods
let packet = stream.receive().await?;
match packet[0] {
// OK
0x00 => {
break;
}
// ERROR
0xFF => {
return stream.handle_err();
}
// AUTH_SWITCH
0xFE => {
let auth = AuthSwitch::read(packet)?;
auth_plugin = auth.auth_plugin;
auth_plugin_data = auth.auth_plugin_data;
let auth_response =
make_auth_response(stream, &auth_plugin, password, &auth_plugin_data).await?;
stream.send(&*auth_response, false).await?;
}
0x01 if auth_plugin == AuthPlugin::CachingSha2Password => {
match packet[1] {
// AUTH_OK
0x03 => {}
// AUTH_CONTINUE
0x04 => {
// The specific password is _not_ cached on the server
// We need to send a normal RSA-encrypted password for this
let enc = rsa_encrypt_with_nonce(stream, 0x02, password, &auth_plugin_data)
.await?;
stream.send(&*enc, false).await?;
}
unk => {
return Err(protocol_err!("unexpected result from 'fast' authentication 0x{:x} when expecting OK (0x03) or CONTINUE (0x04)", unk).into());
}
}
}
_ => {
return stream.handle_unexpected();
}
}
}
Ok(())
}
async fn close(mut stream: MySqlStream) -> crate::Result<()> {
stream.send(Quit,true).await?;
stream.flush().await?;
stream.shutdown()?;
Ok(())
}
async fn ping(stream: &mut MySqlStream) -> crate::Result<()> {
stream.wait_until_ready().await?;
stream.is_ready = false;
stream.send(ComPing, true).await?;
match stream.receive().await?[0] {
0x00 | 0xFE => stream.handle_ok().map(drop),
0xFF => stream.handle_err(),
_ => stream.handle_unexpected(),
}
}
impl MySqlConnection {
pub(super) async fn new(url: std::result::Result<Url, url::ParseError>) -> crate::Result<Self> {
let url = url?;
let mut stream = MySqlStream::new(&url).await?;
establish(&mut stream, &url).await?;
let mut self_ = Self {
stream,
current_row_values: Vec::with_capacity(10),
is_ready: true,
cache_statement: HashMap::new(),
};
// After the connection is established, we initialize by configuring a few
// connection parameters
// https://mariadb.com/kb/en/sql-mode/
// PIPES_AS_CONCAT - Allows using the pipe character (ASCII 124) as string concatenation operator.
// This means that "A" || "B" can be used in place of CONCAT("A", "B").
// NO_ENGINE_SUBSTITUTION - If not set, if the available storage engine specified by a CREATE TABLE is
// not available, a warning is given and the default storage
// engine is used instead.
// NO_ZERO_DATE - Don't allow '0000-00-00'. This is invalid in Rust.
// NO_ZERO_IN_DATE - Don't allow 'YYYY-00-00'. This is invalid in Rust.
// --
// Setting the time zone allows us to assume that the output
// from a TIMESTAMP field is UTC
// --
// https://mathiasbynens.be/notes/mysql-utf8mb4
self_.execute(r#"
SET sql_mode=(SELECT CONCAT(@@sql_mode, ',PIPES_AS_CONCAT,NO_ENGINE_SUBSTITUTION,NO_ZERO_DATE,NO_ZERO_IN_DATE'));
SET time_zone = '+00:00';
SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;
"#).await?;
Ok(self_)
}
}
impl Connect for MySqlConnection {
fn connect<T>(url: T) -> BoxFuture<'static, crate::Result<MySqlConnection>>
where
T: TryInto<Url, Error = url::ParseError>,
Self: Sized,
{
Box::pin(MySqlConnection::new(url.try_into()))
}
}
impl Connection for MySqlConnection {
#[inline]
fn close(self) -> BoxFuture<'static, crate::Result<()>> {
Box::pin(close(self.stream))
}
#[inline]
fn ping(&mut self) -> BoxFuture<crate::Result<()>> {
Box::pin(ping(&mut self.stream))
}
}
|
//! Inherent implementation and trait implementations for the [`Shared`] type.
use core::fmt;
use core::marker::PhantomData;
use core::ops::Deref;
use typenum::Unsigned;
use crate::internal::Internal;
use crate::pointer::{Marked, MarkedNonNull, MarkedNonNullable, MarkedPointer};
use crate::{Reclaim, Shared, Unprotected};
/********** impl Clone ****************************************************************************/
impl<'g, T, R, N> Clone for Shared<'g, T, N, R> {
#[inline]
fn clone(&self) -> Self {
Self { inner: self.inner, _marker: PhantomData }
}
}
/********** impl Copy *****************************************************************************/
impl<'g, T, R, N> Copy for Shared<'g, T, R, N> {}
/********** impl MarkedPointer ********************************************************************/
impl<'g, T, R: Reclaim, N: Unsigned> MarkedPointer for Shared<'g, T, R, N> {
impl_trait!(shared);
}
/********** impl inherent *************************************************************************/
impl<'g, T, R: Reclaim, N: Unsigned> Shared<'g, T, R, N> {
impl_inherent!(shared);
/// Decomposes the marked reference, returning the reference itself and the
/// separated tag.
#[inline]
pub fn decompose_ref(shared: Self) -> (&'g T, usize) {
let (ptr, tag) = shared.inner.decompose();
unsafe { (&*ptr.as_ptr(), tag) }
}
/// Consumes and decomposes the marked reference, returning only the
/// reference itself.
///
/// # Example
///
/// Derefencing a [`Shared`] through the [`Deref`] implementation ties the
/// returned reference to the shorter lifetime of the `shared` itself.
/// Use this function to get a reference with the full lifetime `'g`.
///
/// ```
/// use core::sync::atomic::Ordering::Relaxed;
///
/// use reclaim::prelude::*;
/// use reclaim::typenum::U0;
/// use reclaim::leak::Shared;
///
/// type Atomic<T> = reclaim::leak::Atomic<T, U0>;
/// type Guard = reclaim::leak::Guard;
///
/// let atomic = Atomic::new("string");
///
/// let mut guard = Guard::new();
/// let shared = atomic.load(Relaxed, &mut guard);
///
/// let reference = Shared::into_ref(shared.unwrap());
/// assert_eq!(reference, &"string");
/// ```
#[inline]
pub fn into_ref(shared: Self) -> &'g T {
unsafe { &*shared.inner.decompose_ptr() }
}
/// Converts the `Shared` reference into an [`Unprotected`].
#[inline]
pub fn into_unprotected(shared: Self) -> Unprotected<T, R, N> {
Unprotected { inner: shared.inner, _marker: PhantomData }
}
/// Casts the [`Shared`] to a reference to a different type and with a different lifetime.
///
/// This can be useful to extend the lifetime of a [`Shared`] in cases the borrow checker is
/// unable to correctly determine the relationship between mutable borrows of guards and the
/// resulting shared references.
///
/// # Safety
///
/// The caller has to ensure the cast is valid both in terms of type and lifetime.
#[inline]
pub unsafe fn cast<'h, U>(shared: Self) -> Shared<'h, U, R, N> {
Shared { inner: shared.inner.cast(), _marker: PhantomData }
}
}
/********** impl AsRef ****************************************************************************/
impl<'g, T, R: Reclaim, N: Unsigned> AsRef<T> for Shared<'g, T, R, N> {
#[inline]
fn as_ref(&self) -> &T {
unsafe { self.inner.as_ref() }
}
}
/********** impl Deref ****************************************************************************/
impl<'g, T, R: Reclaim, N: Unsigned> Deref for Shared<'g, T, R, N> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { self.inner.as_ref() }
}
}
/********** impl Debug ****************************************************************************/
impl<'g, T, R: Reclaim, N: Unsigned> fmt::Debug for Shared<'g, T, R, N> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (ptr, tag) = self.inner.decompose();
f.debug_struct("Shared").field("ptr", &ptr).field("tag", &tag).finish()
}
}
/********** impl Pointer **************************************************************************/
impl<'g, T, R: Reclaim, N: Unsigned> fmt::Pointer for Shared<'g, T, R, N> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Pointer::fmt(&self.inner.decompose_ptr(), f)
}
}
/********** impl NonNullable **********************************************************************/
impl<'g, T, R, N: Unsigned> MarkedNonNullable for Shared<'g, T, R, N> {
type Item = T;
type MarkBits = N;
#[inline]
fn into_marked_non_null(self) -> MarkedNonNull<Self::Item, Self::MarkBits> {
self.inner
}
}
/********** impl Internal *************************************************************************/
impl<'g, T, R, N> Internal for Shared<'g, T, R, N> {}
|
use super::MotorPort;
use crate::{wait, Attribute, Device, Driver, Ev3Error, Ev3Result};
use std::time::Duration;
/// EV3 medium servo motor
#[derive(Debug, Clone, Device)]
pub struct MediumMotor {
driver: Driver,
}
impl MediumMotor {
fn new(driver: Driver) -> Self {
Self { driver }
}
findable!(
"tacho-motor",
["lego-ev3-m-motor"],
MotorPort,
"MediumMotor",
"out"
);
tacho_motor!();
}
|
use hmac::{Hmac, Mac};
use rand::Rng;
use sha2::{Digest, Sha256};
use crate::postgres::protocol::{
hi, Authentication, AuthenticationSaslContinue, Message, SaslInitialResponse, SaslResponse,
};
use crate::postgres::stream::PgStream;
static GS2_HEADER: &'static str = "n,,";
static CHANNEL_ATTR: &'static str = "c";
static USERNAME_ATTR: &'static str = "n";
static CLIENT_PROOF_ATTR: &'static str = "p";
static NONCE_ATTR: &'static str = "r";
// Nonce generator
// Nonce is a sequence of random printable bytes
fn nonce() -> String {
let mut rng = rand::thread_rng();
let count = rng.gen_range(64, 128);
// printable = %x21-2B / %x2D-7E
// ;; Printable ASCII except ",".
// ;; Note that any "printable" is also
// ;; a valid "value".
let nonce: String = std::iter::repeat(())
.map(|()| {
let mut c = rng.gen_range(0x21, 0x7F) as u8;
while c == 0x2C {
c = rng.gen_range(0x21, 0x7F) as u8;
}
c
})
.take(count)
.map(|c| c as char)
.collect();
rng.gen_range(32, 128);
format!("{}={}", NONCE_ATTR, nonce)
}
// Performs authenticiton using Simple Authentication Security Layer (SASL) which is what
// Postgres uses
pub(super) async fn authenticate<T: AsRef<str>>(
stream: &mut PgStream,
username: T,
password: T,
) -> crate::Result<()> {
// channel-binding = "c=" base64
let channel_binding = format!("{}={}", CHANNEL_ATTR, base64::encode(GS2_HEADER));
// "n=" saslname ;; Usernames are prepared using SASLprep.
let username = format!("{}={}", USERNAME_ATTR, username.as_ref());
// nonce = "r=" c-nonce [s-nonce] ;; Second part provided by server.
let nonce = nonce();
let client_first_message_bare =
format!("{username},{nonce}", username = username, nonce = nonce);
// client-first-message-bare = [reserved-mext ","] username "," nonce ["," extensions]
let client_first_message = format!(
"{gs2_header}{client_first_message_bare}",
gs2_header = GS2_HEADER,
client_first_message_bare = client_first_message_bare
);
stream.write(SaslInitialResponse(&client_first_message));
stream.flush().await?;
let server_first_message = stream.receive().await?;
if let Message::Authentication = server_first_message {
let auth = Authentication::read(stream.buffer())?;
if let Authentication::SaslContinue = auth {
// todo: better way to indicate that we consumed just these 4 bytes?
let sasl = AuthenticationSaslContinue::read(&stream.buffer()[4..])?;
let server_first_message = sasl.data;
// SaltedPassword := Hi(Normalize(password), salt, i)
let salted_password = hi(password.as_ref(), &sasl.salt, sasl.iter_count)?;
// ClientKey := HMAC(SaltedPassword, "Client Key")
let mut mac = Hmac::<Sha256>::new_varkey(&salted_password)
.map_err(|_| protocol_err!("HMAC can take key of any size"))?;
mac.input(b"Client Key");
let client_key = mac.result().code();
// StoredKey := H(ClientKey)
let mut hasher = Sha256::new();
hasher.input(client_key);
let stored_key = hasher.result();
// String::from_utf8_lossy should never fail because Postgres requires
// the nonce to be all printable characters except ','
let client_final_message_wo_proof = format!(
"{channel_binding},r={nonce}",
channel_binding = channel_binding,
nonce = String::from_utf8_lossy(&sasl.nonce)
);
// AuthMessage := client-first-message-bare + "," + server-first-message + "," + client-final-message-without-proof
let auth_message = format!("{client_first_message_bare},{server_first_message},{client_final_message_wo_proof}",
client_first_message_bare = client_first_message_bare,
server_first_message = server_first_message,
client_final_message_wo_proof = client_final_message_wo_proof);
// ClientSignature := HMAC(StoredKey, AuthMessage)
let mut mac =
Hmac::<Sha256>::new_varkey(&stored_key).expect("HMAC can take key of any size");
mac.input(&auth_message.as_bytes());
let client_signature = mac.result().code();
// ClientProof := ClientKey XOR ClientSignature
let client_proof: Vec<u8> = client_key
.iter()
.zip(client_signature.iter())
.map(|(&a, &b)| a ^ b)
.collect();
// ServerKey := HMAC(SaltedPassword, "Server Key")
let mut mac = Hmac::<Sha256>::new_varkey(&salted_password)
.map_err(|_| protocol_err!("HMAC can take key of any size"))?;
mac.input(b"Server Key");
let server_key = mac.result().code();
// ServerSignature := HMAC(ServerKey, AuthMessage)
let mut mac =
Hmac::<Sha256>::new_varkey(&server_key).expect("HMAC can take key of any size");
mac.input(&auth_message.as_bytes());
let _server_signature = mac.result().code();
// client-final-message = client-final-message-without-proof "," proof
let client_final_message = format!(
"{client_final_message_wo_proof},{client_proof_attr}={client_proof}",
client_final_message_wo_proof = client_final_message_wo_proof,
client_proof_attr = CLIENT_PROOF_ATTR,
client_proof = base64::encode(&client_proof)
);
stream.write(SaslResponse(&client_final_message));
stream.flush().await?;
let _server_final_response = stream.receive().await?;
// todo: assert that this was SaslFinal?
Ok(())
} else {
Err(protocol_err!(
"Expected Authentication::SaslContinue, but received {:?}",
auth
))?
}
} else {
Err(protocol_err!(
"Expected Message::Authentication, but received {:?}",
server_first_message
))?
}
}
|
use crate::shared::Parameters;
pub fn parameters(field: &syn::Field, attr_id: &'static str) -> (Vec<syn::Ident>, Vec<syn::Expr>) {
let member = match field.ident.as_ref() {
Some(m) => m,
None => unreachable!()
};
let nwg_control = |attr: &&syn::Attribute| {
attr.path.get_ident()
.map(|id| id == attr_id )
.unwrap_or(false)
};
let attr = match field.attrs.iter().find(nwg_control) {
Some(attr) => attr,
None => unreachable!()
};
let ctrl: Parameters = match syn::parse2(attr.tokens.clone()) {
Ok(a) => a,
Err(e) => panic!("Failed to parse field #{}: {}", member, e)
};
let params = ctrl.params;
let mut names = Vec::with_capacity(params.len());
let mut exprs = Vec::with_capacity(params.len());
for p in params {
if p.ident == "ty" {
continue;
}
names.push(p.ident);
exprs.push(p.e);
}
(names, exprs)
}
pub fn expand_flags(member_name: &syn::Ident, ty: &syn::Ident, flags: syn::Expr) -> syn::Expr {
let flags_type = format!("{}Flags", ty);
let flags_value = match &flags {
syn::Expr::Lit(expr_lit) => match &expr_lit.lit {
syn::Lit::Str(value) => value,
other => panic!("Compressed flags must str, got {:?} for control {}", other, member_name)
},
other => panic!("Compressed flags must str, got {:?} for control {}", other, member_name)
};
let flags = flags_value.value();
let splitted: Vec<&str> = flags.split('|').collect();
let flags_count = splitted.len() - 1;
let mut final_flags: String = String::with_capacity(100);
for (i, value) in splitted.into_iter().enumerate() {
final_flags.push_str(&flags_type);
final_flags.push_str("::");
final_flags.push_str(value);
if i != flags_count {
final_flags.push('|');
}
}
match syn::parse_str(&final_flags) {
Ok(e) => e,
Err(e) => panic!("Failed to parse flags value for control {}: {}", member_name, e)
}
}
|
use fileutil;
fn increasing_windows(window_size: usize) {
let depths: Vec<i32> = fileutil::read_lines("data/2021/01.txt")
.unwrap()
.iter()
.map(|s| s.parse::<i32>().unwrap())
.collect();
let mut num_larger = 0;
let mut last_sum: Option<i32> = None;
for window in depths.windows(window_size) {
let window_sum: i32 = window.iter().sum();
num_larger += match last_sum {
Some(last_sum_num) if last_sum_num < window_sum => 1,
_ => 0
};
last_sum = Some(window_sum);
}
println!("{}", num_larger);
}
pub fn run() {
// Part1
// increasing_windows(1);
// Part 2
increasing_windows(3);
} |
#![cfg(unix)]
extern crate bytes;
extern crate futures;
extern crate tempfile;
extern crate tokio;
extern crate tokio_codec;
extern crate tokio_uds;
use tokio_uds::*;
use std::str;
use bytes::BytesMut;
use tokio::io;
use tokio::runtime::current_thread::Runtime;
use tokio_codec::{Decoder, Encoder};
use futures::{Future, Sink, Stream};
struct StringDatagramCodec;
/// A codec to decode datagrams from a unix domain socket as utf-8 text messages.
impl Encoder for StringDatagramCodec {
type Item = String;
type Error = io::Error;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
dst.extend_from_slice(&item.into_bytes());
Ok(())
}
}
/// A codec to decode datagrams from a unix domain socket as utf-8 text messages.
impl Decoder for StringDatagramCodec {
type Item = String;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let decoded = str::from_utf8(buf)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
.to_string();
Ok(Some(decoded))
}
}
#[test]
fn framed_echo() {
let dir = tempfile::tempdir().unwrap();
let server_path = dir.path().join("server.sock");
let client_path = dir.path().join("client.sock");
let mut rt = Runtime::new().unwrap();
{
let socket = UnixDatagram::bind(&server_path).unwrap();
let server = UnixDatagramFramed::new(socket, StringDatagramCodec);
let (sink, stream) = server.split();
let echo_stream = stream.map(|(msg, addr)| (msg, addr.as_pathname().unwrap().to_path_buf()));
// spawn echo server
rt.spawn(echo_stream.forward(sink)
.map_err(|e| panic!("err={:?}", e))
.map(|_| ()));
}
{
let socket = UnixDatagram::bind(&client_path).unwrap();
let client = UnixDatagramFramed::new(socket, StringDatagramCodec);
let (sink, stream) = client.split();
rt.block_on(sink.send(("ECHO".to_string(), server_path))).unwrap();
let response = rt.block_on(stream.take(1).collect()).unwrap();
assert_eq!(response[0].0, "ECHO");
}
}
|
use anyhow::Result;
use clap::{App, AppSettings, Arg, SubCommand};
mod cmd;
mod config;
mod err;
mod git;
mod util;
fn main() {
let matches = App::new("tittle")
.version("0.2.0")
.author("Enrico Z. Borba <enricozb@gmail.com>")
.about("Dotfile manager")
.setting(AppSettings::VersionlessSubcommands)
.arg(
Arg::with_name("verbose")
.short("v")
.long("verbose")
.help("Print commands as they are run"),
)
.subcommand(
SubCommand::with_name("clone")
.about(
"Clone a dotfile repository. This cannot be run if any local dotfile \
repo already exists.",
)
.arg(
Arg::with_name("URL")
.help("The upstream repo url")
.required(true)
.index(1),
),
)
.subcommand(
SubCommand::with_name("diff").about(
"Show diffs between remote and local dotfiles. Uses colordiff if available",
),
)
.subcommand(
SubCommand::with_name("edit")
.about("Edit the tittle config")
.arg(
Arg::with_name("MODE")
.help("One of [me]. Specifies which portion of the config to edit.")
.index(1),
),
)
.subcommand(SubCommand::with_name("pull").about("Pulls the repository from upstream"))
.subcommand(
SubCommand::with_name("push").about("Pushes the current repository upstream"),
)
.subcommand(
SubCommand::with_name("remove").about("Remove tracked files or directories"),
)
.subcommand(
SubCommand::with_name("render")
.about("Render templates to their respective locations"),
)
.subcommand(
SubCommand::with_name("repo")
.about("Sets the upstream dotfile repo")
.arg(
Arg::with_name("URL")
.help("The upstream repo url")
.required(true)
.index(1),
),
)
.subcommand(
SubCommand::with_name("sync").about("Sync between remote and local dotfiles"),
)
.subcommand(
SubCommand::with_name("track")
.about("Track a file or directory")
.arg(
Arg::with_name("name")
.short("n")
.long("name")
.value_name("NAME")
.help("Sets a custom name for the tracked path"),
)
.arg(
Arg::with_name("renders_to")
.short("t")
.long("renders_to")
.value_name("PATH")
.help("If set, then the tracked file is a template and renders to this path"),
)
.arg(
Arg::with_name("PATH")
.help("The path to track")
.required(true)
.index(1),
),
)
.subcommand(SubCommand::with_name("tree").about("Show a tree of the tracked files"))
.get_matches();
let run = || -> Result<()> {
// when cloning, don't initialize config and git first
if let ("clone", Some(matches)) = matches.subcommand() {
git::clone(matches.value_of("URL").unwrap())?;
return Ok(());
}
config::init()?;
git::init()?;
match matches.subcommand() {
("diff", _) => cmd::diff::diff()?,
("edit", Some(matches)) => cmd::edit::edit(matches.value_of("MODE"))?,
("pull", _) => git::pull()?,
("push", _) => git::push()?,
("remove", _) => cmd::remove::remove()?,
("render", _) => cmd::render::render()?,
("repo", Some(matches)) => git::set_remote(matches.value_of("URL").unwrap())?,
("sync", _) => cmd::sync::sync()?,
("track", Some(matches)) => cmd::track::track(
matches.value_of("PATH").unwrap(),
matches.value_of("name"),
matches.value_of("renders_to"),
)?,
("tree", _) => cmd::tree::tree()?,
_ => {}
}
Ok(())
};
if let Err(err) = run() {
util::error(err);
}
}
|
use sycamore::prelude::*;
static PAGES: &[(&str, &[(&str, &str)])] = &[
(
"Getting Started",
&[
("Installation", "getting_started/installation"),
("Hello World!", "getting_started/hello_world"),
],
),
(
"Basics",
&[
("template!", "basics/template"),
("Reactivity", "basics/reactivity"),
("Components", "basics/components"),
("Control Flow", "basics/control_flow"),
("Iteration", "basics/iteration"),
("Data Binding", "basics/data_binding"),
],
),
(
"Advanced Guides",
&[
("NodeRef", "advanced/noderef"),
("Tweened", "advanced/tweened"),
("Advanced Reactivity", "advanced/advanced_reactivity"),
("CSS", "advanced/css"),
("Testing", "advanced/testing"),
("Routing", "advanced/routing"),
("SSR", "advanced/ssr"),
("JS Interop", "advanced/js_interop"),
],
),
(
"Optimizations",
&[
("Code Size", "optimizations/code_size"),
("Speed", "optimizations/speed"),
],
),
(
"Contribute",
&[
("Architecture", "contribute/architecture"),
("Development", "contribute/development"),
],
),
];
#[component(Sidebar<G>)]
pub fn sidebar(version: String) -> Template<G> {
let sections = PAGES
.iter()
.map(|section| {
let pages = section
.1
.iter()
.map(|page| {
template! {
li {
a(
href=format!("../{}", page.1),
class="pl-4 hover:bg-gray-300 w-full inline-block rounded transition",
) {
(page.0)
}
}
}
})
.collect();
let pages = Template::new_fragment(pages);
template! {
li {
h1(class="text-lg font-bold py-1 pl-2") {
(section.0)
}
ul(class="text-gray-700") {
(pages)
}
}
}
})
.collect();
let sections = Template::new_fragment(sections);
template! {
aside(class="p-3 bg-white w-44") {
ul(class="text-black") {
li {
a(
href="/versions",
class="pl-4 font-bold text-gray-700 hover:bg-gray-300 w-full inline-block rounded transition",
) {
"Version: " (version)
}
}
(sections)
}
}
}
}
|
use presentation::prelude::*;
use std::sync::{Arc, Mutex};
#[derive(Debug)]
pub struct VulkanCore {
device: Arc<Device>,
queue: Arc<Mutex<Queue>>,
}
impl VulkanCore {
pub fn new(
presentation_core: &PresentationCore,
vulkan_debug_info: &VulkanDebugInfo,
app_info: &ApplicationInfo,
device_features: DeviceFeatures,
) -> VerboseResult<VulkanCore> {
// --- create instance ---
// application info
let app_name = VkString::new(&app_info.application_name);
let engine_name = VkString::new(&app_info.engine_name);
let info = VkApplicationInfo::new(
&app_name,
app_info.application_version,
&engine_name,
app_info.engine_version,
VK_MAKE_VERSION(1, 1, 0),
);
// instance extensions
let mut instance_extensions = InstanceExtensions::default();
presentation_core.activate_vulkan_instance_extensions(&mut instance_extensions)?;
instance_extensions.physical_device_properties2 = true;
// create instance
let instance = Instance::new(info, *vulkan_debug_info, instance_extensions)?;
let (queue_info, physical_device) = match presentation_core.backend() {
PresentationBackend::Window(wsi) => {
wsi.create_vulkan_surface(&instance)?;
// create physical device
let physical_device = PhysicalDevice::new(instance.clone())?;
let queue_info = Queue::create_presentable_request_info(
&physical_device,
&wsi.surface()?,
VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
)?;
(queue_info, physical_device)
}
PresentationBackend::OpenXR(xri) => {
let physical_device =
PhysicalDevice::from_raw(instance.clone(), xri.physical_device(&instance)?)?;
let queue_info = Queue::create_non_presentable_request_info(
&physical_device,
VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
)?;
(queue_info, physical_device)
}
PresentationBackend::OpenVR(vri) => {
// Check if OpenVR can find an appropriate PhysicalDevice,
// otherwise fallback with using default routine
let physical_device = match vri.physical_device(&instance) {
Some(physical_device_handle) => {
PhysicalDevice::from_raw(instance.clone(), physical_device_handle)?
}
None => PhysicalDevice::new(instance.clone())?,
};
let queue_info = Queue::create_non_presentable_request_info(
&physical_device,
VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
)?;
(queue_info, physical_device)
}
};
// device extensions
let mut dev_exts = DeviceExtensions::default();
presentation_core.activate_vulkan_device_extensions(&mut dev_exts, &physical_device)?;
dev_exts.memory_requirements2 = true;
dev_exts.nv_ray_tracing = true;
dev_exts.amd_rasterization_order = true;
dev_exts.descriptor_indexing = true;
dev_exts.maintenance3 = true;
if vulkan_debug_info.renderdoc {
dev_exts.debug_marker = true;
}
let device = Device::new(
physical_device,
dev_exts,
&[queue_info.queue_create_info],
device_features,
)?;
let queue = Device::get_queue(
&device,
queue_info.queue_family_index,
queue_info.queue_index,
);
Ok(VulkanCore { device, queue })
}
pub fn device(&self) -> &Arc<Device> {
&self.device
}
pub fn queue(&self) -> &Arc<Mutex<Queue>> {
&self.queue
}
}
|
#[allow(dead_code)]
fn part_one() {
fn get() -> (i64, Vec<i64>) {
let mut lines = include_str!("../input.txt").lines();
(
lines.next().unwrap().parse().unwrap(),
lines
.next()
.unwrap()
.split(',')
.filter(|&ss| ss != "x")
.map(|ss| ss.parse().unwrap())
.collect(),
)
}
let (earliest, buses) = get();
let mut departure_bus: Vec<(i64, i64)> = Vec::new();
for bus in buses {
let mut i = 0;
while i < earliest * 2 {
departure_bus.push((i, bus));
i += bus;
}
}
departure_bus.sort_unstable();
let i = departure_bus.binary_search(&(earliest, -1)).unwrap_err();
dbg!(departure_bus[i]);
dbg!(departure_bus[i].1 * (departure_bus[i].0 - earliest));
}
fn part_two() {
fn get() -> Vec<u64> {
include_str!("../input.txt")
.lines()
.nth(1)
.unwrap()
.split(',')
.map(|ss| if ss == "x" { "0" } else { ss })
.map(|ss| ss.parse().unwrap())
.collect()
}
let buses = get();
// dbg!(buses
// .iter()
// .cloned()
// .enumerate()
// .collect::<Vec::<(usize, u64)>>());
let mut i = 937u64;
loop {
let cond = buses.iter().enumerate().all(|(n, &bus)| {
//
if bus == 0 {
true
} else {
(i + ((n) as u64) - 16) % bus == 0
}
});
if cond {
dbg!(i);
break;
}
// i += first_bus;
// i += 937;
i += 937;
}
}
fn main() {
// part_one()
part_two();
}
|
// # The Rust Programing Language
//
// ### Chapter 8.3 Challenge
//
// Given a list of integers, use a vector and return the mean (the average
// value), median (when sorted, the value in the middle position), and mode
// (the value that occurs most often; a hash map will be helpful here) of
// the list.
//
// [Source](https://doc.rust-lang.org/book/ch08-03-hash-maps.html)
//
use std::collections::HashMap;
use std::io::{self, Write};
// A statistical mode — while typically a single value — can also either be
// not present at all (all values appear equally as often) or multimodal (
// two or more values appear as often as each other and more often than at
// least one other value).
//
#[derive(Debug)]
enum Mode {
None,
Single(i32),
Multiple(Vec<i32>),
}
#[derive(Debug)]
struct Statistics {
mean: f32,
median: f32,
mode: Mode,
}
fn main() {
println!("This program will calculate the mean, median and mode of several integers.");
let integers = prompt_user_for_integers();
if !integers.is_empty() {
let stats = calculate_stats(&integers);
println!("{:#?}", stats);
}
}
// Prompts a user to enter a list of integers from which we can calculate
// the statistical mean, median and mode (if present).
fn prompt_user_for_integers() -> Vec<i32> {
let mut v = Vec::new();
loop {
print!("Enter an integer (or ENTER when done): > ");
let _ = io::stdout().flush();
let mut entry = String::new();
io::stdin()
.read_line(&mut entry)
.expect("Failed to read line");
if entry.trim().is_empty() {
break v;
}
let val: i32 = match entry.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please enter a valid integer");
continue;
}
};
v.push(val);
}
}
fn calculate_stats(integers: &[i32]) -> Statistics {
Statistics {
mean: calculate_mean(integers),
median: calculate_median(integers),
mode: calculate_mode(integers),
}
}
// Determine the mean for a list of integers.
fn calculate_mean(integers: &[i32]) -> f32 {
integers.iter().sum::<i32>() as f32 / integers.len() as f32
}
// Determine the statistical median for a list of integers.
fn calculate_median(integers: &[i32]) -> f32 {
let mid_point = integers.len() / 2;
let mut sorted_integers = vec![0 as i32; integers.len()];
sorted_integers.copy_from_slice(integers);
sorted_integers.sort();
match integers.len() {
0 => 0.0,
_ => match integers.len() % 2 {
0 => (sorted_integers[mid_point] + sorted_integers[mid_point - 1]) as f32 / 2.0,
_ => sorted_integers[mid_point] as f32,
},
}
}
// Determine the statistical mode for a list of integers.
// This function correctly handles the case of no mode, single mode or multi-modes.
fn calculate_mode(integers: &[i32]) -> Mode {
match integers.len() {
0 => Mode::None,
1 => Mode::None,
_ => {
// Count the number of times each integer appears
let mut map = HashMap::new();
for i in integers {
*map.entry(i.to_string()).or_insert(0) += 1;
}
let mut sorted_key_vals: Vec<(&String, &i32)> = map.iter().collect();
// Sort a vector of (key, val) by the number of times each key appeared
sorted_key_vals.sort_by(|a, b| a.1.cmp(b.1));
let max_count = sorted_key_vals[sorted_key_vals.len() - 1].1;
let min_count = sorted_key_vals[0].1;
if min_count == max_count {
// If the first and last keys had the same count in our sorted array, then
// all keys had the same count and we therefore no mode.
Mode::None
} else {
// We definately have a mode, but we must now determine if our vector
// of integers is multimodal or has only a single mode.
let accumulator: Vec<i32> = Vec::new();
let modes = map.iter().filter(|(_, count)| *count == max_count).fold(
accumulator,
|mut acc, (key, _)| {
acc.push(key.parse().expect("int -> string -> int cannot fail"));
acc
},
);
if modes.len() == 1 {
Mode::Single(modes[0])
} else {
Mode::Multiple(modes)
}
}
}
}
}
|
use charter::chart::{HorizontalBarChart, BarData};
fn main() {
let mut hbc = HorizontalBarChart::new(false);
hbc.push(BarData("three".to_string(), 3));
hbc.push(BarData("five".to_string(), 5));
hbc.push(BarData("fifteen".to_string(), 15));
hbc.width = 20;
hbc.character = '=';
println!("{}", hbc.plot_bar_labels().join("\n"));
} |
use std::fmt;
use std::io::{self, Read, Seek, SeekFrom};
use std::mem::size_of;
use std::path::PathBuf;
use std::sync::Mutex;
use byteorder::NetworkEndian;
use bytes::Bytes;
use dashmap::mapref::entry::Entry as DashMapEntry;
use dashmap::DashMap;
use fs_err::File;
use smallvec::SmallVec;
use thiserror::Error;
use zerocopy::byteorder::U32;
use zerocopy::FromBytes;
use crate::object::database::packed::delta::{apply_delta, DeltaError};
use crate::object::database::packed::index::{FindIndexOffsetError, IndexFile};
use crate::object::database::ObjectReader;
use crate::object::{Id, ObjectHeader, ObjectKind, ParseObjectError, ShortId, ID_LEN};
use crate::parse;
pub(in crate::object::database::packed) struct PackFile {
id: Id,
file: Mutex<parse::Buffer<File>>,
cache: DashMap<u64, (ObjectHeader, Bytes)>,
version: PackFileVersion,
count: u32,
}
#[derive(Debug, Error)]
pub(in crate::object::database::packed) enum ReadPackFileError {
#[error("the signature of the pack file is invalid")]
InvalidSignature,
#[error("cannot parse a pack file with version `{0}`")]
UnknownVersion(u32),
#[error("cannot parse object type `{0}`")]
UnknownType(u8),
#[error("error finding base object offset in pack index file")]
FindIndexOffset(
#[from]
#[source]
FindIndexOffsetError,
),
#[error("a base object is invalid")]
ParseObjectError(
#[from]
#[source]
ParseObjectError,
),
#[error("failed to apply a delta")]
ParseDeltaError(
#[from]
#[source]
DeltaError,
),
#[error("{0}")]
Other(&'static str),
#[error(transparent)]
Parse(#[from] parse::Error),
#[error("io error reading pack index file")]
Io(
#[from]
#[source]
io::Error,
),
}
#[derive(Debug)]
enum PackFileVersion {
V2,
V3,
}
#[repr(C)]
#[derive(Copy, Clone, Debug, FromBytes)]
struct PackFileHeader {
signature: U32<NetworkEndian>,
version: U32<NetworkEndian>,
count: U32<NetworkEndian>,
}
type Chain = SmallVec<[ChainEntry; 16]>;
#[derive(Debug)]
struct ChainEntry {
// The offset of the object header (used as its key in the cache)
key: u64,
// The offset of the object data, following the header
offset: u64,
header: ObjectHeader,
}
impl PackFile {
const SIGNATURE: u32 = u32::from_be_bytes(*b"PACK");
pub fn open(path: PathBuf) -> Result<Self, ReadPackFileError> {
let mut file = Mutex::new(parse::Buffer::with_capacity(File::open(path)?, ID_LEN));
let buffer = file.get_mut().unwrap();
let header = buffer.read_pack_file_header()?;
if header.signature.get() != PackFile::SIGNATURE {
return Err(ReadPackFileError::InvalidSignature);
}
let version = match header.version.get() {
2 => PackFileVersion::V2,
3 => PackFileVersion::V3,
n => return Err(ReadPackFileError::UnknownVersion(n)),
};
buffer.seek(SeekFrom::End(-(ID_LEN as i64)))?;
let id = buffer.read_id()?;
Ok(PackFile {
version,
cache: DashMap::new(),
count: header.count.get(),
file,
id,
})
}
pub fn read_object(
&self,
index: &IndexFile,
offset: u64,
) -> Result<ObjectReader, ReadPackFileError> {
let (chain, mut header, mut base) = self.find_chain(index, offset)?;
for entry in chain {
let (new_header, new_base) = self.apply_delta(base, entry)?;
header = new_header;
base = new_base;
}
Ok(ObjectReader::from_bytes(header, base))
}
pub fn count(&self) -> u32 {
self.count
}
fn find_chain(
&self,
index: &IndexFile,
mut offset: u64,
) -> Result<(Chain, ObjectHeader, Bytes), ReadPackFileError> {
let mut chain = Chain::new();
let mut buffer = self.file.lock().unwrap();
loop {
let cache_entry = match self.cache.entry(offset) {
DashMapEntry::Occupied(entry) => {
return Ok((chain, entry.get().0, entry.get().1.clone()))
}
DashMapEntry::Vacant(entry) => entry,
};
buffer.seek(SeekFrom::Start(offset))?;
let header = buffer.read_pack_object_header()?;
let base_offset = match header.kind {
ObjectKind::OfsDelta => {
let delta_offset = buffer.read_delta_offset()?;
offset
.checked_sub(delta_offset)
.ok_or(ReadPackFileError::Other("invalid delta offset"))?
}
ObjectKind::RefDelta => {
let id = buffer.read_delta_reference()?;
let (offset, _) = index.find_offset(&ShortId::from(id))?;
offset
}
_ => {
let base = buffer.read_exact(header.len)?;
let base = buffer.take_buffer(base);
cache_entry.insert((header, base.clone()));
return Ok((chain, header, base));
}
};
chain.push(ChainEntry {
key: offset,
offset: offset + buffer.pos() as u64,
header,
});
if base_offset == offset {
return Err(ReadPackFileError::Other("loop in deltas"));
}
offset = base_offset;
}
}
fn apply_delta(
&self,
base: Bytes,
delta: ChainEntry,
) -> Result<(ObjectHeader, Bytes), ReadPackFileError> {
let mut buffer = self.file.lock().unwrap();
buffer.seek(SeekFrom::Start(delta.offset))?;
let result = apply_delta(delta.header.kind, &base, &mut buffer.decompress_exact(delta.header.len))?;
Ok(self
.cache
.insert(delta.key, result.clone())
.unwrap_or(result))
}
pub fn id(&self) -> Id {
self.id
}
}
impl PackFileHeader {
const LEN: usize = size_of::<PackFileHeader>();
}
impl ObjectHeader {
const MAX_PACKED_LEN: usize = 1 + (size_of::<usize>() * 8 - 4) / 7 + 1;
const MAX_DELTA_OFFSET_LEN: usize = (size_of::<u64>() * 8) / 7 + 1;
}
impl<R: Read> parse::Buffer<R> {
fn read_pack_file_header(&mut self) -> Result<PackFileHeader, ReadPackFileError> {
let range = self.read_exact(PackFileHeader::LEN)?;
let mut parser = self.parser(range);
Ok(*parser.parse_struct::<PackFileHeader>()?)
}
fn read_pack_object_header(&mut self) -> Result<ObjectHeader, ReadPackFileError> {
let range = self
.read_until(ObjectHeader::MAX_PACKED_LEN, |slice| {
slice
.iter()
.position(|&byte| byte & 0b1000_0000 == 0)
.map(|offset| offset + 1)
})?
.ok_or(ReadPackFileError::Other("invalid object size"))?;
let parser = &mut self.parser(range);
let mut byte = parser.parse_byte()?;
let kind = match (byte & 0b0111_0000) >> 4 {
1 => ObjectKind::Commit,
2 => ObjectKind::Tree,
3 => ObjectKind::Blob,
4 => ObjectKind::Tag,
6 => ObjectKind::OfsDelta,
7 => ObjectKind::RefDelta,
n => return Err(ReadPackFileError::UnknownType(n)),
};
let mut len = usize::from(byte & 0b0000_1111);
let mut shift = 4;
while parser.remaining() != 0 {
byte = parser.parse_byte()?;
len |= usize::from(byte & 0b0111_1111)
.checked_shl(shift)
.ok_or(ReadPackFileError::Other("invalid object size"))?;
shift += 7;
}
Ok(ObjectHeader { len, kind })
}
fn read_delta_offset(&mut self) -> Result<u64, ReadPackFileError> {
let range = self
.read_until(ObjectHeader::MAX_DELTA_OFFSET_LEN, |slice| {
slice
.iter()
.position(|&byte| byte & 0b1000_0000 == 0)
.map(|offset| offset + 1)
})?
.ok_or(ReadPackFileError::Other("invalid delta offset"))?;
let parser = &mut self.parser(range);
let mut offset: u64 = 0;
while parser.remaining() != 0 {
let byte = parser.parse_byte()?;
offset <<= 7;
offset += u64::from(byte & 0b0111_1111);
}
Ok(offset)
}
fn read_delta_reference(&mut self) -> Result<Id, ReadPackFileError> {
Ok(self.read_id()?)
}
}
impl fmt::Debug for PackFile {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("PackFile")
.field("version", &self.version)
.finish()
}
}
#[cfg(test)]
mod tests {
use bstr::B;
use super::*;
#[cfg(target_pointer_width = "64")]
#[test]
fn pack_object_header_max_len() {
let max_len_header = b"\x9F\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x0F";
assert_eq!(max_len_header.len(), ObjectHeader::MAX_PACKED_LEN);
let mut buffer = parse::Buffer::new(io::Cursor::new(B(max_len_header)));
let parsed_header = buffer.read_pack_object_header().unwrap();
assert_eq!(parsed_header.kind, ObjectKind::Commit);
assert_eq!(parsed_header.len, usize::MAX);
}
#[test]
fn pack_object_header_max_delta_offset_len() {
let max_len_header = b"\x81\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F";
assert_eq!(max_len_header.len(), ObjectHeader::MAX_DELTA_OFFSET_LEN);
let mut buffer = parse::Buffer::new(io::Cursor::new(B(max_len_header)));
assert_eq!(buffer.read_delta_offset().unwrap(), u64::MAX);
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[macro_use]
extern crate afl;
use common_ast::parser::parse_expr;
use common_ast::parser::tokenize_sql;
use common_ast::Backtrace;
fn main() {
loop {
fuzz!(|text: String| {
let backtrace = Backtrace::new();
let tokens = tokenize_sql(&text).unwrap();
let _ = parse_expr(&tokens, &backtrace);
});
}
}
|
use cipher::{self, Mode};
use dh::{mod_p::Dh, DH};
use num::bigint::BigUint;
use sha1::{Digest, Sha1};
fn main() {
println!("🔓 Challenge 34");
normal_protocol();
mitm();
}
struct Person {
dh: Dh,
sk: BigUint,
pub pk: BigUint,
}
impl Person {
pub fn new() -> Person {
let dh = Dh::new();
let (sk, pk) = dh.key_gen();
Person { dh, sk, pk }
}
pub fn gen_session_key(&self, pk: &BigUint) -> BigUint {
self.dh.kex(&self.sk, &pk)
}
}
fn normal_protocol() {
println!("Starting normal protocol...");
let alice = Person::new();
let bob = Person::new();
let alice_session_key = alice.gen_session_key(&bob.pk);
let bob_session_key = bob.gen_session_key(&alice.pk);
let msg = b"secert msg from A to B".to_vec();
let alice_ct = encrypt(&alice_session_key, &msg);
let bob_ct = encrypt(&bob_session_key, &decrypt(&bob_session_key, &alice_ct));
assert_eq!(decrypt(&alice_session_key, &bob_ct), msg);
println!("Success!");
}
fn mitm() {
println!("Simulating Man-in-the-Middle Attack...");
let alice = Person::new();
let bob = Person::new();
let eve = Person::new();
let alice_eve_key = eve.gen_session_key(&alice.pk);
let eve_bob_key = eve.gen_session_key(&bob.pk);
// Alice sending message to Eve
let msg_alice = b"msg intended from Alice to Bob".to_vec();
let alice_ct = encrypt(&alice_eve_key, &msg_alice);
// Eve decrypt it and forward to Bob
let eve_ct = encrypt(&eve_bob_key, &decrypt(&alice_eve_key, &alice_ct));
// Bob sending message to Eve
let msg_bob = decrypt(&eve_bob_key, &eve_ct);
let bob_ct = encrypt(&eve_bob_key, &msg_bob);
// Eve decrypt it and forward to Alice
let eve_ct = encrypt(&alice_eve_key, &decrypt(&eve_bob_key, &bob_ct));
// finally, alice verifies the msg (and thought "everything is fine")
assert_eq!(decrypt(&alice_eve_key, &eve_ct), msg_alice);
assert_eq!(msg_alice, msg_bob);
println!("MiTM Succeed!");
}
fn encrypt(session_key: &BigUint, msg: &[u8]) -> Vec<u8> {
let mut h = Sha1::new();
h.input(session_key.to_bytes_le());
let enc_key = &h.result().to_vec()[..16];
let cbc_cipher = cipher::new(Mode::CBC);
cbc_cipher.encrypt(&enc_key, &msg)
}
fn decrypt(session_key: &BigUint, ct: &[u8]) -> Vec<u8> {
let mut h = Sha1::new();
h.input(session_key.to_bytes_le());
let enc_key = &h.result().to_vec()[..16];
let cbc_cipher = cipher::new(Mode::CBC);
cbc_cipher.decrypt(&enc_key, &ct)
}
|
use crate::cpu::cpu::CPU;
use crate::cpu::cpu::Target;
use crate::cpu::cpu::Instruction;
#[test]
fn add() {
let mut cpu = CPU::new();
cpu.reg.a = 0x02;
cpu.reg.b = 0x02;
cpu.execute(Instruction::ADD(cpu.reg.b));
assert_eq!(cpu.reg.a, 4);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn adc() {
let mut cpu = CPU::new();
cpu.reg.a = 0xfd;
cpu.reg.b = 0x02;
cpu.reg.f.c = true;
cpu.execute(Instruction::ADC(cpu.reg.b));
assert_eq!(cpu.reg.a, 0x0);
assert_eq!(cpu.reg.f.z, true);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, true);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn addhl() {
let mut cpu = CPU::new();
cpu.reg.set_hl(0xF000);
cpu.reg.set_bc(0x000F);
cpu.execute(Instruction::ADDHL(cpu.reg.bc()));
assert_eq!(cpu.reg.hl(), 0xF00F);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn sub() {
let mut cpu = CPU::new();
cpu.reg.a = 0x00;
cpu.reg.b = 0x01;
cpu.execute(Instruction::SUB(cpu.reg.b));
assert_eq!(cpu.reg.a, 0xFF);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, true);
assert_eq!(cpu.reg.f.c, true);
assert_eq!(cpu.reg.f.h, true);
}
#[test]
fn sbc() {
let mut cpu = CPU::new();
cpu.reg.a = 0x10;
cpu.reg.b = 0x01;
cpu.reg.f.c = true;
cpu.execute(Instruction::SBC(cpu.reg.b));
assert_eq!(cpu.reg.a, 0x0E);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, true);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, true);
}
#[test]
fn and() {
let mut cpu = CPU::new();
cpu.reg.a = 0x11;
cpu.reg.b = 0x01;
cpu.execute(Instruction::AND(cpu.reg.b));
assert_eq!(cpu.reg.a, 0x01);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, true);
}
#[test]
fn or() {
let mut cpu = CPU::new();
cpu.reg.a = 0x11;
cpu.reg.b = 0x01;
cpu.execute(Instruction::OR(cpu.reg.b));
assert_eq!(cpu.reg.a, 0x11);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn xor() {
let mut cpu = CPU::new();
cpu.reg.a = 0x11;
cpu.reg.b = 0x01;
cpu.execute(Instruction::XOR(RegisterTarget::B));
assert_eq!(cpu.reg.a, 0x10);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn cp() {
let mut cpu = CPU::new();
cpu.reg.a = 0x00;
cpu.reg.b = 0x01;
cpu.execute(Instruction::CP(Some(RegisterTarget::B)));
assert_eq!(cpu.reg.a, 0x00);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, true);
assert_eq!(cpu.reg.f.c, true);
assert_eq!(cpu.reg.f.h, true);
}
#[test]
fn inc() {
let mut cpu = CPU::new();
cpu.reg.b = 0x0F;
cpu.execute(Instruction::INC(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x10);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.h, true);
}
#[test]
fn dec() {
let mut cpu = CPU::new();
cpu.reg.b = 0x01;
cpu.execute(Instruction::DEC(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x00);
assert_eq!(cpu.reg.f.z, true);
assert_eq!(cpu.reg.f.n, true);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rra() {
let mut cpu = CPU::new();
cpu.reg.a = 0x08;
cpu.execute(Instruction::RRA);
assert_eq!(cpu.reg.a, 0x04);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rla() {
let mut cpu = CPU::new();
cpu.reg.a = 0x08;
cpu.execute(Instruction::RLA);
assert_eq!(cpu.reg.a, 0x10);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rrca() {
let mut cpu = CPU::new();
cpu.reg.a = 0x08;
cpu.execute(Instruction::RRCA);
assert_eq!(cpu.reg.a, 0x04);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rrla() {
let mut cpu = CPU::new();
cpu.reg.a = 0x08;
cpu.execute(Instruction::RRLA);
assert_eq!(cpu.reg.a, 0x10);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rr() {
let mut cpu = CPU::new();
cpu.reg.b = 0x08;
cpu.execute(Instruction::RR(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x04);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rl() {
let mut cpu = CPU::new();
cpu.reg.b = 0x08;
cpu.execute(Instruction::RL(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x10);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rrc() {
let mut cpu = CPU::new();
cpu.reg.b = 0x08;
cpu.execute(Instruction::RRC(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x04);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn rlc() {
let mut cpu = CPU::new();
cpu.reg.b = 0x08;
cpu.execute(Instruction::RLC(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x10);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn srl() {
let mut cpu = CPU::new();
cpu.reg.b = 0x08;
cpu.execute(Instruction::SRL(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x04);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn sra() {
let mut cpu = CPU::new();
cpu.reg.b = 0x08;
cpu.execute(Instruction::SRA(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x04);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn sla() {
let mut cpu = CPU::new();
cpu.reg.b = 0x08;
cpu.execute(Instruction::SLA(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x10);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, false);
assert_eq!(cpu.reg.f.h, false);
}
#[test]
fn swap() {
let mut cpu = CPU::new();
cpu.reg.b = 0xF0;
cpu.execute(Instruction::SWAP(RegisterTarget::B));
assert_eq!(cpu.reg.b, 0x0F);
assert_eq!(cpu.reg.f.z, false);
assert_eq!(cpu.reg.f.n, false);
assert_eq!(cpu.reg.f.c, true);
assert_eq!(cpu.reg.f.h, false);
} |
#[macro_use]
extern crate criterion;
use criterion::Criterion;
extern crate curve25519_dalek;
use curve25519_dalek::scalar::Scalar;
extern crate rand;
use rand::Rng;
extern crate spacesuit;
use spacesuit::{prove, verify, Value};
extern crate bulletproofs;
use bulletproofs::{BulletproofGens, PedersenGens};
fn create_spacesuit_proof_helper(n: usize, c: &mut Criterion) {
let label = format!("Spacesuit proof creation with {} inputs and outputs", n);
c.bench_function(&label, move |b| {
// Generate inputs and outputs to spacesuit prover
let bp_gens = BulletproofGens::new(10000, 1);
let pc_gens = PedersenGens::default();
let mut rng = rand::thread_rng();
let (min, max) = (0u64, std::u64::MAX);
let inputs: Vec<Value> = (0..n)
.map(|_| Value {
q: rng.gen_range(min, max),
a: Scalar::random(&mut rng),
t: Scalar::random(&mut rng),
})
.collect();
let mut outputs = inputs.clone();
rand::thread_rng().shuffle(&mut outputs);
// Make spacesuit proof
b.iter(|| {
prove(&bp_gens, &pc_gens, &inputs, &outputs).unwrap();
})
});
}
fn create_spacesuit_proof_n_2(c: &mut Criterion) {
create_spacesuit_proof_helper(2, c);
}
fn create_spacesuit_proof_n_8(c: &mut Criterion) {
create_spacesuit_proof_helper(8, c);
}
fn create_spacesuit_proof_n_16(c: &mut Criterion) {
create_spacesuit_proof_helper(16, c);
}
fn create_spacesuit_proof_n_32(c: &mut Criterion) {
create_spacesuit_proof_helper(32, c);
}
fn create_spacesuit_proof_n_64(c: &mut Criterion) {
create_spacesuit_proof_helper(64, c);
}
fn verify_spacesuit_proof_helper(n: usize, c: &mut Criterion) {
let label = format!("Spacesuit proof verification with {} inputs and outputs", n);
c.bench_function(&label, move |b| {
// Generate inputs and outputs to spacesuit prover
let bp_gens = BulletproofGens::new(10000, 1);
let pc_gens = PedersenGens::default();
let mut rng = rand::thread_rng();
let (min, max) = (0u64, std::u64::MAX);
let inputs: Vec<Value> = (0..n)
.map(|_| Value {
q: rng.gen_range(min, max),
a: Scalar::random(&mut rng),
t: Scalar::random(&mut rng),
})
.collect();
let mut outputs = inputs.clone();
rand::thread_rng().shuffle(&mut outputs);
let (proof, commitments) = prove(&bp_gens, &pc_gens, &inputs, &outputs).unwrap();
b.iter(|| {
verify(&bp_gens, &pc_gens, &proof, commitments.clone(), n, n).unwrap();
})
});
}
fn verify_spacesuit_proof_n_2(c: &mut Criterion) {
verify_spacesuit_proof_helper(2, c);
}
fn verify_spacesuit_proof_n_8(c: &mut Criterion) {
verify_spacesuit_proof_helper(8, c);
}
fn verify_spacesuit_proof_n_16(c: &mut Criterion) {
verify_spacesuit_proof_helper(16, c);
}
fn verify_spacesuit_proof_n_32(c: &mut Criterion) {
verify_spacesuit_proof_helper(32, c);
}
fn verify_spacesuit_proof_n_64(c: &mut Criterion) {
verify_spacesuit_proof_helper(64, c);
}
criterion_group!{
name = create_spacesuit_proof;
config = Criterion::default().sample_size(10);
targets = create_spacesuit_proof_n_2,
create_spacesuit_proof_n_8,
create_spacesuit_proof_n_16,
create_spacesuit_proof_n_32,
create_spacesuit_proof_n_64,
}
criterion_group!{
name = verify_spacesuit_proof;
config = Criterion::default().sample_size(10);
targets = verify_spacesuit_proof_n_2,
verify_spacesuit_proof_n_8,
verify_spacesuit_proof_n_16,
verify_spacesuit_proof_n_32,
verify_spacesuit_proof_n_64,
}
criterion_main!(create_spacesuit_proof, verify_spacesuit_proof);
|
//! #Problem 4
//! A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
//! Find the largest palindrome made from the product of two 3-digit numbers.
/// Compute highest palindrome computed from number with n digits
pub fn get_highest_palindrome_generated_by_two_number_of_n_digits(digits:u32) -> Option<u32> {
match get_numbers_to_generate_max_palindrome_with_n_digits(digits) {
Some((x,y)) => Some(x*y),
None => None
}
}
/// Optimal solution given by projec teuler
pub fn get_highest_palindrome_optimally_generated_by_two_number_of_3_digits() -> Option<u32> {
let mut largest_palindrome = 0;
let mut a = 999;
while a >= 100 {
let mut b = 999;
while b >= a {
if a*b <= largest_palindrome {
break; //Since a*b is always going to be too small
}
if is_palindrome(a*b) {
largest_palindrome = a*b;
}
b = b-1;
}
a = a-1;
}
Some(largest_palindrome)
}
/// brute force approach of get_highest_palindrome_optimally_generated_by_two_number_of_3_digits
pub fn brute_force_approach_3_digits() -> Option<u32>{
let mut largest_palindrome = 0;
let mut a = 100;
while a <= 999 {
let mut b = 100;
while b <= 999 {
if is_palindrome(a*b) && a*b > largest_palindrome {
largest_palindrome = a*b
}
b = b+1;
}
a = a+1;
}
Some(largest_palindrome)
}
#[derive(Debug)]
struct Palindrome {
//full value of palindrome
p:u32,
//size of the palindrome to avoid calculating it every time
size:u32,
//half part to enable simple subtraction to go dow in palindromes
half:u32,
//minimal value of half do detect when the size of the palindrome has changed
min_half:u32,
//palindrome is odd or even to know if last digit of half should be repeated
is_odd:bool,
}
impl Palindrome {
fn new(p:u32) -> Palindrome {
if !is_palindrome(p) {
panic!("Invalid palindrome {}", p);
}
let size = number_of_digits(p);
let is_odd = size % 2 != 0;
let half = if is_odd {
size /2 +1
}else{
size /2
};
let min_half = power_of_ten(half)/10;
Palindrome{ p, size, half: p / power_of_ten(size-half), min_half, is_odd}
}
//compute previous palindrome
fn mutate_to_prev(&mut self) {
self.half-=1;
if self.half < self.min_half {
self.is_odd = !self.is_odd;
self.size-=1;
if !self.is_odd {
self.min_half = self.min_half / 10;
}else{
self.half = self.half * 10 + 9;
}
}
//TODO this odd value is incorrect. was valid for previous value of half
self.p = half_to_full_palindrome(self.half, self.is_odd);
}
}
/// Get (x,y), where x and y have the size of n digits that can produce the highest palindrome
pub fn get_numbers_to_generate_max_palindrome_with_n_digits(digits:u32) -> Option<(u32,u32)> {
let max_oper = power_of_ten(digits) - 1;
let max = first_palindrome_below(max_oper.pow(2));
let mut p = Palindrome::new(max);
while p.half > 0 {
let n = p.p;
for i in (max_oper/2)..=max_oper {
if n % i == 0 && i < max_oper && number_of_digits(n / i) == digits {
return Some((i, n / i));
}
}
p.mutate_to_prev();
}
None
}
fn power_of_ten(digits:u32) -> u32 {
(10 as u32).pow(digits)
}
/// Compute the number of digits
fn number_of_digits(v:u32) -> u32 {
let mut size = 0;
let mut v = v;
while v > 0 {
v = v /10;
size+=1;
}
size
}
/// Make a palindrome out of half a palindrome. if is_odd is true, last digit is to be
/// placed twice in the center
fn half_to_full_palindrome(half:u32, is_odd:bool) -> u32{
let mut res = half;
let mut v = half;
if is_odd {
v = v / 10;
}
while v > 0 {
res = res * 10 + (v % 10);
v/=10;
}
res
}
// Find first palindrome below max number
fn first_palindrome_below(max:u32) -> u32 {
let mut i = max;
if i > 10 {
//reduce the number of iteration required to get first palindrome
while i > 10 {
i/=10;
}
i = (max / 10)*10 + i
}
while i > 0 && !is_palindrome(i) {
i-=10;
}
if !is_palindrome(i) {
panic!("invalid palindrome: {}", i);
}
i
}
// verify if given n is a palindrome
fn is_palindrome(n:u32) -> bool {
let mut n2 = n;
let mut reverse = 0;
while n2 > 0 {
reverse = reverse * 10 + n2 % 10;
n2 = n2/10;
}
reverse == n
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn first_palindrome_is_correct() {
assert_eq!(997799, first_palindrome_below(999*999));
}
#[test]
fn give_correct_solutions() {
assert_eq!(9009, get_highest_palindrome_generated_by_two_number_of_n_digits(2).unwrap());
assert_eq!(906609, get_highest_palindrome_generated_by_two_number_of_n_digits(3).unwrap());
assert_eq!(906609, get_highest_palindrome_optimally_generated_by_two_number_of_3_digits().unwrap());
}
#[test]
fn max_palindrome_made_out_of_n_digit_number() {
assert_eq!((91, 99), get_numbers_to_generate_max_palindrome_with_n_digits(2).unwrap());
assert_eq!((913, 993), get_numbers_to_generate_max_palindrome_with_n_digits(3).unwrap());
}
#[test]
fn prev_return_only_palindrome_numbers() {
let mut p = Palindrome::new(999);
for i in (0..9).rev() {
p.mutate_to_prev();
assert_eq!((90 + i) * 10 + 9, p.p);
}
p.mutate_to_prev();
assert_eq!(898, p.p);
}
#[test]
fn corner_cases() {
let mut p = Palindrome::new(1001);
p.mutate_to_prev();
assert_eq!(999, p.p);
let mut p = Palindrome::new(101);
p.mutate_to_prev();
assert_eq!(99, p.p);
let mut p = Palindrome::new(11);
p.mutate_to_prev();
assert_eq!(9, p.p);
}
#[test]
fn detect_a_valid_palindrome() {
assert_eq!(true, is_palindrome(9009));
assert_eq!(true, is_palindrome(909));
assert_eq!(true, is_palindrome(99));
}
#[test]
fn detect_an_invalid_palindrome() {
assert_eq!(false, is_palindrome(998001));
assert_eq!(false, is_palindrome(9019));
assert_eq!(false, is_palindrome(119));
assert_eq!(false, is_palindrome(913));
}
} |
use crate::server::*;
fn new(){
println!("Redstone RPC");
let bc = Blockchain::new()?;
let bc1 = Blockchain::new2()?;
let port = 3001;
let utxo_set = UTXOSet { blockchain: bc };
let utxo_set1 = UTXOSet { blockchain: bc1 };
let utxo = utxo_set;
let utxo1 = utxo_set1;
let server = Server::new(port, "",utxo,utxo1)?;
println!("Started RPC");
server.start_server(1)?;
} |
use crate::source::Source;
use crate::to_lowercase_first_char;
use crate::token::Location;
use std::rc::Rc;
#[derive(Debug)]
pub struct ASTs {
pub source: Rc<Source>,
pub class: Class,
}
#[derive(Debug, Clone)]
pub struct Class {
pub loc: Location,
pub name: String,
pub vars: Vec<ClassVarDec>,
pub subroutines: Vec<SubroutineDec>,
}
impl Class {
pub fn static_vars(&self) -> Vec<&ClassVarDec> {
self.vars
.iter()
.filter(|var| var.modifier == ClassVarModifier::Static)
.collect()
}
pub fn field_vars(&self) -> Vec<&ClassVarDec> {
self.vars
.iter()
.filter(|var| var.modifier == ClassVarModifier::Field)
.collect()
}
}
#[derive(Debug, Clone)]
pub struct ClassVarDec {
pub loc: Location,
pub modifier: ClassVarModifier,
pub typ: Type,
pub names: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ClassVarModifier {
Static,
Field,
}
impl ClassVarModifier {
pub fn display(&self) -> String {
to_lowercase_first_char(format!("{:?}", self).as_str())
}
}
#[derive(Debug, Clone)]
pub struct SubroutineDec {
pub loc: Location,
pub modifier: SubroutineModifier,
pub typ: ReturnType,
pub name: String,
pub parameters: Vec<ParameterDec>,
pub body: SubroutineBody,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SubroutineModifier {
Constructor,
Function,
Method,
}
impl SubroutineModifier {
pub fn display(&self) -> String {
to_lowercase_first_char(format!("{:?}", self).as_str())
}
}
#[derive(Debug, Clone)]
pub struct ParameterDec {
pub loc: Location,
pub typ: Type,
pub name: String,
}
#[derive(Debug, Clone)]
pub struct SubroutineBody {
pub vars: Vec<VarDec>,
pub statements: Statements,
}
#[derive(Debug, Clone)]
pub struct VarDec {
pub loc: Location,
pub typ: Type,
pub names: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct Statements {
pub statements: Vec<Statement>,
}
#[derive(Debug, Clone)]
pub enum Statement {
Let(LetStatement),
If(IfStatement),
While(WhileStatement),
Do(DoStatement),
Return(ReturnStatement),
}
#[derive(Debug, Clone)]
pub struct LetStatement {
pub loc: Location,
pub name: String,
pub accessor: Option<Expr>,
pub expr: Expr,
}
#[derive(Debug, Clone)]
pub struct IfStatement {
pub loc: Location,
pub cond: Expr,
pub statements: Statements,
pub else_branch: Option<Statements>,
}
#[derive(Debug, Clone)]
pub struct WhileStatement {
pub loc: Location,
pub cond: Expr,
pub statements: Statements,
}
#[derive(Debug, Clone)]
pub struct DoStatement {
pub loc: Location,
pub call: SubroutineCall,
}
#[derive(Debug, Clone)]
pub struct ReturnStatement {
pub loc: Location,
pub expr: Option<Expr>,
}
#[derive(Debug, Clone)]
pub struct Expr {
pub loc: Location,
pub lhs: Box<Term>,
pub rhs: Box<Option<(Op, Expr)>>,
}
#[derive(Debug, Clone)]
pub enum Term {
Integer(u16),
Str(String),
Keyword(KeywordConst),
Var(String),
IndexAccess(String, Expr),
Call(SubroutineCall),
Expr(Expr),
Unary(UnaryOp, Box<Term>),
}
#[derive(Debug, Clone)]
pub enum KeywordConst {
True,
False,
Null,
This,
}
impl KeywordConst {
pub fn display(&self) -> String {
to_lowercase_first_char(format!("{:?}", self).as_str())
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Op {
Add,
Sub,
Mul,
Div,
And,
Or,
Lt,
Gt,
Eq,
}
impl Op {
pub fn parse(sym: char) -> Option<Op> {
match sym {
'+' => Some(Op::Add),
'-' => Some(Op::Sub),
'*' => Some(Op::Mul),
'/' => Some(Op::Div),
'&' => Some(Op::And),
'|' => Some(Op::Or),
'<' => Some(Op::Lt),
'>' => Some(Op::Gt),
'=' => Some(Op::Eq),
_ => None,
}
}
pub fn display(&self) -> String {
match self {
Op::Add => "+",
Op::Sub => "-",
Op::Mul => "*",
Op::Div => "/",
Op::And => "&",
Op::Or => "|",
Op::Lt => "<",
Op::Gt => ">",
Op::Eq => "=",
}
.to_string()
}
}
#[derive(Debug, Clone)]
pub enum UnaryOp {
Minus,
Not,
}
impl UnaryOp {
pub fn parse(sym: char) -> Option<UnaryOp> {
match sym {
'-' => Some(UnaryOp::Minus),
'~' => Some(UnaryOp::Not),
_ => None,
}
}
pub fn display(&self) -> String {
match self {
UnaryOp::Minus => "-",
UnaryOp::Not => "~",
}
.to_string()
}
}
#[derive(Debug, Clone)]
pub struct SubroutineCall {
pub loc: Location,
pub reciever: Option<String>,
pub name: String,
pub exprs: Vec<Expr>,
}
#[derive(Debug, Clone)]
pub enum Type {
Int,
Char,
Boolean,
Class(String),
}
impl Type {
pub fn display(&self) -> String {
match self {
Type::Int | Type::Char | Type::Boolean => {
to_lowercase_first_char(format!("{:?}", self).as_str())
}
Type::Class(name) => name.clone(),
}
}
}
#[derive(Debug, Clone)]
pub enum ReturnType {
Void,
Type(Type),
}
|
use sp_std::prelude::*;
use codec::Encode;
use move_core_types::account_address::AccountAddress;
pub trait AccountIdAsBytes<AccountId, T: Sized> {
fn account_to_bytes(acc: &AccountId) -> T;
}
impl<T> AccountIdAsBytes<T::AccountId, Vec<u8>> for T
where
T: frame_system::Trait,
T::AccountId: Encode,
{
fn account_to_bytes(acc: &T::AccountId) -> Vec<u8> {
acc.encode()
}
}
pub fn account_to_bytes<AccountId: Encode>(acc: &AccountId) -> [u8; AccountAddress::LENGTH] {
const LENGTH: usize = AccountAddress::LENGTH;
let mut result = [0; LENGTH];
let bytes = acc.encode();
let skip = if bytes.len() < LENGTH {
LENGTH - bytes.len()
} else {
0
};
(&mut result[skip..]).copy_from_slice(&bytes);
trace!(
"converted: (with skip: {})\n\t{:?}\n\tto {:?}",
skip,
bytes,
result
);
result
}
pub fn account_to_account_address<AccountId: Encode>(acc: &AccountId) -> AccountAddress {
AccountAddress::new(account_to_bytes(acc))
}
impl<T> AccountIdAsBytes<T::AccountId, [u8; AccountAddress::LENGTH]> for T
where
T: frame_system::Trait,
T::AccountId: Encode,
{
fn account_to_bytes(acc: &T::AccountId) -> [u8; AccountAddress::LENGTH] {
account_to_bytes(acc)
}
}
#[cfg(test)]
mod tests {
use super::account_to_account_address;
use sp_core::sr25519::Public;
use sp_core::crypto::Ss58Codec;
#[test]
fn convert_address() {
//Alice
let pk =
Public::from_ss58check("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY").unwrap();
let addr = account_to_account_address(&pk);
assert_eq!(
"D43593C715FDD31C61141ABD04A99FD6822C8558854CCDE39A5684E7A56DA27D",
addr.to_string()
);
//Bob
let pk =
Public::from_ss58check("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty").unwrap();
let addr = account_to_account_address(&pk);
assert_eq!(
"8EAF04151687736326C9FEA17E25FC5287613693C912909CB226AA4794F26A48",
addr.to_string()
);
}
}
|
use regex::Regex;
use std::fs;
use std::str;
#[test]
fn validate_4_1() {
assert_eq!(algorithm("src/day_4/input_test.txt"), (4, 2));
}
fn algorithm(file_location: &str) -> (usize, usize) {
let content = fs::read_to_string(file_location).unwrap();
let delimiter = Regex::new("\n\\s+\n").unwrap();
let passports: Vec<&str> = delimiter.split(&content).collect();
let keys = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];
let mut matches = 0;
for passport in passports.iter() {
if keys.iter().all(|key| passport.contains(key)) {
matches = matches + 1;
}
}
(passports.len(), matches)
}
pub fn run() {
let (passports, valid) = algorithm("src/day_4/input.txt");
println!("Out of {} passports, {} are valid.", passports, valid);
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::RREN {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `RR0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR0R {
#[doc = "RR\\[0\\] register is disabled."]
DISABLED,
#[doc = "RR\\[0\\] register is enabled."]
ENABLED,
}
impl RR0R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR0R::DISABLED => false,
RR0R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR0R {
match value {
false => RR0R::DISABLED,
true => RR0R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR0R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR0R::ENABLED
}
}
#[doc = "Possible values of the field `RR1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR1R {
#[doc = "RR\\[1\\] register is disabled."]
DISABLED,
#[doc = "RR\\[1\\] register is enabled."]
ENABLED,
}
impl RR1R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR1R::DISABLED => false,
RR1R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR1R {
match value {
false => RR1R::DISABLED,
true => RR1R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR1R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR1R::ENABLED
}
}
#[doc = "Possible values of the field `RR2`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR2R {
#[doc = "RR\\[2\\] register is disabled."]
DISABLED,
#[doc = "RR\\[2\\] register is enabled."]
ENABLED,
}
impl RR2R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR2R::DISABLED => false,
RR2R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR2R {
match value {
false => RR2R::DISABLED,
true => RR2R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR2R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR2R::ENABLED
}
}
#[doc = "Possible values of the field `RR3`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR3R {
#[doc = "RR\\[3\\] register is disabled."]
DISABLED,
#[doc = "RR\\[3\\] register is enabled."]
ENABLED,
}
impl RR3R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR3R::DISABLED => false,
RR3R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR3R {
match value {
false => RR3R::DISABLED,
true => RR3R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR3R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR3R::ENABLED
}
}
#[doc = "Possible values of the field `RR4`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR4R {
#[doc = "RR\\[4\\] register is disabled."]
DISABLED,
#[doc = "RR\\[4\\] register is enabled."]
ENABLED,
}
impl RR4R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR4R::DISABLED => false,
RR4R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR4R {
match value {
false => RR4R::DISABLED,
true => RR4R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR4R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR4R::ENABLED
}
}
#[doc = "Possible values of the field `RR5`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR5R {
#[doc = "RR\\[5\\] register is disabled."]
DISABLED,
#[doc = "RR\\[5\\] register is enabled."]
ENABLED,
}
impl RR5R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR5R::DISABLED => false,
RR5R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR5R {
match value {
false => RR5R::DISABLED,
true => RR5R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR5R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR5R::ENABLED
}
}
#[doc = "Possible values of the field `RR6`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR6R {
#[doc = "RR\\[6\\] register is disabled."]
DISABLED,
#[doc = "RR\\[6\\] register is enabled."]
ENABLED,
}
impl RR6R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR6R::DISABLED => false,
RR6R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR6R {
match value {
false => RR6R::DISABLED,
true => RR6R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR6R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR6R::ENABLED
}
}
#[doc = "Possible values of the field `RR7`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RR7R {
#[doc = "RR\\[7\\] register is disabled."]
DISABLED,
#[doc = "RR\\[7\\] register is enabled."]
ENABLED,
}
impl RR7R {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
RR7R::DISABLED => false,
RR7R::ENABLED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> RR7R {
match value {
false => RR7R::DISABLED,
true => RR7R::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline]
pub fn is_disabled(&self) -> bool {
*self == RR7R::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline]
pub fn is_enabled(&self) -> bool {
*self == RR7R::ENABLED
}
}
#[doc = "Values that can be written to the field `RR0`"]
pub enum RR0W {
#[doc = "RR\\[0\\] register is disabled."]
DISABLED,
#[doc = "RR\\[0\\] register is enabled."]
ENABLED,
}
impl RR0W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR0W::DISABLED => false,
RR0W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR0W<'a> {
w: &'a mut W,
}
impl<'a> _RR0W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR0W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[0\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR0W::DISABLED)
}
#[doc = "RR\\[0\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR0W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RR1`"]
pub enum RR1W {
#[doc = "RR\\[1\\] register is disabled."]
DISABLED,
#[doc = "RR\\[1\\] register is enabled."]
ENABLED,
}
impl RR1W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR1W::DISABLED => false,
RR1W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR1W<'a> {
w: &'a mut W,
}
impl<'a> _RR1W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR1W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[1\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR1W::DISABLED)
}
#[doc = "RR\\[1\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR1W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RR2`"]
pub enum RR2W {
#[doc = "RR\\[2\\] register is disabled."]
DISABLED,
#[doc = "RR\\[2\\] register is enabled."]
ENABLED,
}
impl RR2W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR2W::DISABLED => false,
RR2W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR2W<'a> {
w: &'a mut W,
}
impl<'a> _RR2W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR2W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[2\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR2W::DISABLED)
}
#[doc = "RR\\[2\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR2W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RR3`"]
pub enum RR3W {
#[doc = "RR\\[3\\] register is disabled."]
DISABLED,
#[doc = "RR\\[3\\] register is enabled."]
ENABLED,
}
impl RR3W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR3W::DISABLED => false,
RR3W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR3W<'a> {
w: &'a mut W,
}
impl<'a> _RR3W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR3W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[3\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR3W::DISABLED)
}
#[doc = "RR\\[3\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR3W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RR4`"]
pub enum RR4W {
#[doc = "RR\\[4\\] register is disabled."]
DISABLED,
#[doc = "RR\\[4\\] register is enabled."]
ENABLED,
}
impl RR4W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR4W::DISABLED => false,
RR4W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR4W<'a> {
w: &'a mut W,
}
impl<'a> _RR4W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR4W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[4\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR4W::DISABLED)
}
#[doc = "RR\\[4\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR4W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RR5`"]
pub enum RR5W {
#[doc = "RR\\[5\\] register is disabled."]
DISABLED,
#[doc = "RR\\[5\\] register is enabled."]
ENABLED,
}
impl RR5W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR5W::DISABLED => false,
RR5W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR5W<'a> {
w: &'a mut W,
}
impl<'a> _RR5W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR5W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[5\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR5W::DISABLED)
}
#[doc = "RR\\[5\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR5W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RR6`"]
pub enum RR6W {
#[doc = "RR\\[6\\] register is disabled."]
DISABLED,
#[doc = "RR\\[6\\] register is enabled."]
ENABLED,
}
impl RR6W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR6W::DISABLED => false,
RR6W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR6W<'a> {
w: &'a mut W,
}
impl<'a> _RR6W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR6W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[6\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR6W::DISABLED)
}
#[doc = "RR\\[6\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR6W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `RR7`"]
pub enum RR7W {
#[doc = "RR\\[7\\] register is disabled."]
DISABLED,
#[doc = "RR\\[7\\] register is enabled."]
ENABLED,
}
impl RR7W {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
RR7W::DISABLED => false,
RR7W::ENABLED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _RR7W<'a> {
w: &'a mut W,
}
impl<'a> _RR7W<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: RR7W) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "RR\\[7\\] register is disabled."]
#[inline]
pub fn disabled(self) -> &'a mut W {
self.variant(RR7W::DISABLED)
}
#[doc = "RR\\[7\\] register is enabled."]
#[inline]
pub fn enabled(self) -> &'a mut W {
self.variant(RR7W::ENABLED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Enable or disable RR\\[0\\] register."]
#[inline]
pub fn rr0(&self) -> RR0R {
RR0R::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 1 - Enable or disable RR\\[1\\] register."]
#[inline]
pub fn rr1(&self) -> RR1R {
RR1R::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - Enable or disable RR\\[2\\] register."]
#[inline]
pub fn rr2(&self) -> RR2R {
RR2R::_from({
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 3 - Enable or disable RR\\[3\\] register."]
#[inline]
pub fn rr3(&self) -> RR3R {
RR3R::_from({
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 4 - Enable or disable RR\\[4\\] register."]
#[inline]
pub fn rr4(&self) -> RR4R {
RR4R::_from({
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 5 - Enable or disable RR\\[5\\] register."]
#[inline]
pub fn rr5(&self) -> RR5R {
RR5R::_from({
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 6 - Enable or disable RR\\[6\\] register."]
#[inline]
pub fn rr6(&self) -> RR6R {
RR6R::_from({
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 7 - Enable or disable RR\\[7\\] register."]
#[inline]
pub fn rr7(&self) -> RR7R {
RR7R::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 1 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - Enable or disable RR\\[0\\] register."]
#[inline]
pub fn rr0(&mut self) -> _RR0W {
_RR0W { w: self }
}
#[doc = "Bit 1 - Enable or disable RR\\[1\\] register."]
#[inline]
pub fn rr1(&mut self) -> _RR1W {
_RR1W { w: self }
}
#[doc = "Bit 2 - Enable or disable RR\\[2\\] register."]
#[inline]
pub fn rr2(&mut self) -> _RR2W {
_RR2W { w: self }
}
#[doc = "Bit 3 - Enable or disable RR\\[3\\] register."]
#[inline]
pub fn rr3(&mut self) -> _RR3W {
_RR3W { w: self }
}
#[doc = "Bit 4 - Enable or disable RR\\[4\\] register."]
#[inline]
pub fn rr4(&mut self) -> _RR4W {
_RR4W { w: self }
}
#[doc = "Bit 5 - Enable or disable RR\\[5\\] register."]
#[inline]
pub fn rr5(&mut self) -> _RR5W {
_RR5W { w: self }
}
#[doc = "Bit 6 - Enable or disable RR\\[6\\] register."]
#[inline]
pub fn rr6(&mut self) -> _RR6W {
_RR6W { w: self }
}
#[doc = "Bit 7 - Enable or disable RR\\[7\\] register."]
#[inline]
pub fn rr7(&mut self) -> _RR7W {
_RR7W { w: self }
}
}
|
extern crate jlib;
use jlib::api::set_fee_rate::data::{FeeRateResponse, SetBrokerageSideKick};
use jlib::api::set_fee_rate::api::FeeRate;
use jlib::api::message::amount::Amount;
use jlib::api::config::Config;
pub static TEST_SERVER: &'static str = "ws://101.200.176.249:5040"; //dev12 国密服务器
fn main() {
let config = Config::new(TEST_SERVER, true);
let account: String = "j9syYwWgtmjchcbqhVB18pmFqXUYahZvvg".to_string();
let secret:String = "shstwqJpVJbsqFA5uYJJw1YniXcDF".to_string();
let fee_account: String = "j9syYwWgtmjchcbqhVB18pmFqXUYahZvvg".to_string();
let den = 1u64;
let num = 1000u64;
let amount: Amount = Amount::new(Some("TES".to_string()), "3".to_string(), Some("jP7G6Ue5AcQ5GZ71LkMxXvf5Reg44EKrjy".to_string()));
FeeRate::with_params(config, account, secret, fee_account).set_rate( den, num, amount,
|x| match x {
Ok(response) => {
let res: FeeRateResponse = response;
println!("set brokerage: {:?}", &res);
},
Err(e) => {
let err: SetBrokerageSideKick = e;
println!("err: {:?}", err);
}
});
}
|
use crate::config::{config, Config};
use crate::errors::*;
use crate::pool::{create_pool, ConnectionPool};
use crate::query::Query;
use crate::stream::RowStream;
use crate::txn::Txn;
use std::sync::Arc;
use tokio::sync::Mutex;
/// A neo4j database abstraction
pub struct Graph {
config: Config,
pool: ConnectionPool,
}
/// Returns a [`Query`] which provides methods like [`Query::param`] to add parameters to the query
pub fn query(q: &str) -> Query {
Query::new(q.to_owned())
}
impl Graph {
/// Connects to the database with configurations provided, you can build a config using
/// [`config`]
pub async fn connect(config: Config) -> Result<Self> {
let pool = create_pool(&config).await;
Ok(Graph { config, pool })
}
/// Connects to the database with default configurations
pub async fn new(uri: &str, user: &str, password: &str) -> Result<Self> {
let config = config().uri(uri).user(user).password(password).build()?;
Self::connect(config).await
}
/// Starts a new transaction, all queries that needs to be run/executed within the transaction
/// should be executed using either [`Txn::run`] or [`Txn::execute`]
pub async fn start_txn(&self) -> Result<Txn> {
let connection = self.pool.get().await?;
Txn::new(self.config.clone(), connection).await
}
/// Runs a query using a connection from the connection pool, it doesn't return any
/// [`RowStream`] as the `run` abstraction discards any stream.
///
/// Use [`Graph::run`] for cases where you just want a write operation
///
/// use [`Graph::execute`] when you are interested in the result stream
pub async fn run(&self, q: Query) -> Result<()> {
let connection = Arc::new(Mutex::new(self.pool.get().await?));
q.run(&self.config, connection).await
}
/// Executes a query and returns a [`RowStream`]
pub async fn execute(&self, q: Query) -> Result<RowStream> {
let connection = Arc::new(Mutex::new(self.pool.get().await?));
q.execute(&self.config, connection).await
}
}
|
#![feature(global_asm, asm)]
#![feature(alloc, alloc_error_handler)]
#![feature(core_intrinsics, lang_items)]
#![feature(ptr_wrapping_offset_from)]
#![feature(align_offset)]
#![no_std] // don't link the Rust standard library
#![no_main] // disable all Rust-level entry points
#![allow(dead_code)]
global_asm!(include_str!("boot.S"));
#[macro_use]
extern crate alloc;
use core::panic::PanicInfo;
use core::intrinsics::volatile_load;
//use alloc::prelude::*;
mod uart;
mod mem;
mod util;
mod timer;
mod task;
mod mmu;
use self::util::mmio_write;
#[allow(dead_code)]
mod constval {
pub const CORE0_INTERRUPT_SOURCE: u32 = 0x40000060;
pub const IRQ_PEND_BASIC: u32 = 0x3F00B200;
pub const IRQ_PEND1: u32 = 0x3F00B204;
pub const IRQ_PEND2: u32 = 0x3F00B208;
pub const UART0_MIS: u32 = 0x3f201040;
pub const GPU_INTERRUPTS_ROUTING: u32 = 0x4000000C;
}
use self::constval::*;
#[global_allocator]
static GLOBAL: mem::KernelAllocator = mem::KernelAllocator;
#[no_mangle]
pub extern fn kernel_main() {
unsafe {mem::init()};
uart::init();
timer::init();
// route IRQ to CORE0
unsafe {mmio_write(GPU_INTERRUPTS_ROUTING, 0u32);};
enable_irq();
mmu::init();
task::demo_start();
uart::write("!!!! unreachable\n");
loop {
// uart::write(&format!("SYSTEM_TIMER_C1: {}\n", unsafe { mmio_read(timer::SYSTEM_TIMER_CLO) }));
unsafe {asm!("" :::: "volatile");}
}
}
#[inline]
fn enable_irq() {
unsafe { asm!("cpsie i");}
}
#[inline]
fn disable_irq() {
unsafe {asm!("cpsid i");}
}
#[lang = "eh_personality"]
pub extern fn eh_personality() {}
/// This function is called on panic.
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {
unsafe {asm!("" :::: "volatile");}
}
}
unsafe fn check_flag(addr: u32, val: u32) -> bool {
return volatile_load(addr as *mut u32) & val > 0;
}
#[no_mangle]
pub extern "C" fn irq_handler() -> u32 {
if unsafe { check_flag(CORE0_INTERRUPT_SOURCE, 1<<8) } {
if unsafe { check_flag(IRQ_PEND2, 1 << 25)} {
if unsafe { check_flag(UART0_MIS, 1 << 4) } {
uart::writec(uart::getc());
}
}
}
if timer::read_core0timer_pending() & 0x08 > 0 {
timer::timer_isr();
return 1
}
uart::write("\nirq_handler\n");
0
}
#[no_mangle]
pub extern "C" fn demo_context_switch(sp: *mut u32) {
task::demo_context_switch(sp);
}
// for custom allocator
#[no_mangle]
pub extern fn __aeabi_unwind_cpp_pr0 () {}
|
use crate::datastructure::DataStructure;
use crate::raytracer::RayTracer;
use crate::shader::Shader;
use crate::util::camera::Camera;
use crate::util::rng::get_rng;
use crate::util::vector::Vector;
use rand::Rng;
#[derive(Debug)]
pub struct JMSTracer {
samples_per_pixel: usize,
}
impl JMSTracer {
pub fn new(samples_per_pixel: usize) -> Self {
Self { samples_per_pixel }
}
}
impl RayTracer for JMSTracer {
fn raytrace<'r>(
&self,
x: usize,
y: usize,
datastructure: &'r (dyn DataStructure + 'r),
shader: &'r (dyn Shader + 'r),
camera: &Camera,
) -> Vector {
let mut out = Vector::repeated(0f64);
for _ in 0..self.samples_per_pixel {
let ray = camera.generate_ray(
x as f64 + get_rng(|mut r| r.gen::<f64>()),
y as f64 + get_rng(|mut r| r.gen::<f64>()),
);
out += shader.shade(&ray, datastructure);
}
out / self.samples_per_pixel as f64
}
}
|
mod macros;
mod marker;
mod ops;
mod signed;
mod unsigned;
pub use marker::*;
pub use ops::*;
pub use signed::*;
pub use unsigned::*;
|
use serde::Deserialize;
use serenity::{
async_trait,
model::{channel::Message, error::Error, gateway::Ready},
prelude::*,
};
use std::{collections::HashMap, sync::Mutex};
use tokio::task;
pub struct Handler {
user_lock: Mutex<HashMap<u64, HashMap<u64, MapData>>>,
config: Config
}
#[derive(Clone, Deserialize)]
pub struct Config {
pub token: String,
pub prefix: String,
pub timeout: Option<std::time::Duration>,
pub tmppath: Option<std::path::PathBuf>,
pub transpile: bool
}
#[derive(Clone)]
struct MapData {
text: String,
botmsg: Message,
}
impl Handler {
pub fn new(config: Config) -> Handler {
Handler {
user_lock: Mutex::new(HashMap::new()),
config
}
}
fn add_to_map(&self, chid: u64, uid: u64, content: String, botmsg: Message) {
let mut channels = self.user_lock.lock().unwrap();
if let Some(user) = channels.get_mut(&chid) {
user.insert(
uid,
MapData {
text: content,
botmsg,
},
);
} else {
channels.insert(chid, {
let mut map = HashMap::new();
map.insert(
uid,
MapData {
text: content,
botmsg,
},
);
map
});
}
}
fn get_user_lock(&self, chid: u64, uid: u64) -> Option<MapData> {
if let Some(c) = self.user_lock.lock().unwrap().get_mut(&chid) {
if let Some(m) = c.remove(&uid) {
Some(m)
} else {
None
}
} else {
None
}
}
}
#[async_trait]
impl EventHandler for Handler {
async fn message(&self, ctx: Context, msg: Message) {
let mapdata = self.get_user_lock(msg.channel_id.0, msg.author.id.0);
let transpile = self.config.transpile;
let pl = self.config.prefix.len();
let timeout = self.config.timeout;
let prog = if let Some(d) = mapdata.clone() {
Some(d.text)
} else if msg.content.len() > pl + 1 {
if msg.content[..pl + 1] == format!("{} ", self.config.prefix) {
Some(String::from(&msg.content[2..]))
} else {
None
}
} else if msg.content == self.config.prefix && msg.attachments.len() > 0 {
match msg.attachments[0].download().await {
Ok(chars) => Some(String::from_utf8_lossy(&chars).into_owned()),
Err(err) => {
println!("Error downloading attachment: {:?}", err);
None
}
}
} else {
None
};
let input = if let Some(d) = mapdata {
if let Err(err) = d.botmsg.delete(&ctx.http).await {
println!("Error deleting message: {:?}", err);
}
Some(msg.content)
} else {
None
};
let output = if let Some(prog) = prog {
if bf_lib::wants_input(&prog) && input == None {
let botmsg = msg
.channel_id
.say(
&ctx.http,
format!(
"Program requires input, next message from {} will be read",
msg.author.name
),
)
.await
.expect("Error sending message");
self.add_to_map(msg.channel_id.0, msg.author.id.0, prog, botmsg);
None
} else {
//let join = task::spawn_blocking(move || bf_lib::Exec::prog(&prog).input(input).timeout(self.config.timeout.clone()).run());
let join = task::spawn_blocking(move ||
{
let exec = bf_lib::Exec::prog(&prog).input(input).timeout(timeout);
if transpile {
exec.run()
} else { exec.interpret() }
});
let typing = msg.channel_id.start_typing(&ctx.http).unwrap();
let o = match join.await.unwrap() {
Ok(ok) => ok,
Err(err) => err.to_string(),
};
typing.stop();
Some(o)
}
} else {
None
};
if let Some(o) = output {
if let Err(e) = msg.channel_id.say(&ctx.http, &o).await {
if let serenity::Error::Model(Error::MessageTooLong(_)) = e {
if let Err(e) = msg
.channel_id
.send_files(&ctx.http, vec![(o.as_bytes(), "output.txt")], |m| {
m.content("Program output was too long, sending as file")
})
.await
{
println!("Error sending message: {}", e)
}
} else {
println!("Error sending message: {}", e)
}
};
}
}
async fn ready(&self, _: Context, ready: Ready) {
println!("{} is connected!", ready.user.name);
}
}
|
use crate::{
builtins::{
asyncgenerator, bool_, builtin_func, bytearray, bytes, classmethod, code, complex,
coroutine, descriptor, dict, enumerate, filter, float, frame, function, generator,
genericalias, getset, int, iter, list, map, mappingproxy, memory, module, namespace,
object, property, pystr, range, set, singletons, slice, staticmethod, super_, traceback,
tuple,
type_::{self, PyType},
union_, weakproxy, weakref, zip,
},
class::StaticType,
vm::Context,
Py,
};
/// Holder of references to builtin types.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TypeZoo {
pub async_generator: &'static Py<PyType>,
pub async_generator_asend: &'static Py<PyType>,
pub async_generator_athrow: &'static Py<PyType>,
pub async_generator_wrapped_value: &'static Py<PyType>,
pub bytes_type: &'static Py<PyType>,
pub bytes_iterator_type: &'static Py<PyType>,
pub bytearray_type: &'static Py<PyType>,
pub bytearray_iterator_type: &'static Py<PyType>,
pub bool_type: &'static Py<PyType>,
pub callable_iterator: &'static Py<PyType>,
pub cell_type: &'static Py<PyType>,
pub classmethod_type: &'static Py<PyType>,
pub code_type: &'static Py<PyType>,
pub coroutine_type: &'static Py<PyType>,
pub coroutine_wrapper_type: &'static Py<PyType>,
pub dict_type: &'static Py<PyType>,
pub enumerate_type: &'static Py<PyType>,
pub filter_type: &'static Py<PyType>,
pub float_type: &'static Py<PyType>,
pub frame_type: &'static Py<PyType>,
pub frozenset_type: &'static Py<PyType>,
pub generator_type: &'static Py<PyType>,
pub int_type: &'static Py<PyType>,
pub iter_type: &'static Py<PyType>,
pub reverse_iter_type: &'static Py<PyType>,
pub complex_type: &'static Py<PyType>,
pub list_type: &'static Py<PyType>,
pub list_iterator_type: &'static Py<PyType>,
pub list_reverseiterator_type: &'static Py<PyType>,
pub str_iterator_type: &'static Py<PyType>,
pub dict_keyiterator_type: &'static Py<PyType>,
pub dict_reversekeyiterator_type: &'static Py<PyType>,
pub dict_valueiterator_type: &'static Py<PyType>,
pub dict_reversevalueiterator_type: &'static Py<PyType>,
pub dict_itemiterator_type: &'static Py<PyType>,
pub dict_reverseitemiterator_type: &'static Py<PyType>,
pub dict_keys_type: &'static Py<PyType>,
pub dict_values_type: &'static Py<PyType>,
pub dict_items_type: &'static Py<PyType>,
pub map_type: &'static Py<PyType>,
pub memoryview_type: &'static Py<PyType>,
pub memoryviewiterator_type: &'static Py<PyType>,
pub tuple_type: &'static Py<PyType>,
pub tuple_iterator_type: &'static Py<PyType>,
pub set_type: &'static Py<PyType>,
pub set_iterator_type: &'static Py<PyType>,
pub staticmethod_type: &'static Py<PyType>,
pub super_type: &'static Py<PyType>,
pub str_type: &'static Py<PyType>,
pub range_type: &'static Py<PyType>,
pub range_iterator_type: &'static Py<PyType>,
pub long_range_iterator_type: &'static Py<PyType>,
pub slice_type: &'static Py<PyType>,
pub type_type: &'static Py<PyType>,
pub zip_type: &'static Py<PyType>,
pub function_type: &'static Py<PyType>,
pub builtin_function_or_method_type: &'static Py<PyType>,
pub builtin_method_type: &'static Py<PyType>,
pub method_descriptor_type: &'static Py<PyType>,
pub property_type: &'static Py<PyType>,
pub getset_type: &'static Py<PyType>,
pub module_type: &'static Py<PyType>,
pub namespace_type: &'static Py<PyType>,
pub bound_method_type: &'static Py<PyType>,
pub weakref_type: &'static Py<PyType>,
pub weakproxy_type: &'static Py<PyType>,
pub mappingproxy_type: &'static Py<PyType>,
pub traceback_type: &'static Py<PyType>,
pub object_type: &'static Py<PyType>,
pub ellipsis_type: &'static Py<PyType>,
pub none_type: &'static Py<PyType>,
pub not_implemented_type: &'static Py<PyType>,
pub generic_alias_type: &'static Py<PyType>,
pub union_type: &'static Py<PyType>,
pub member_descriptor_type: &'static Py<PyType>,
// RustPython-original types
pub method_def: &'static Py<PyType>,
}
impl TypeZoo {
#[cold]
pub(crate) fn init() -> Self {
let (type_type, object_type, weakref_type) = crate::object::init_type_hierarchy();
Self {
// the order matters for type, object, weakref, and int
type_type: type_::PyType::init_manually(type_type),
object_type: object::PyBaseObject::init_manually(object_type),
weakref_type: weakref::PyWeak::init_manually(weakref_type),
int_type: int::PyInt::init_builtin_type(),
// types exposed as builtins
bool_type: bool_::PyBool::init_builtin_type(),
bytearray_type: bytearray::PyByteArray::init_builtin_type(),
bytes_type: bytes::PyBytes::init_builtin_type(),
classmethod_type: classmethod::PyClassMethod::init_builtin_type(),
complex_type: complex::PyComplex::init_builtin_type(),
dict_type: dict::PyDict::init_builtin_type(),
enumerate_type: enumerate::PyEnumerate::init_builtin_type(),
float_type: float::PyFloat::init_builtin_type(),
frozenset_type: set::PyFrozenSet::init_builtin_type(),
filter_type: filter::PyFilter::init_builtin_type(),
list_type: list::PyList::init_builtin_type(),
map_type: map::PyMap::init_builtin_type(),
memoryview_type: memory::PyMemoryView::init_builtin_type(),
property_type: property::PyProperty::init_builtin_type(),
range_type: range::PyRange::init_builtin_type(),
set_type: set::PySet::init_builtin_type(),
slice_type: slice::PySlice::init_builtin_type(),
staticmethod_type: staticmethod::PyStaticMethod::init_builtin_type(),
str_type: pystr::PyStr::init_builtin_type(),
super_type: super_::PySuper::init_builtin_type(),
tuple_type: tuple::PyTuple::init_builtin_type(),
zip_type: zip::PyZip::init_builtin_type(),
// hidden internal types. is this really need to be cached here?
async_generator: asyncgenerator::PyAsyncGen::init_builtin_type(),
async_generator_asend: asyncgenerator::PyAsyncGenASend::init_builtin_type(),
async_generator_athrow: asyncgenerator::PyAsyncGenAThrow::init_builtin_type(),
async_generator_wrapped_value:
asyncgenerator::PyAsyncGenWrappedValue::init_builtin_type(),
bound_method_type: function::PyBoundMethod::init_builtin_type(),
builtin_function_or_method_type: builtin_func::PyNativeFunction::init_builtin_type(),
builtin_method_type: builtin_func::PyNativeMethod::init_builtin_type(),
bytearray_iterator_type: bytearray::PyByteArrayIterator::init_builtin_type(),
bytes_iterator_type: bytes::PyBytesIterator::init_builtin_type(),
callable_iterator: iter::PyCallableIterator::init_builtin_type(),
cell_type: function::PyCell::init_builtin_type(),
code_type: code::PyCode::init_builtin_type(),
coroutine_type: coroutine::PyCoroutine::init_builtin_type(),
coroutine_wrapper_type: coroutine::PyCoroutineWrapper::init_builtin_type(),
dict_keys_type: dict::PyDictKeys::init_builtin_type(),
dict_values_type: dict::PyDictValues::init_builtin_type(),
dict_items_type: dict::PyDictItems::init_builtin_type(),
dict_keyiterator_type: dict::PyDictKeyIterator::init_builtin_type(),
dict_reversekeyiterator_type: dict::PyDictReverseKeyIterator::init_builtin_type(),
dict_valueiterator_type: dict::PyDictValueIterator::init_builtin_type(),
dict_reversevalueiterator_type: dict::PyDictReverseValueIterator::init_builtin_type(),
dict_itemiterator_type: dict::PyDictItemIterator::init_builtin_type(),
dict_reverseitemiterator_type: dict::PyDictReverseItemIterator::init_builtin_type(),
ellipsis_type: slice::PyEllipsis::init_builtin_type(),
frame_type: crate::frame::Frame::init_builtin_type(),
function_type: function::PyFunction::init_builtin_type(),
generator_type: generator::PyGenerator::init_builtin_type(),
getset_type: getset::PyGetSet::init_builtin_type(),
iter_type: iter::PySequenceIterator::init_builtin_type(),
reverse_iter_type: enumerate::PyReverseSequenceIterator::init_builtin_type(),
list_iterator_type: list::PyListIterator::init_builtin_type(),
list_reverseiterator_type: list::PyListReverseIterator::init_builtin_type(),
mappingproxy_type: mappingproxy::PyMappingProxy::init_builtin_type(),
memoryviewiterator_type: memory::PyMemoryViewIterator::init_builtin_type(),
module_type: module::PyModule::init_builtin_type(),
namespace_type: namespace::PyNamespace::init_builtin_type(),
range_iterator_type: range::PyRangeIterator::init_builtin_type(),
long_range_iterator_type: range::PyLongRangeIterator::init_builtin_type(),
set_iterator_type: set::PySetIterator::init_builtin_type(),
str_iterator_type: pystr::PyStrIterator::init_builtin_type(),
traceback_type: traceback::PyTraceback::init_builtin_type(),
tuple_iterator_type: tuple::PyTupleIterator::init_builtin_type(),
weakproxy_type: weakproxy::PyWeakProxy::init_builtin_type(),
method_descriptor_type: descriptor::PyMethodDescriptor::init_builtin_type(),
none_type: singletons::PyNone::init_builtin_type(),
not_implemented_type: singletons::PyNotImplemented::init_builtin_type(),
generic_alias_type: genericalias::PyGenericAlias::init_builtin_type(),
union_type: union_::PyUnion::init_builtin_type(),
member_descriptor_type: descriptor::PyMemberDescriptor::init_builtin_type(),
method_def: crate::function::HeapMethodDef::init_builtin_type(),
}
}
/// Fill attributes of builtin types.
#[cold]
pub(crate) fn extend(context: &Context) {
type_::init(context);
object::init(context);
list::init(context);
set::init(context);
tuple::init(context);
dict::init(context);
builtin_func::init(context);
function::init(context);
staticmethod::init(context);
classmethod::init(context);
generator::init(context);
coroutine::init(context);
asyncgenerator::init(context);
int::init(context);
float::init(context);
complex::init(context);
bytes::init(context);
bytearray::init(context);
property::init(context);
getset::init(context);
memory::init(context);
pystr::init(context);
range::init(context);
slice::init(context);
super_::init(context);
iter::init(context);
enumerate::init(context);
filter::init(context);
map::init(context);
zip::init(context);
bool_::init(context);
code::init(context);
frame::init(context);
weakref::init(context);
weakproxy::init(context);
singletons::init(context);
module::init(context);
namespace::init(context);
mappingproxy::init(context);
traceback::init(context);
genericalias::init(context);
union_::init(context);
descriptor::init(context);
}
}
|
#[derive(Default)]
pub struct ShouldDisplayTimer(pub bool);
|
use crate::NameGenerator;
use itertools::Itertools;
use std::fmt::Write as WriteFmt;
use telamon::codegen::*;
use telamon::ir::Type;
use telamon::search_space::{DimKind, Domain};
use telamon_c::C99Display as _;
use utils::unwrap;
// TODO(cc_perf): avoid concatenating strings.
#[derive(Default)]
pub(crate) struct X86printer {
buffer: String,
}
fn param_t(param: &ParamVal) -> String {
match param {
&ParamVal::External(ref param, par_type) => {
if let Some(elem_t) = param.elem_t {
format!("{}*", elem_t.c99())
} else {
par_type.c99().to_string()
}
}
ParamVal::Size(_) => "uint32_t".to_string(),
ParamVal::GlobalMem(_, _, par_type) => format!("{}*", par_type.c99()),
}
}
impl X86printer {
/// Declares all parameters of the function with the appropriate type
fn param_decl(&self, param: &ParamVal) -> String {
format!("{} {}", param_t(param), param.key().ident())
}
/// Declared all variables that have been required from the namegen
fn var_decls(&self, namegen: &NameGenerator) -> String {
let print_decl = |(&t, &n)| {
if let Type::PtrTo(..) = t {
unreachable!("Type PtrTo are never inserted in this map");
}
let prefix = NameGenerator::gen_prefix(t);
let mut s = format!("{} ", t.c99());
s.push_str(
&(0..n)
.map(|i| format!("{}{}", prefix, i))
.collect_vec()
.join(", "),
);
s.push_str(";\n ");
s
};
let other_var_decl = namegen.num_var.iter().map(print_decl).join("\n ");
if namegen.num_glob_ptr == 0 {
other_var_decl
} else {
format!(
"intptr_t {};\n{}",
&(0..namegen.num_glob_ptr)
.map(|i| format!("ptr{}", i))
.collect_vec()
.join(", "),
other_var_decl,
)
}
}
/// Declares block and thread indexes.
fn decl_par_indexes(&self, function: &Function, name_map: &NameMap<'_>) -> String {
assert!(function.block_dims().is_empty());
let mut decls = vec![];
// Compute thread indexes.
for (ind, dim) in function.thread_dims().iter().enumerate() {
decls.push(format!(
"{} = tid.t{};\n",
name_map.name_index(dim.id()).name(),
ind
));
}
decls.join("\n ")
}
/// Prints a `Function`.
pub fn function(&mut self, function: &Function) -> String {
let mut namegen = NameGenerator::default();
let interner = Interner::default();
let name_map = &mut NameMap::new(&interner, function, &mut namegen);
// SIGNATURE AND OPEN BRACKET
let mut return_string = format!(
"void {name}(
{params}
)
{{",
name = function.name(),
params = std::iter::once("thread_dim_id_t tid".to_string())
.chain(function.device_code_args().map(|v| self.param_decl(v)),)
.join(",\n "),
);
// INDEX LOADS
let idx_loads = self.decl_par_indexes(function, name_map);
unwrap!(writeln!(self.buffer, "{}", idx_loads));
// LOAD PARAM
for val in function.device_code_args() {
let var_name = name_map.name_param_val(val.key());
unwrap!(writeln!(
self.buffer,
"{var_name} = {cast}{name}; // {param}",
cast = if val.elem_t().is_some() {
format!("({})", var_name.t().c99())
} else {
"".to_string()
},
var_name = var_name.c99(),
name = val.key().ident(),
param = val.key(),
));
}
// MEM DECL
for block in function.mem_blocks() {
match block.alloc_scheme() {
AllocationScheme::Shared => panic!("No shared mem in cpu!!"),
AllocationScheme::PrivatisedGlobal => {
Printer::new(self, name_map).privatise_global_block(block, function)
}
AllocationScheme::Global => (),
}
}
// Compute size casts
for dim in function.dimensions() {
if !dim.kind().intersects(DimKind::UNROLL | DimKind::LOOP) {
continue;
}
for level in dim.induction_levels() {
if let Some((_, ref incr)) = level.increment {
let reg = name_map.declare_size_cast(incr, level.t());
if let Some(reg) = reg {
let old_name = name_map.name_size(incr, Type::I(32));
self.print_inst(
llir::Instruction::cast(level.t(), reg, old_name)
.unwrap()
.into(),
);
}
}
}
}
// INIT
let ind_levels = function.init_induction_levels().iter().chain(
function
.block_dims()
.iter()
.flat_map(|d| d.induction_levels()),
);
for level in ind_levels {
Printer::new(self, name_map).parallel_induction_level(level);
}
// BODY
Printer::new(self, name_map).cfg(function, function.cfg());
let var_decls = self.var_decls(&namegen);
return_string.push_str(&var_decls);
return_string.push_str(&self.buffer);
// Close function bracket
return_string.push('}');
return_string
}
/// Function takes parameters as an array of void* pointers
/// This function converts back these pointers into their original types
fn fun_params_cast(&self, function: &Function) -> String {
function
.device_code_args()
.enumerate()
.map(|(i, v)| match v {
ParamVal::External(..) => format!(
" {t} {p} = *({t}*)args[{i}];",
t = param_t(v),
p = v.key().ident(),
i = i
),
ParamVal::Size(_) => format!(
" uint32_t {p} = *(uint32_t*)args[{i}];",
p = v.key().ident(),
i = i
),
// Are we sure we know the size at compile time ? I think we do
ParamVal::GlobalMem(_, _, par_type) => format!(
" {t} {p} = *({t}*)args[{i}];",
p = v.key().ident(),
t = par_type.c99(),
i = i
),
})
.join("\n")
}
/// Helper for building a structure containing as many thread ids (one id per dim) as required.
fn build_thread_id_struct(&self, func: &Function) -> String {
if func.thread_dims().is_empty() {
"".to_string()
} else {
format!(
"int {};\n",
(0..func.thread_dims().len())
.format_with(", ", |idx, f| f(&format_args!("t{}", idx)))
)
}
}
/// Prints code that generates the required number of threads, stores the handles in an array
fn thread_gen(&self, func: &Function) -> String {
let loop_decl =
func.thread_dims()
.iter()
.enumerate()
.format_with("\n", |(idx, dim), f| {
f(&format_args!(
"for (int d{idx} = 0; d{idx} < {size}; ++d{idx})",
idx = idx,
size = dim.size().as_int().unwrap(),
))
});
format!(
"pthread_t thread_ids[{num_threads}];
thread_arg_t thread_args[{num_threads}];
pthread_barrier_t barrier;
pthread_barrier_init(&barrier, NULL, {num_threads});
{loop_decl}
{{
size_t tid = {tid};
thread_args[tid].args = args;
{tid_struct}
thread_args[tid].tid.barrier = &barrier;
pthread_create(&thread_ids[tid], NULL, exec_wrap, (void *)&thread_args[tid]);
}}
for (size_t tid = 0; tid < {num_threads}; ++tid) {{
pthread_join(thread_ids[tid], NULL);
}}
pthread_barrier_destroy(&barrier);
",
num_threads = func.num_threads(),
// Build the right call for a nested loop on dimensions with linearized accesses that
// is, for a 3 dimensions arrays a[2][5][3] returns d0 + 3 * (d1 + 5 * (d2 + 2 * (0)))
tid = format!(
"{}0{}",
func.thread_dims()
.iter()
.enumerate()
.format_with("", |(idx, dim), f| {
f(&format_args!(
"d{} + {} * (",
idx,
dim.size().as_int().unwrap()
))
}),
")".repeat(func.thread_dims().len())
),
loop_decl = loop_decl,
tid_struct = (0..func.thread_dims().len()).format_with(" ", |idx, f| {
f(&format_args!(
"thread_args[tid].tid.t{idx} = d{idx};\n",
idx = idx,
))
}),
)
}
/// wrap the kernel call into a function with a fixed interface
pub fn wrapper_function(&mut self, func: &Function) -> String {
let fun_str = self.function(func);
format!(
include_str!("template/host.c.template"),
fun_name = func.name(),
fun_str = fun_str,
fun_params_cast = self.fun_params_cast(func),
// The first comma is for the `tid` argument
fun_params = func
.device_code_args()
.format_with("", |p, f| f(&format_args!(", {}", p.key().ident()))),
entry_point = self.thread_gen(func),
dim_decl = self.build_thread_id_struct(func),
)
}
}
impl InstPrinter for X86printer {
fn print_label(&mut self, label: llir::Label<'_>) {
writeln!(self.buffer, "{}", label.c99()).unwrap()
}
fn print_inst(&mut self, inst: llir::PredicatedInstruction<'_>) {
writeln!(self.buffer, "{}", inst.c99()).unwrap();
}
}
|
fn main() {
let args = libtest_mimic::Arguments::from_args();
std::env::set_current_dir("..").unwrap();
let tests = std::iter::empty()
.chain(pikelet_test::walk_files("examples").filter_map(pikelet_test::extract_simple_test))
.chain(pikelet_test::walk_files("tests").filter_map(pikelet_test::extract_config_test))
.collect();
let run_test = pikelet_test::run_test(env!("CARGO_BIN_EXE_pikelet"));
libtest_mimic::run_tests(&args, tests, run_test).exit();
}
|
use crate::asset::{material, mesh, model};
use crate::gl::tex;
use crate::helpers::loader;
use crate::math;
use std::path::Path;
use std::sync::Arc;
pub fn calculate_tangents_and_bitangents(
indices: &mesh::Indices,
vertices: &mesh::Vertices,
uvs: &mesh::UVs,
) -> (mesh::Tangents, mesh::Bitangents) {
let mut tangents = mesh::Tangents::new();
let mut bitangents = mesh::Bitangents::new();
for i in (0..indices.len()).step_by(3) {
let vert0 = &vertices[indices[i + 0].x as usize];
let vert1 = &vertices[indices[i + 1].x as usize];
let vert2 = &vertices[indices[i + 2].x as usize];
let uv0 = &uvs[indices[i + 0].x as usize];
let uv1 = &uvs[indices[i + 1].x as usize];
let uv2 = &uvs[indices[i + 2].x as usize];
let delta_pos1 = *vert1 - *vert0;
let delta_pos2 = *vert2 - *vert0;
let delta_uv1 = *uv1 - *uv0;
let delta_uv2 = *uv2 - *uv0;
let r = 1.0 / (delta_uv1.x * delta_uv2.y - delta_uv1.y * delta_uv2.x);
let tangent =
math::normalize_vec3((delta_pos1 * delta_uv2.y - delta_pos2 * delta_uv1.y) * r);
let bitangent =
math::normalize_vec3((delta_pos2 * delta_uv1.x - delta_pos1 * delta_uv2.x) * r);
// if tangent.x.is_nan() || tangent.y.is_nan() || tangent.z.is_nan() {
// let pass = 0;
// }
// if bitangent.x.is_nan() || bitangent.y.is_nan() || bitangent.z.is_nan() {
// let pass = 0;
// }
// assert!(
// !tangent.x.is_nan() && !tangent.y.is_nan() && !tangent.z.is_nan(),
// "Nan tangent!"
// );
// assert!(
// !bitangent.x.is_nan() && !bitangent.y.is_nan() && !bitangent.z.is_nan(),
// "Nan bitangent!"
// );
tangents.push(tangent);
tangents.push(tangent);
tangents.push(tangent);
bitangents.push(bitangent);
bitangents.push(bitangent);
bitangents.push(bitangent);
}
return (tangents, bitangents);
}
#[allow(dead_code)]
pub fn create_host_triangle_model() -> mesh::HostMesh {
let vertices: Vec<math::Vec3f> = vec![
math::Vec3::new(-1.0, -1.0, 0.5),
math::Vec3::new(1.0, -1.0, 0.5),
math::Vec3::new(0.0, 1.0, 0.5),
];
let normals = vec![
math::Vec3::new(0.0, 0.0, 1.0),
math::Vec3::new(0.0, 0.0, 1.0),
math::Vec3::new(0.0, 0.0, 1.0),
];
let uvs = vec![
math::Vec2 { x: 0.0, y: 0.0 },
math::Vec2 { x: 1.0, y: 0.0 },
math::Vec2 { x: 0.5, y: 1.0 },
];
let indices = vec![
math::Vec1u::new(0),
math::Vec1u::new(1),
math::Vec1u::new(2),
];
let (tangents, bitangents) = calculate_tangents_and_bitangents(&indices, &vertices, &uvs);
mesh::HostMesh::new(
"Triangle".to_string(),
0,
vertices,
normals,
tangents,
bitangents,
uvs,
indices,
)
}
pub fn create_full_screen_triangle_host_mesh() -> mesh::HostMesh {
let vertices: Vec<math::Vec3f> = vec![
math::Vec3::new(-1.0, -1.0, 0.5),
math::Vec3::new(3.0, -1.0, 0.5),
math::Vec3::new(-1.0, 3.0, 0.5),
];
let normals = vec![
math::Vec3::new(0.0, 0.0, 1.0),
math::Vec3::new(0.0, 0.0, 1.0),
math::Vec3::new(0.0, 0.0, 1.0),
];
let uvs = vec![
math::Vec2::new(0.0, 0.0),
math::Vec2::new(2.0, 0.0),
math::Vec2::new(0.0, 2.0),
];
let indices = vec![
math::Vec1u { x: 0u32 },
math::Vec1u { x: 1u32 },
math::Vec1u { x: 2u32 },
];
let (tangents, bitangents) = calculate_tangents_and_bitangents(&indices, &vertices, &uvs);
mesh::HostMesh::new(
"Triangle".to_string(),
0,
vertices,
normals,
tangents,
bitangents,
uvs,
indices,
)
}
pub fn create_full_screen_triangle_model() -> model::DeviceModel {
model::DeviceModel::new(&model::HostModel {
meshes: Arc::new(vec![create_full_screen_triangle_host_mesh()]),
materials: Arc::new(vec![material::HostMaterial::empty()]),
})
}
#[allow(dead_code)]
pub fn load_wall() -> model::DeviceModel {
let mut device_model =
loader::load_device_model_from_obj(Path::new("data/models/quad/quad.obj"));
device_model.materials[0]
.set_svec1f("uScalarRoughnessVec1f", math::Vec1f::new(1.))
.unwrap();
device_model.materials[0]
.set_svec1f("uScalarMetalnessVec1f", math::Vec1f::new(0.))
.unwrap();
device_model.materials[0]
.set_svec3f("uScalarAlbedoVec3f", math::Vec3f::new(1., 1., 1.))
.unwrap();
device_model
}
#[allow(dead_code)]
pub fn load_studio() -> (model::DeviceModel, Vec<math::Mat4x4f>) {
let mut device_model =
loader::load_device_model_from_obj(Path::new("data/models/studio/studio.obj"));
device_model.materials[0]
.set_svec1f("uScalarRoughnessVec1f", math::Vec1f::new(1.))
.unwrap();
device_model.materials[0]
.set_svec1f("uScalarMetalnessVec1f", math::Vec1f::new(0.))
.unwrap();
device_model.materials[0]
.set_svec3f("uScalarAlbedoVec3f", math::Vec3f::new(1., 1., 1.))
.unwrap();
let trasforms = vec![
math::x_rotation_mat4x4(3.14_f32),
math::x_rotation_mat4x4(3.14_f32),
];
(device_model, trasforms)
}
#[allow(dead_code)]
pub fn load_well() -> (model::DeviceModel, Vec<math::Mat4x4f>) {
let mut device_model =
loader::load_device_model_from_obj(Path::new("data/models/well/well.obj"));
device_model.materials[0]
.set_svec1f("uScalarRoughnessVec1f", math::Vec1f::new(1.))
.unwrap();
device_model.materials[0]
.set_svec1f("uScalarMetalnessVec1f", math::Vec1f::new(0.))
.unwrap();
device_model.materials[0]
.set_svec3f("uScalarAlbedoVec3f", math::Vec3f::new(0., 0., 0.))
.unwrap();
let trasforms = vec![math::Mat4x4f::identity()];
(device_model, trasforms)
}
#[allow(dead_code)]
pub fn load_cylinder() -> (model::DeviceModel, Vec<math::Mat4x4f>) {
let mut device_model =
loader::load_device_model_from_obj(Path::new("data/models/cylinder/cylinder.obj"));
device_model.materials[0]
.set_svec1f("uScalarRoughnessVec1f", math::Vec1f::new(0.))
.unwrap();
device_model.materials[0]
.set_svec1f("uScalarMetalnessVec1f", math::Vec1f::new(0.))
.unwrap();
device_model.materials[0]
.set_svec3f("uScalarAlbedoVec3f", math::Vec3f::new(0., 0., 0.))
.unwrap();
let trasforms = vec![
math::tranlation_mat4x4(math::Vec3f::new(0., 0., 0.))
* math::scale_mat4x4(math::Vec3f::new(100., 100., 100.)),
];
(device_model, trasforms)
}
// #[allow(dead_code)]
// pub fn load_pbr_sphere() -> (model::DeviceModel, Vec<math::Mat4x4f>) {
// let mut device_model =
// loader::load_device_model_from_obj(Path::new("data/models/pbr-sphere/sphere.obj"));
// let mesh = device_model.meshes[0].clone();
// let mut material = device_model.materials[0].clone();
// material
// .set_svec3f("uScalarAlbedoVec3f", math::Vec3f::new(1., 1., 1.))
// .unwrap();
// material.properties_3f[0].value.data_location.data[0] = math::Vec3f::new(1., 1., 1.);
// let mut transforms = Vec::new();
// device_model.meshes.clear();
// device_model.materials.clear();
// for x in (-10..12).step_by(2) {
// for y in (-10..12).step_by(2) {
// let mut material = material.clone();
// let roughness = (x + 10) as f32 / 20.;
// let metalness = (y + 10) as f32 / 20.;
// material
// .set_svec1f("uScalarRoughnessVec1f", math::Vec1f::new(roughness))
// .unwrap();
// material
// .set_svec1f("uScalarMetalnessVec1f", math::Vec1f::new(metalness))
// .unwrap();
// device_model.materials.push(material);
// let mut mesh = mesh.clone();
// mesh.material_index = device_model.materials.len() - 1;
// device_model.meshes.push(mesh.clone());
// transforms.push(math::tranlation_mat4x4(math::Vec3f {
// x: x as f32,
// y: y as f32,
// z: 0.,
// }));
// }
// }
// (device_model, transforms)
// }
#[allow(dead_code)]
pub fn load_pbr_spheres() -> (model::DeviceModel, Vec<math::Mat4x4f>) {
let device_model =
loader::load_device_model_from_obj(Path::new("data/models/pbr-spheres/spheres.obj"));
let transforms = vec![
math::tranlation_mat4x4(math::Vec3f::new(-25., -25., -65.));
device_model.meshes.len()
];
(device_model, transforms)
}
#[allow(dead_code)]
pub fn load_skybox() -> model::DeviceModel {
let mut box_model = loader::load_device_model_from_obj(Path::new("data/models/box/box.obj"));
box_model.materials = vec![material::DeviceMaterial::empty()];
box_model
}
#[allow(dead_code)]
pub fn load_hdri_texture() -> tex::HostTexture {
loader::load_host_texture_from_file(
&Path::new("data/materials/hdri/quattro_canti/quattro_canti_8k.hdr"),
"uHdriSampler2D",
)
.unwrap()
}
#[allow(dead_code)]
pub fn load_sponza() -> (model::DeviceModel, Vec<math::Mat4x4f>) {
let device_model =
loader::load_device_model_from_obj(Path::new("data/models/Sponza/sponza.obj"));
let transforms = vec![math::Mat4x4f::identity(); device_model.meshes.len()];
(device_model, transforms)
}
#[allow(dead_code)]
pub fn load_bistro_exterior() -> (model::DeviceModel, Vec<math::Mat4x4f>) {
let device_model =
loader::load_device_model_from_obj(Path::new("data/models/bistro/bistro.obj"));
let transforms = vec![math::Mat4x4f::identity(); device_model.meshes.len()];
(device_model, transforms)
}
|
use std::{fs::File, io::Write};
use anyhow::Result;
use bookfile::{BookWriter, BoundedReader, ChapterId, ChapterWriter};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct BlobRange {
offset: u64,
size: usize,
}
pub fn read_blob(reader: &BoundedReader<&'_ File>, range: &BlobRange) -> Result<Vec<u8>> {
let mut buf = vec![0u8; range.size];
reader.read_exact_at(&mut buf, range.offset)?;
Ok(buf)
}
pub struct BlobWriter<W> {
writer: ChapterWriter<W>,
offset: u64,
}
impl<W: Write> BlobWriter<W> {
// This function takes a BookWriter and creates a new chapter to ensure offset is 0.
pub fn new(book_writer: BookWriter<W>, chapter_id: impl Into<ChapterId>) -> Self {
let writer = book_writer.new_chapter(chapter_id);
Self { writer, offset: 0 }
}
pub fn write_blob(&mut self, blob: &[u8]) -> Result<BlobRange> {
self.writer.write_all(blob)?;
let range = BlobRange {
offset: self.offset,
size: blob.len(),
};
self.offset += blob.len() as u64;
Ok(range)
}
pub fn close(self) -> bookfile::Result<BookWriter<W>> {
self.writer.close()
}
}
|
use core::slice;
pub struct Bytes<'a> {
slice: &'a [u8],
pos: usize
}
impl<'a> Bytes<'a> {
#[inline]
pub fn new(slice: &'a [u8]) -> Bytes<'a> {
Bytes {
slice: slice,
pos: 0
}
}
#[inline]
pub fn pos(&self) -> usize {
self.pos
}
#[inline]
pub fn peek(&self) -> Option<u8> {
self.slice.get(self.pos).cloned()
}
#[inline]
pub unsafe fn bump(&mut self) {
debug_assert!(self.pos + 1 <= self.slice.len(), "overflow");
self.pos += 1;
}
#[allow(unused)]
#[inline]
pub unsafe fn advance(&mut self, n: usize) {
debug_assert!(self.pos + n <= self.slice.len(), "overflow");
self.pos += n;
}
#[inline]
pub fn len(&self) -> usize {
self.slice.len()
}
#[inline]
pub fn slice(&mut self) -> &'a [u8] {
// not moving position at all, so it's safe
unsafe {
self.slice_skip(0)
}
}
#[inline]
pub unsafe fn slice_skip(&mut self, skip: usize) -> &'a [u8] {
debug_assert!(self.pos >= skip);
let head_pos = self.pos - skip;
let ptr = self.slice.as_ptr();
let head = slice::from_raw_parts(ptr, head_pos);
let tail = slice::from_raw_parts(ptr.offset(self.pos as isize), self.slice.len() - self.pos);
self.pos = 0;
self.slice = tail;
head
}
#[inline]
pub fn next_8<'b>(&'b mut self) -> Option<Bytes8<'b, 'a>> {
if self.slice.len() > self.pos + 8 {
Some(Bytes8::new(self))
} else {
None
}
}
}
impl<'a> AsRef<[u8]> for Bytes<'a> {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.slice[self.pos..]
}
}
impl<'a> Iterator for Bytes<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
if self.slice.len() > self.pos {
let b = unsafe { *self.slice.get_unchecked(self.pos) };
self.pos += 1;
Some(b)
} else {
None
}
}
}
pub struct Bytes8<'a, 'b: 'a> {
bytes: &'a mut Bytes<'b>,
#[cfg(debug_assertions)]
pos: usize
}
macro_rules! bytes8_methods {
($f:ident, $pos:expr) => {
#[inline]
pub fn $f(&mut self) -> u8 {
self.assert_pos($pos);
let b = unsafe { *self.bytes.slice.get_unchecked(self.bytes.pos) };
self.bytes.pos += 1;
b
}
};
() => {
bytes8_methods!(_0, 0);
bytes8_methods!(_1, 1);
bytes8_methods!(_2, 2);
bytes8_methods!(_3, 3);
bytes8_methods!(_4, 4);
bytes8_methods!(_5, 5);
bytes8_methods!(_6, 6);
bytes8_methods!(_7, 7);
}
}
impl<'a, 'b: 'a> Bytes8<'a, 'b> {
bytes8_methods! {}
#[cfg(not(debug_assertions))]
#[inline]
fn new(bytes: &'a mut Bytes<'b>) -> Bytes8<'a, 'b> {
Bytes8 {
bytes: bytes,
}
}
#[cfg(debug_assertions)]
#[inline]
fn new(bytes: &'a mut Bytes<'b>) -> Bytes8<'a, 'b> {
Bytes8 {
bytes: bytes,
pos: 0,
}
}
#[cfg(not(debug_assertions))]
#[inline]
fn assert_pos(&mut self, _pos: usize) {
}
#[cfg(debug_assertions)]
#[inline]
fn assert_pos(&mut self, pos: usize) {
assert!(self.pos == pos);
self.pos += 1;
}
}
|
#[test]
fn vec_as_ptr() {
let vec: Vec<u8> = vec![10, 20, 30];
let ptr = vec.as_ptr();
let first_ptr: *const u8 = ptr;
let second_ptr: *const u8 = unsafe { ptr.offset(1) };
let third_ptr: *const u8 = unsafe { ptr.offset(2) };
assert_eq!(10, unsafe { *first_ptr });
assert_eq!(20, unsafe { *second_ptr });
assert_eq!(30, unsafe { *third_ptr });
}
#[test]
fn vec_as_mut_ptr() {
let mut vec: Vec<u8> = vec![10, 20];
let first_ptr: *mut u8 = vec.as_mut_ptr();
let second_ptr: *mut u8;
unsafe {
*first_ptr = 30;
second_ptr = first_ptr.offset(1);
*second_ptr = 40;
}
assert_eq!(30, unsafe { *first_ptr });
assert_eq!(40, unsafe { *second_ptr });
}
|
use core::{mem, ptr};
use uefi::memory::{MemoryDescriptor, MemoryType};
static MM_BASE: u64 = 0x500;
static MM_SIZE: u64 = 0x4B00;
/// Memory does not exist
pub const MEMORY_AREA_NULL: u32 = 0;
/// Memory is free to use
pub const MEMORY_AREA_FREE: u32 = 1;
/// Memory is reserved
pub const MEMORY_AREA_RESERVED: u32 = 2;
/// Memory is used by ACPI, and can be reclaimed
pub const MEMORY_AREA_ACPI: u32 = 3;
/// A memory map area
#[derive(Copy, Clone, Debug, Default)]
#[repr(packed)]
pub struct MemoryArea {
pub base_addr: u64,
pub length: u64,
pub _type: u32,
pub acpi: u32
}
pub unsafe fn memory_map() -> usize {
let uefi = std::system_table();
ptr::write_bytes(MM_BASE as *mut u8, 0, MM_SIZE as usize);
let mut map: [u8; 65536] = [0; 65536];
let mut map_size = map.len();
let mut map_key = 0;
let mut descriptor_size = 0;
let mut descriptor_version = 0;
let _ = (uefi.BootServices.GetMemoryMap)(
&mut map_size,
map.as_mut_ptr() as *mut MemoryDescriptor,
&mut map_key,
&mut descriptor_size,
&mut descriptor_version
);
if descriptor_size >= mem::size_of::<MemoryDescriptor>() {
for i in 0..map_size/descriptor_size {
let descriptor_ptr = map.as_ptr().offset((i * descriptor_size) as isize);
let descriptor = & *(descriptor_ptr as *const MemoryDescriptor);
let descriptor_type: MemoryType = mem::transmute(descriptor.Type);
let bios_type = match descriptor_type {
MemoryType::EfiLoaderCode |
MemoryType::EfiLoaderData |
MemoryType::EfiBootServicesCode |
MemoryType::EfiBootServicesData |
MemoryType::EfiConventionalMemory => {
MEMORY_AREA_FREE
},
_ => {
MEMORY_AREA_RESERVED
}
};
let bios_area = MemoryArea {
base_addr: descriptor.PhysicalStart.0,
length: descriptor.NumberOfPages * 4096,
_type: bios_type,
acpi: 0,
};
ptr::write((MM_BASE as *mut MemoryArea).offset(i as isize), bios_area);
}
} else {
println!("Unknown memory descriptor size: {}", descriptor_size);
}
map_key
}
|
use std::collections::HashMap;
use std::env;
use std::fs;
use std::iter::Peekable;
#[derive(Debug)]
pub struct CType {
name: String,
forms: HashMap<String, Vec<String>>,
}
struct Parser<P> {
state: P,
}
impl<I: Iterator<Item = char>> Parser<Peekable<I>> {
pub fn new(state: Peekable<I>) -> Parser<Peekable<I>> {
Parser { state }
}
fn eat(&mut self, ch: char) {
assert_eq!(self.state.next(), Some(ch))
}
fn skip(&mut self) {
self.state.next().expect("unexpected end of file");
}
fn peek(&mut self) -> char {
*self.state.peek().expect("unexpected end of file")
}
fn skip_whitespace(&mut self) {
while let Some(true) = self.state.peek().map(|c| c.is_whitespace()) {
self.skip();
}
}
fn is_finished(&mut self) -> bool {
self.skip_whitespace();
self.state.peek().is_none()
}
pub fn parse_word(&mut self) -> String {
let mut word = String::new();
self.skip_whitespace();
loop {
let ch = self.peek();
if ch == ')' || ch.is_whitespace() {
return word;
} else {
self.skip();
word.push(ch);
}
}
}
pub fn parse_cform(&mut self) -> (String, String) {
self.skip_whitespace();
self.eat('(');
let name = self.parse_word();
let form = self.parse_word();
let _ = self.parse_word();
self.skip_whitespace();
if self.peek() != ')' {
let _ = self.parse_word();
}
self.skip_whitespace();
self.eat(')');
(name, form)
}
pub fn parse_ctype(&mut self) -> CType {
self.skip_whitespace();
self.eat('(');
let name = self.parse_word();
eprintln!("reading {}", name);
let mut forms = HashMap::new();
loop {
self.skip_whitespace();
match self.peek() {
')' => break,
'(' => {
let (name, form) = self.parse_cform();
forms.entry(name).or_insert_with(|| Vec::new()).push(form);
}
_ => panic!("unexpected word occurence"),
}
}
self.skip_whitespace();
self.eat(')');
CType { name, forms }
}
}
pub fn print_match(ctypes: &[CType]) {
println!("match #matcher# {{");
for ctype in ctypes {
for (name, cforms) in &ctype.forms {
println!(
" Conjugation::#{ctype}#(#{ctype}#::#{cform}#) => &{form:?} as &[&'static str],",
ctype = ctype.name,
cform = name,
form = cforms
);
}
}
println!("}}")
}
fn main() {
let file_name = env::args().nth(1).unwrap();
let content = fs::read_to_string(file_name).unwrap();
let mut parser = Parser::new(content.chars().peekable());
let mut ctypes = Vec::new();
while !parser.is_finished() {
ctypes.push(parser.parse_ctype());
}
print_match(&ctypes);
}
|
use crate::config_cmd::ConfigCmd;
use crate::auth::Auth;
use crate::configuration::Configuration;
use crate::configuration::DEFAULT_PROFILE;
type Error = Box<dyn std::error::Error>;
type Result<T, E = Error> = std::result::Result<T, E>;
pub fn call(form : ConfigCmd) -> Result<()> {
match form {
ConfigCmd::Set{auth_profile, auth_token, auth_secret_key} => {
let profile_key = match auth_profile {
Some(profile) => profile,
None => String::from(DEFAULT_PROFILE)
};
Configuration::store(profile_key,Auth {token : auth_token, secret_key : auth_secret_key})
},
ConfigCmd::ShowFile=>
Ok(println!("{}", Configuration::get_config_file_path().to_str().expect("Error Reading config file.")))
}
} |
#[doc = "Reader of register CSR"]
pub type R = crate::R<u32, super::CSR>;
#[doc = "Writer for register CSR"]
pub type W = crate::W<u32, super::CSR>;
#[doc = "Register CSR `reset()`'s with value 0"]
impl crate::ResetValue for super::CSR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Enable WKUP pin 2\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EWUP2_A {
#[doc = "0: WKUP pin 2 is used for general purpose I/Os. An event on the WKUP pin 2 does not wakeup the device from Standby mode"]
DISABLED = 0,
#[doc = "1: WKUP pin 2 is used for wakeup from Standby mode and forced in input pull down configuration (rising edge on WKUP pin 2 wakes-up the system from Standby mode)"]
ENABLED = 1,
}
impl From<EWUP2_A> for bool {
#[inline(always)]
fn from(variant: EWUP2_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EWUP2`"]
pub type EWUP2_R = crate::R<bool, EWUP2_A>;
impl EWUP2_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EWUP2_A {
match self.bits {
false => EWUP2_A::DISABLED,
true => EWUP2_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EWUP2_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EWUP2_A::ENABLED
}
}
#[doc = "Write proxy for field `EWUP2`"]
pub struct EWUP2_W<'a> {
w: &'a mut W,
}
impl<'a> EWUP2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EWUP2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "WKUP pin 2 is used for general purpose I/Os. An event on the WKUP pin 2 does not wakeup the device from Standby mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EWUP2_A::DISABLED)
}
#[doc = "WKUP pin 2 is used for wakeup from Standby mode and forced in input pull down configuration (rising edge on WKUP pin 2 wakes-up the system from Standby mode)"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EWUP2_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Enable WKUP pin 1\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EWUP1_A {
#[doc = "0: WKUP pin 1 is used for general purpose I/Os. An event on the WKUP pin 1 does not wakeup the device from Standby mode"]
DISABLED = 0,
#[doc = "1: WKUP pin 1 is used for wakeup from Standby mode and forced in input pull down configuration (rising edge on WKUP pin 1 wakes-up the system from Standby mode)"]
ENABLED = 1,
}
impl From<EWUP1_A> for bool {
#[inline(always)]
fn from(variant: EWUP1_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EWUP1`"]
pub type EWUP1_R = crate::R<bool, EWUP1_A>;
impl EWUP1_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EWUP1_A {
match self.bits {
false => EWUP1_A::DISABLED,
true => EWUP1_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EWUP1_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EWUP1_A::ENABLED
}
}
#[doc = "Write proxy for field `EWUP1`"]
pub struct EWUP1_W<'a> {
w: &'a mut W,
}
impl<'a> EWUP1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EWUP1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "WKUP pin 1 is used for general purpose I/Os. An event on the WKUP pin 1 does not wakeup the device from Standby mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EWUP1_A::DISABLED)
}
#[doc = "WKUP pin 1 is used for wakeup from Standby mode and forced in input pull down configuration (rising edge on WKUP pin 1 wakes-up the system from Standby mode)"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EWUP1_A::ENABLED)
}
#[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
}
}
#[doc = "Internal voltage reference ready flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VREFINTRDYF_A {
#[doc = "0: VREFINT is OFF"]
NOTREADY = 0,
#[doc = "1: VREFINT is ready"]
READY = 1,
}
impl From<VREFINTRDYF_A> for bool {
#[inline(always)]
fn from(variant: VREFINTRDYF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `VREFINTRDYF`"]
pub type VREFINTRDYF_R = crate::R<bool, VREFINTRDYF_A>;
impl VREFINTRDYF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VREFINTRDYF_A {
match self.bits {
false => VREFINTRDYF_A::NOTREADY,
true => VREFINTRDYF_A::READY,
}
}
#[doc = "Checks if the value of the field is `NOTREADY`"]
#[inline(always)]
pub fn is_not_ready(&self) -> bool {
*self == VREFINTRDYF_A::NOTREADY
}
#[doc = "Checks if the value of the field is `READY`"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
*self == VREFINTRDYF_A::READY
}
}
#[doc = "PVD output\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PVDO_A {
#[doc = "0: VDD is higher than the PVD threshold selected with the PLS\\[2:0\\]
bits"]
ABOVETHRESHOLD = 0,
#[doc = "1: VDD is lower than the PVD threshold selected with the PLS\\[2:0\\]
bits"]
BELOWTHRESHOLD = 1,
}
impl From<PVDO_A> for bool {
#[inline(always)]
fn from(variant: PVDO_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `PVDO`"]
pub type PVDO_R = crate::R<bool, PVDO_A>;
impl PVDO_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> PVDO_A {
match self.bits {
false => PVDO_A::ABOVETHRESHOLD,
true => PVDO_A::BELOWTHRESHOLD,
}
}
#[doc = "Checks if the value of the field is `ABOVETHRESHOLD`"]
#[inline(always)]
pub fn is_above_threshold(&self) -> bool {
*self == PVDO_A::ABOVETHRESHOLD
}
#[doc = "Checks if the value of the field is `BELOWTHRESHOLD`"]
#[inline(always)]
pub fn is_below_threshold(&self) -> bool {
*self == PVDO_A::BELOWTHRESHOLD
}
}
#[doc = "Standby flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SBF_A {
#[doc = "0: Device has not been in Standby mode"]
NOSTANDBYEVENT = 0,
#[doc = "1: Device has been in Standby mode"]
STANDBYEVENT = 1,
}
impl From<SBF_A> for bool {
#[inline(always)]
fn from(variant: SBF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SBF`"]
pub type SBF_R = crate::R<bool, SBF_A>;
impl SBF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SBF_A {
match self.bits {
false => SBF_A::NOSTANDBYEVENT,
true => SBF_A::STANDBYEVENT,
}
}
#[doc = "Checks if the value of the field is `NOSTANDBYEVENT`"]
#[inline(always)]
pub fn is_no_standby_event(&self) -> bool {
*self == SBF_A::NOSTANDBYEVENT
}
#[doc = "Checks if the value of the field is `STANDBYEVENT`"]
#[inline(always)]
pub fn is_standby_event(&self) -> bool {
*self == SBF_A::STANDBYEVENT
}
}
#[doc = "Wakeup flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WUF_A {
#[doc = "0: No wakeup event occurred"]
NOWAKEUPEVENT = 0,
#[doc = "1: A wakeup event was received from the WKUP pin or from the RTC alarm (Alarm A or Alarm B), RTC Tamper event, RTC TimeStamp event or RTC Wakeup)"]
WAKEUPEVENT = 1,
}
impl From<WUF_A> for bool {
#[inline(always)]
fn from(variant: WUF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `WUF`"]
pub type WUF_R = crate::R<bool, WUF_A>;
impl WUF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> WUF_A {
match self.bits {
false => WUF_A::NOWAKEUPEVENT,
true => WUF_A::WAKEUPEVENT,
}
}
#[doc = "Checks if the value of the field is `NOWAKEUPEVENT`"]
#[inline(always)]
pub fn is_no_wakeup_event(&self) -> bool {
*self == WUF_A::NOWAKEUPEVENT
}
#[doc = "Checks if the value of the field is `WAKEUPEVENT`"]
#[inline(always)]
pub fn is_wakeup_event(&self) -> bool {
*self == WUF_A::WAKEUPEVENT
}
}
#[doc = "Voltage Scaling select flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VOSF_A {
#[doc = "0: Regulator is ready in the selected voltage range"]
READY = 0,
#[doc = "1: Regulator voltage output is changing to the required VOS level"]
NOTREADY = 1,
}
impl From<VOSF_A> for bool {
#[inline(always)]
fn from(variant: VOSF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `VOSF`"]
pub type VOSF_R = crate::R<bool, VOSF_A>;
impl VOSF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VOSF_A {
match self.bits {
false => VOSF_A::READY,
true => VOSF_A::NOTREADY,
}
}
#[doc = "Checks if the value of the field is `READY`"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
*self == VOSF_A::READY
}
#[doc = "Checks if the value of the field is `NOTREADY`"]
#[inline(always)]
pub fn is_not_ready(&self) -> bool {
*self == VOSF_A::NOTREADY
}
}
#[doc = "Regulator LP flag\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum REGLPF_A {
#[doc = "0: Regulator is ready in Main mode"]
READY = 0,
#[doc = "1: Regulator voltage is in low-power mode"]
NOTREADY = 1,
}
impl From<REGLPF_A> for bool {
#[inline(always)]
fn from(variant: REGLPF_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `REGLPF`"]
pub type REGLPF_R = crate::R<bool, REGLPF_A>;
impl REGLPF_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> REGLPF_A {
match self.bits {
false => REGLPF_A::READY,
true => REGLPF_A::NOTREADY,
}
}
#[doc = "Checks if the value of the field is `READY`"]
#[inline(always)]
pub fn is_ready(&self) -> bool {
*self == REGLPF_A::READY
}
#[doc = "Checks if the value of the field is `NOTREADY`"]
#[inline(always)]
pub fn is_not_ready(&self) -> bool {
*self == REGLPF_A::NOTREADY
}
}
#[doc = "Enable WKUP pin 3\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EWUP3_A {
#[doc = "0: WKUP pin 3 is used for general purpose I/Os. An event on the WKUP pin 3 does not wakeup the device from Standby mode"]
DISABLED = 0,
#[doc = "1: WKUP pin 3 is used for wakeup from Standby mode and forced in input pull down configuration (rising edge on WKUP pin 3wakes-up the system from Standby mode)"]
ENABLED = 1,
}
impl From<EWUP3_A> for bool {
#[inline(always)]
fn from(variant: EWUP3_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `EWUP3`"]
pub type EWUP3_R = crate::R<bool, EWUP3_A>;
impl EWUP3_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EWUP3_A {
match self.bits {
false => EWUP3_A::DISABLED,
true => EWUP3_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == EWUP3_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == EWUP3_A::ENABLED
}
}
#[doc = "Write proxy for field `EWUP3`"]
pub struct EWUP3_W<'a> {
w: &'a mut W,
}
impl<'a> EWUP3_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EWUP3_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "WKUP pin 3 is used for general purpose I/Os. An event on the WKUP pin 3 does not wakeup the device from Standby mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(EWUP3_A::DISABLED)
}
#[doc = "WKUP pin 3 is used for wakeup from Standby mode and forced in input pull down configuration (rising edge on WKUP pin 3wakes-up the system from Standby mode)"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(EWUP3_A::ENABLED)
}
#[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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
impl R {
#[doc = "Bit 9 - Enable WKUP pin 2"]
#[inline(always)]
pub fn ewup2(&self) -> EWUP2_R {
EWUP2_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 8 - Enable WKUP pin 1"]
#[inline(always)]
pub fn ewup1(&self) -> EWUP1_R {
EWUP1_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 3 - Internal voltage reference ready flag"]
#[inline(always)]
pub fn vrefintrdyf(&self) -> VREFINTRDYF_R {
VREFINTRDYF_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 2 - PVD output"]
#[inline(always)]
pub fn pvdo(&self) -> PVDO_R {
PVDO_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 1 - Standby flag"]
#[inline(always)]
pub fn sbf(&self) -> SBF_R {
SBF_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - Wakeup flag"]
#[inline(always)]
pub fn wuf(&self) -> WUF_R {
WUF_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 4 - Voltage Scaling select flag"]
#[inline(always)]
pub fn vosf(&self) -> VOSF_R {
VOSF_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Regulator LP flag"]
#[inline(always)]
pub fn reglpf(&self) -> REGLPF_R {
REGLPF_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 10 - Enable WKUP pin 3"]
#[inline(always)]
pub fn ewup3(&self) -> EWUP3_R {
EWUP3_R::new(((self.bits >> 10) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 9 - Enable WKUP pin 2"]
#[inline(always)]
pub fn ewup2(&mut self) -> EWUP2_W {
EWUP2_W { w: self }
}
#[doc = "Bit 8 - Enable WKUP pin 1"]
#[inline(always)]
pub fn ewup1(&mut self) -> EWUP1_W {
EWUP1_W { w: self }
}
#[doc = "Bit 10 - Enable WKUP pin 3"]
#[inline(always)]
pub fn ewup3(&mut self) -> EWUP3_W {
EWUP3_W { w: self }
}
}
|
use crate::camera::CameraParameters;
use ndarray::Array2;
use pyo3::prelude::{pyclass, PyObject};
#[pyclass]
#[derive(Clone)]
pub struct Frame {
pub camera_params: CameraParameters,
pub image: Array2<f64>,
pub transform: Array2<f64>, // transform from frame to world
}
|
use proconio::input;
fn main() {
input! {
n: usize,
mut m: u64,
k: usize,
mut a: [u64; n],
};
let mut ans = 0_u64;
for i in (0..32).rev() {
let mut b: Vec<(u64, usize)> = a
.iter()
.copied()
.enumerate()
.filter(|&(_, x)| ans & x == ans)
.map(|(j, x)| {
let cost = if x >> i & 1 == 1 {
0
} else {
(1 << i) - (x & ((1 << i) - 1))
};
(cost, j)
})
.collect();
if b.len() < k {
break;
}
b.sort();
let b = b[..k].to_vec();
let cost = b.iter().map(|(c, _)| c).sum::<u64>();
if cost > m {
continue;
}
m -= cost;
for (c, j) in b {
a[j] += c;
}
ans ^= 1 << i;
}
println!("{}", ans);
}
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::{bail, Context, Result},
serde::{Deserialize, Serialize},
serde_json::{from_value, Value},
std::io::Read,
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct ManifestFile {
version: u64,
manifest: Value,
}
pub(crate) enum FlashManifest {
V1(FlashManifestV1),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub(crate) struct FlashManifestV1(Vec<Product>);
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub(crate) struct Product {
name: String,
partitions: Vec<Partition>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub(crate) struct Partition(String, String);
#[cfg(test)]
impl Partition {
pub(crate) fn name(&self) -> &str {
self.0.as_str()
}
pub(crate) fn file(&self) -> &str {
self.1.as_str()
}
}
impl FlashManifest {
pub(crate) fn load<R: Read>(reader: R) -> Result<Self> {
let manifest: ManifestFile = serde_json::from_reader::<R, ManifestFile>(reader)
.context("reading flash manifest from disk")?;
match manifest.version {
1 => Ok(Self::V1(from_value(manifest.manifest.clone())?)),
_ => bail!("Unknown flash manifest version"),
}
}
}
////////////////////////////////////////////////////////////////////////////////
// tests
#[cfg(test)]
mod test {
use super::*;
use serde_json::from_str;
use std::io::BufReader;
const UNKNOWN_VERSION: &'static str = r#"{
"version": 99999,
"manifest": "test"
}"#;
const MANIFEST: &'static str = r#"{
"version": 1,
"manifest": [
{
"name": "zedboot",
"partitions": [
["test1", "path1"],
["test2", "path2"],
["test3", "path3"],
["test4", "path4"],
["test5", "path5"]
]
},
{
"name": "product",
"partitions": [
["test10", "path10"],
["test20", "path20"],
["test30", "path30"]
]
}
]
}"#;
#[test]
fn test_deserialization() -> Result<()> {
let _manifest: ManifestFile = from_str(MANIFEST)?;
Ok(())
}
#[test]
fn test_loading_unknown_version() {
let manifest_contents = UNKNOWN_VERSION.to_string();
let result = FlashManifest::load(BufReader::new(manifest_contents.as_bytes()));
assert!(result.is_err());
}
#[allow(irrefutable_let_patterns)]
#[fuchsia_async::run_singlethreaded(test)]
async fn test_loading_version_1() -> Result<()> {
let manifest_contents = MANIFEST.to_string();
let manifest = FlashManifest::load(BufReader::new(manifest_contents.as_bytes()))?;
if let FlashManifest::V1(v) = manifest {
let zedboot: &Product = &v.0[0];
assert_eq!("zedboot", zedboot.name);
assert_eq!(5, zedboot.partitions.len());
let expected = [
["test1", "path1"],
["test2", "path2"],
["test3", "path3"],
["test4", "path4"],
["test5", "path5"],
];
for x in 0..expected.len() {
assert_eq!(zedboot.partitions[x].name(), expected[x][0]);
assert_eq!(zedboot.partitions[x].file(), expected[x][1]);
}
let product: &Product = &v.0[1];
assert_eq!("product", product.name);
assert_eq!(3, product.partitions.len());
let expected2 = [["test10", "path10"], ["test20", "path20"], ["test30", "path30"]];
for x in 0..expected2.len() {
assert_eq!(product.partitions[x].name(), expected2[x][0]);
assert_eq!(product.partitions[x].file(), expected2[x][1]);
}
} else {
bail!("Parsed incorrect version");
}
Ok(())
}
}
|
use rand::Rng;
use std::env;
use std::process;
use std::time::Instant;
fn main() {
let args: Vec<String> = env::args().collect();
let mut program_state = ProgState::new(&args).unwrap_or_else(|err| {
println!("\nERROR: {}\n\nUSAGE: {}", err, ProgState::get_usage());
process::exit(1);
});
println!("Begin {} iterations with strategy {}", &args[1], &args[2]);
iterate(&mut program_state);
print_status(&program_state);
}
// Derive and store win counts, pass appropriate values to print_strat_status
fn print_status(program_state: &ProgState) {
println!("Tested {} of {} iterations", program_state.iterations_performed, program_state.iterations);
let stay_wins = program_state.stay_wins;
let switch_wins = program_state.iterations_performed - program_state.stay_wins;
let test_count = program_state.iterations_performed;
match program_state.strategy {
Strategy::STAY => print_strat_status("STAY", stay_wins, test_count),
Strategy::SWITCH => print_strat_status("SWITCH", switch_wins, test_count),
Strategy::BOTH => {
print_strat_status("STAY", stay_wins, test_count);
print_strat_status("SWITCH", switch_wins, test_count);
},
}
}
// Make result interpretation pretty
fn print_strat_status(strategy_string: &str, wins: u128, iterations: u128) {
let winpercent = 100.0 * ((wins as f64)/(iterations as f64));
println!("\t{} wins {} times (win rate: {}%)",strategy_string, wins, winpercent);
}
// so the cheeseball logic here is this:
// If initial contestant pick is the car door (1 in three chance), staying wins
// If initial contestant pick is NOT car door (2 in three chance), switching wins
// Which door is opened is pretty inconsequential unless detailed logging, so don't do it
// until we need to
fn iterate(program_state: &mut ProgState) {
let mut rng = rand::thread_rng();
let mut now = Instant::now();
while program_state.needs_another_iteration() {
let car_door = rng.gen_range(0,3);
let contestant_door = rng.gen_range(0,3);
program_state.result_completed(car_door == contestant_door);
if program_state.logging {
let mut goat_doors = vec![0, 1, 2];
goat_doors.remove(car_door);
let open_door;
if contestant_door == goat_doors[0] {
open_door = goat_doors[1];
} else if contestant_door == goat_doors[1] {
open_door = goat_doors[0];
} else {
open_door = rng.gen_range(0, goat_doors.len());
}
println!("Test {} of {}:\n\tCar behind {}, Goats behind {} and {}\n\t\
Contestant Chooses {}\n\t\
Monty Opens {} and reveals a goat",
program_state.iterations_performed,
program_state.iterations,
car_door + 1,
goat_doors[0] + 1,
goat_doors[1] + 1,
contestant_door + 1,
open_door + 1);
} else if now.elapsed().as_millis() >= 1000 {
print_status(&program_state);
now = Instant::now();
}
}
}
// we want to store the target iterations and the ongoing iterations actually performed.
// Since, on any given iterations, staying will win or switching will win (never both lose), only
// track stay win (arbitrary choice). Store cmd line logging option.
// Finally, store strategy for iterpreting results based on stay_wins and printing
struct ProgState {
iterations: u128,
iterations_performed: u128,
stay_wins: u128,
logging: bool,
strategy: Strategy,
}
enum Strategy {
STAY,
SWITCH,
BOTH,
}
impl ProgState {
fn new(args: &[String]) -> Result<ProgState, &'static str> {
if args.len() != 3 && args.len() != 4 {
return Err("Incomplete argument list");
}
let iterations = match u128::from_str_radix(&args[1], 10) {
Ok(count) => count,
Err(_) => return Err("Iterations argument failed to parse"),
};
if iterations == 0 {
return Err("Zero is an invalid number of iterations");
}
let strategy = match args[2].as_str() {
"STAY" => Strategy::STAY,
"SWITCH" => Strategy::SWITCH,
"BOTH" => Strategy::BOTH,
_ => return Err("Strategy failed to parse"),
};
let logging;
if args.len() == 4 && args[3].as_str() == "DEBUGLOG" {
logging = true;
} else {
logging = false;
}
Ok(ProgState { iterations, iterations_performed: 0, stay_wins: 0, logging, strategy })
}
fn get_usage() -> &'static str {
return "montyhall [iterations] [strategy]\n\t \
Iterations:\tNumber of tests to run (1 or more)\n\t \
Strategy:\tChoose between STAY, SWTICH, or BOTH\n\t \
Logging:\tOptional. Enter DEBUGLOG to enable"
}
fn result_completed(&mut self, staywin: bool) {
self.iterations_performed = self.iterations_performed + 1;
if staywin {
self.stay_wins = self.stay_wins + 1;
}
}
fn needs_another_iteration(&self) -> bool {
self.iterations_performed < self.iterations
}
}
|
// Miri: copying channels internally in a buffer intrinsically requires a bit of
// tongue in cheek pointer mangling. These tests are added here so that they can
// be run through miri to test that at least a base level of sanity is
// maintained.
#[test]
fn test_copy_channels_dynamic() {
use crate::{Channels, ChannelsMut};
let mut buffer: crate::Dynamic<i16> = crate::dynamic![[1, 2, 3, 4], [0, 0, 0, 0]];
buffer.copy_channels(0, 1);
assert_eq!(buffer.channel(1), buffer.channel(0));
}
#[test]
fn test_copy_channels_sequential() {
use crate::{Channels, ChannelsMut};
let mut buffer: crate::Sequential<i16> = crate::sequential![[1, 2, 3, 4], [0, 0, 0, 0]];
buffer.copy_channels(0, 1);
assert_eq!(buffer.channel(1), buffer.channel(0));
assert_eq!(buffer.as_slice(), &[1, 2, 3, 4, 1, 2, 3, 4]);
}
#[test]
fn test_copy_channels_wrap_sequential() {
use crate::wrap;
use crate::{Channels, ChannelsMut};
let mut data = [1, 2, 3, 4, 0, 0, 0, 0];
let data = &mut data[..];
let mut buffer: wrap::Sequential<&mut [i16]> = wrap::sequential(data, 2);
buffer.copy_channels(0, 1);
assert_eq!(buffer.channel(1), buffer.channel(0));
assert_eq!(data, &[1, 2, 3, 4, 1, 2, 3, 4]);
}
#[test]
fn test_copy_channels_interleaved() {
use crate::{Channels, ChannelsMut};
let mut buffer: crate::Interleaved<i16> = crate::interleaved![[1, 2, 3, 4], [0, 0, 0, 0]];
buffer.copy_channels(0, 1);
assert_eq!(buffer.channel(1), buffer.channel(0));
assert_eq!(buffer.as_slice(), &[1, 1, 2, 2, 3, 3, 4, 4]);
}
#[test]
fn test_copy_channels_wrap_interleaved() {
use crate::wrap;
use crate::{Channels, ChannelsMut};
let mut data = [1, 0, 2, 0, 3, 0, 4, 0];
let mut buffer: wrap::Interleaved<&mut [i16]> = wrap::interleaved(&mut data[..], 2);
buffer.copy_channels(0, 1);
assert_eq!(buffer.channel(1), buffer.channel(0));
assert_eq!(&data[..], &[1, 1, 2, 2, 3, 3, 4, 4]);
}
#[test]
fn test_copy_channels_vec_of_vecs() {
use crate::{Channels, ChannelsMut};
let mut buffer: Vec<Vec<i16>> = vec![vec![1, 2, 3, 4], vec![0, 0]];
buffer.copy_channels(0, 1);
assert_eq!(buffer.channel(1), buffer.channel(0).limit(2));
}
|
#[doc = "Reader of register DC4"]
pub type R = crate::R<u32, super::DC4>;
#[doc = "Reader of field `GPIOA`"]
pub type GPIOA_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOB`"]
pub type GPIOB_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOC`"]
pub type GPIOC_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOD`"]
pub type GPIOD_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOE`"]
pub type GPIOE_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOF`"]
pub type GPIOF_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOG`"]
pub type GPIOG_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOH`"]
pub type GPIOH_R = crate::R<bool, bool>;
#[doc = "Reader of field `GPIOJ`"]
pub type GPIOJ_R = crate::R<bool, bool>;
#[doc = "Reader of field `ROM`"]
pub type ROM_R = crate::R<bool, bool>;
#[doc = "Reader of field `UDMA`"]
pub type UDMA_R = crate::R<bool, bool>;
#[doc = "Reader of field `CCP6`"]
pub type CCP6_R = crate::R<bool, bool>;
#[doc = "Reader of field `CCP7`"]
pub type CCP7_R = crate::R<bool, bool>;
#[doc = "Reader of field `PICAL`"]
pub type PICAL_R = crate::R<bool, bool>;
#[doc = "Reader of field `E1588`"]
pub type E1588_R = crate::R<bool, bool>;
#[doc = "Reader of field `EMAC0`"]
pub type EMAC0_R = crate::R<bool, bool>;
#[doc = "Reader of field `EPHY0`"]
pub type EPHY0_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - GPIO Port A Present"]
#[inline(always)]
pub fn gpioa(&self) -> GPIOA_R {
GPIOA_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - GPIO Port B Present"]
#[inline(always)]
pub fn gpiob(&self) -> GPIOB_R {
GPIOB_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - GPIO Port C Present"]
#[inline(always)]
pub fn gpioc(&self) -> GPIOC_R {
GPIOC_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - GPIO Port D Present"]
#[inline(always)]
pub fn gpiod(&self) -> GPIOD_R {
GPIOD_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - GPIO Port E Present"]
#[inline(always)]
pub fn gpioe(&self) -> GPIOE_R {
GPIOE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - GPIO Port F Present"]
#[inline(always)]
pub fn gpiof(&self) -> GPIOF_R {
GPIOF_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - GPIO Port G Present"]
#[inline(always)]
pub fn gpiog(&self) -> GPIOG_R {
GPIOG_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - GPIO Port H Present"]
#[inline(always)]
pub fn gpioh(&self) -> GPIOH_R {
GPIOH_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - GPIO Port J Present"]
#[inline(always)]
pub fn gpioj(&self) -> GPIOJ_R {
GPIOJ_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 12 - Internal Code ROM Present"]
#[inline(always)]
pub fn rom(&self) -> ROM_R {
ROM_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Micro-DMA Module Present"]
#[inline(always)]
pub fn udma(&self) -> UDMA_R {
UDMA_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - T3CCP0 Pin Present"]
#[inline(always)]
pub fn ccp6(&self) -> CCP6_R {
CCP6_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - T3CCP1 Pin Present"]
#[inline(always)]
pub fn ccp7(&self) -> CCP7_R {
CCP7_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 18 - PIOSC Calibrate"]
#[inline(always)]
pub fn pical(&self) -> PICAL_R {
PICAL_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 24 - 1588 Capable"]
#[inline(always)]
pub fn e1588(&self) -> E1588_R {
E1588_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 28 - Ethernet MAC Layer 0 Present"]
#[inline(always)]
pub fn emac0(&self) -> EMAC0_R {
EMAC0_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 30 - Ethernet PHY Layer 0 Present"]
#[inline(always)]
pub fn ephy0(&self) -> EPHY0_R {
EPHY0_R::new(((self.bits >> 30) & 0x01) != 0)
}
}
|
use otspec::types::*;
use otspec_macros::tables;
use serde::{Deserialize, Serialize};
tables!(head {
uint16 majorVersion
uint16 minorVersion
Fixed fontRevision
uint32 checksumAdjustment
uint32 magicNumber
uint16 flags
uint16 unitsPerEm
LONGDATETIME created
LONGDATETIME modified
int16 xMin
int16 yMin
int16 xMax
int16 yMax
uint16 macStyle
uint16 lowestRecPPEM
int16 fontDirectionHint
int16 indexToLocFormat
int16 glyphDataFormat
});
impl head {
pub fn new(
fontRevision: f32,
upm: uint16,
xMin: int16,
yMin: int16,
xMax: int16,
yMax: int16,
) -> head {
head {
majorVersion: 1,
minorVersion: 0,
fontRevision,
checksumAdjustment: 0x0,
magicNumber: 0x5F0F3CF5,
flags: 3,
unitsPerEm: upm,
created: chrono::Utc::now().naive_local(),
modified: chrono::Utc::now().naive_local(),
xMin,
yMin,
xMax,
yMax,
macStyle: 0,
lowestRecPPEM: 6,
fontDirectionHint: 2,
indexToLocFormat: 0,
glyphDataFormat: 0,
}
}
}
#[cfg(test)]
mod tests {
use crate::head::head;
use otspec::de;
use otspec::ser;
#[test]
fn head_ser() {
let fhead = head {
majorVersion: 1,
minorVersion: 0,
fontRevision: 1.0,
checksumAdjustment: 0xaf8fe61,
magicNumber: 0x5F0F3CF5,
flags: 0b0000000000000011,
unitsPerEm: 1000,
created: chrono::NaiveDate::from_ymd(2020, 1, 28).and_hms(21, 31, 22),
modified: chrono::NaiveDate::from_ymd(2021, 4, 14).and_hms(12, 1, 45),
xMin: 9,
yMin: 0,
xMax: 592,
yMax: 1000,
macStyle: 0,
lowestRecPPEM: 6,
fontDirectionHint: 2,
indexToLocFormat: 1,
glyphDataFormat: 0,
};
let binary_head = vec![
0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0a, 0xf8, 0xfe, 0x61, 0x5f, 0x0f,
0x3c, 0xf5, 0x00, 0x03, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xda, 0x56, 0x58, 0xaa,
0x00, 0x00, 0x00, 0x00, 0xdc, 0x9c, 0x8a, 0x29, 0x00, 0x09, 0x00, 0x00, 0x02, 0x50,
0x03, 0xe8, 0x00, 0x00, 0x00, 0x06, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00,
];
assert_eq!(ser::to_bytes(&fhead).unwrap(), binary_head);
}
#[test]
fn head_de() {
let fhead = head {
majorVersion: 1,
minorVersion: 0,
fontRevision: 1.0,
checksumAdjustment: 0xaf8fe61,
magicNumber: 0x5F0F3CF5,
flags: 0b0000000000000011,
unitsPerEm: 1000,
created: chrono::NaiveDate::from_ymd(2020, 1, 28).and_hms(21, 31, 22),
modified: chrono::NaiveDate::from_ymd(2021, 4, 14).and_hms(12, 1, 45),
xMin: 9,
yMin: 0,
xMax: 592,
yMax: 1000,
macStyle: 0,
lowestRecPPEM: 6,
fontDirectionHint: 2,
indexToLocFormat: 1,
glyphDataFormat: 0,
};
let binary_head = vec![
0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0a, 0xf8, 0xfe, 0x61, 0x5f, 0x0f,
0x3c, 0xf5, 0x00, 0x03, 0x03, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xda, 0x56, 0x58, 0xaa,
0x00, 0x00, 0x00, 0x00, 0xdc, 0x9c, 0x8a, 0x29, 0x00, 0x09, 0x00, 0x00, 0x02, 0x50,
0x03, 0xe8, 0x00, 0x00, 0x00, 0x06, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00,
];
let deserialized: head = otspec::de::from_bytes(&binary_head).unwrap();
assert_eq!(deserialized, fhead);
}
}
|
mod model;
mod routes;
use actix_web::{middleware, App, HttpServer};
use mongodb;
use mongodb::{options::ClientOptions, Client, Collection};
use std::env;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let client_options = ClientOptions::parse(
&env::var("MONGO_URI").expect("The MONGO_URI environment variable must be set."),
)
.await
.unwrap();
let client = Client::with_options(client_options).unwrap();
let recipes: Collection<model::Cocktail> =
client.database("cocktails").collection_with_type("recipes");
HttpServer::new(move || {
App::new()
.data(recipes.clone())
.wrap(middleware::Logger::default())
.service(routes::list_cocktails)
.service(routes::get_cocktail)
.service(routes::new_cocktail)
.service(routes::update_cocktail)
.service(routes::delete_cocktail)
})
.bind("127.0.0.1:5000")?
.run()
.await
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::switchboard::accessibility_types::AccessibilityInfo;
use bitflags::bitflags;
use failure::Error;
use fuchsia_syslog::fx_log_warn;
use futures::channel::mpsc::UnboundedSender;
use futures::channel::oneshot::Sender;
use serde_derive::{Deserialize, Serialize};
use std::collections::HashSet;
pub type SettingResponseResult = Result<Option<SettingResponse>, Error>;
pub type SettingRequestResponder = Sender<SettingResponseResult>;
/// The setting types supported by the messaging system. This is used as a key
/// for listening to change notifications and sending requests.
/// The types are arranged alphabetically.
#[derive(PartialEq, Debug, Eq, Hash, Clone, Copy)]
pub enum SettingType {
Unknown,
Accessibility,
Account,
Audio,
Device,
Display,
DoNotDisturb,
Intl,
LightSensor,
Power,
Privacy,
Setup,
System,
}
/// Returns all known setting types. New additions to SettingType should also
/// be inserted here.
pub fn get_all_setting_types() -> HashSet<SettingType> {
let mut set = HashSet::new();
set.insert(SettingType::Accessibility);
set.insert(SettingType::Audio);
set.insert(SettingType::Device);
set.insert(SettingType::Display);
set.insert(SettingType::DoNotDisturb);
set.insert(SettingType::Intl);
set.insert(SettingType::LightSensor);
set.insert(SettingType::Privacy);
set.insert(SettingType::Setup);
set.insert(SettingType::System);
set
}
/// The possible requests that can be made on a setting. The sink will expect a
/// subset of the values defined below based on the associated type.
/// The types are arranged alphabetically.
#[derive(PartialEq, Debug, Clone)]
pub enum SettingRequest {
Get,
// Accessibility requests.
SetAccessibilityInfo(AccessibilityInfo),
// Account requests
ScheduleClearAccounts,
// Audio requests.
SetVolume(Vec<AudioStream>),
// Display requests.
SetBrightness(f32),
SetAutoBrightness(bool),
// Do not disturb requests.
SetUserInitiatedDoNotDisturb(bool),
SetNightModeInitiatedDoNotDisturb(bool),
// Intl requests.
SetTimeZone(String),
// Power requests.
Reboot,
// Privacy requests.
SetUserDataSharingConsent(Option<bool>),
// Setup info requests.
SetConfigurationInterfaces(ConfigurationInterfaceFlags),
// System login requests.
SetLoginOverrideMode(SystemLoginOverrideMode),
}
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct DeviceInfo {
pub build_tag: String,
}
impl DeviceInfo {
pub const fn new(build_tag: String) -> DeviceInfo {
DeviceInfo { build_tag }
}
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum AudioSettingSource {
Default,
User,
System,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize, Hash, Eq)]
pub enum AudioStreamType {
Background,
Media,
Interruption,
SystemAgent,
Communication,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct AudioStream {
pub stream_type: AudioStreamType,
pub source: AudioSettingSource,
pub user_volume_level: f32,
pub user_volume_muted: bool,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct AudioInputInfo {
pub mic_mute: bool,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct AudioInfo {
pub streams: [AudioStream; 5],
pub input: AudioInputInfo,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DisplayInfo {
/// The last brightness value that was manually set
pub manual_brightness_value: f32,
pub auto_brightness: bool,
}
impl DisplayInfo {
pub const fn new(auto_brightness: bool, manual_brightness_value: f32) -> DisplayInfo {
DisplayInfo {
manual_brightness_value: manual_brightness_value,
auto_brightness: auto_brightness,
}
}
}
bitflags! {
#[derive(Serialize, Deserialize)]
pub struct ConfigurationInterfaceFlags: u32 {
const ETHERNET = 1 << 0;
const WIFI = 1 << 1;
const DEFAULT = Self::WIFI.bits;
}
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DoNotDisturbInfo {
pub user_dnd: bool,
pub night_mode_dnd: bool,
}
impl DoNotDisturbInfo {
pub const fn new(user_dnd: bool, night_mode_dnd: bool) -> DoNotDisturbInfo {
DoNotDisturbInfo { user_dnd: user_dnd, night_mode_dnd: night_mode_dnd }
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct IntlInfo {
pub time_zone_id: String,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct PrivacyInfo {
pub user_data_sharing_consent: Option<bool>,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub enum SystemLoginOverrideMode {
None,
AutologinGuest,
AuthProvider,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
pub struct SystemInfo {
pub login_override_mode: SystemLoginOverrideMode,
}
#[derive(PartialEq, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct SetupInfo {
pub configuration_interfaces: ConfigurationInterfaceFlags,
}
#[derive(PartialEq, Debug, Clone, Copy, Deserialize, Serialize)]
pub struct LightData {
/// Overall illuminance as measured in lux
pub illuminance: f32,
}
/// The possible responses to a SettingRequest.
#[derive(PartialEq, Debug, Clone)]
pub enum SettingResponse {
Unknown,
Accessibility(AccessibilityInfo),
Audio(AudioInfo),
/// Response to a request to get current brightness state.AccessibilityEncoder
Brightness(DisplayInfo),
Device(DeviceInfo),
LightSensor(LightData),
DoNotDisturb(DoNotDisturbInfo),
Intl(IntlInfo),
Privacy(PrivacyInfo),
Setup(SetupInfo),
System(SystemInfo),
}
/// Description of an action request on a setting. This wraps a
/// SettingActionData, providing destination details (setting type) along with
/// callback information (action id).
pub struct SettingAction {
pub id: u64,
pub setting_type: SettingType,
pub data: SettingActionData,
}
/// The types of actions. Note that specific request types should be enumerated
/// in the SettingRequest enum.
#[derive(PartialEq, Debug)]
pub enum SettingActionData {
/// The listening state has changed for the particular setting. The provided
/// value indicates the number of active listeners. 0 indicates there are
/// no more listeners.
Listen(u64),
/// A request has been made on a particular setting. The specific setting
/// and request data are encoded in SettingRequest.
Request(SettingRequest),
}
/// The events generated in response to SettingAction.
pub enum SettingEvent {
/// The backing data for the specified setting type has changed. Interested
/// parties can query through request to get the updated values.
Changed(SettingType),
/// A response to a previous SettingActionData::Request is ready. The source
/// SettingAction's id is provided alongside the result.
Response(u64, SettingResponseResult),
}
/// A trait handed back from Switchboard's listen interface. Allows client to
/// signal they want to end the session.
pub trait ListenSession: Drop {
/// Invoked to close the current listening session. No further updates will
/// be provided to the listener provided at the initial listen call.
fn close(&mut self);
}
/// A interface for send SettingActions.
pub trait Switchboard {
/// Transmits a SettingRequest. Results are returned from the passed in
/// oneshot sender.
fn request(
&mut self,
setting_type: SettingType,
request: SettingRequest,
callback: Sender<Result<Option<SettingResponse>, Error>>,
) -> Result<(), Error>;
/// Establishes a continuous callback for change notifications around a
/// SettingType.
fn listen(
&mut self,
setting_type: SettingType,
listener: UnboundedSender<SettingType>,
) -> Result<Box<dyn ListenSession + Send + Sync>, Error>;
}
/// Custom trait used to handle results from responding to FIDL calls.
pub trait FidlResponseErrorLogger {
fn log_fidl_response_error(&self, client_name: &str);
}
/// In order to not crash when a client dies, logs but doesn't crash for the specific case of
/// being unable to write to the client. Crashes if other types of errors occur.
impl FidlResponseErrorLogger for Result<(), fidl::Error> {
fn log_fidl_response_error(&self, client_name: &str) {
if let Some(error) = self.as_ref().err() {
match error {
fidl::Error::ServerResponseWrite(_) => {
fx_log_warn!("Failed to respond to client {:?} : {:?}", client_name, error);
}
_ => {
panic!(
"Unexpected client response error from client {:?} : {:?}",
client_name, error
);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use fuchsia_zircon as zx;
/// Should succeed either when responding was successful or there was an error on the client side.
#[test]
fn test_error_logger_succeeds() {
let result = Err(fidl::Error::ServerResponseWrite(zx::Status::PEER_CLOSED));
result.log_fidl_response_error("");
let result = Ok(());
result.log_fidl_response_error("");
}
/// Should fail at all other times.
#[should_panic]
#[test]
fn test_error_logger_fails() {
let result = Err(fidl::Error::ServerRequestRead(zx::Status::PEER_CLOSED));
result.log_fidl_response_error("");
}
}
|
use bevy::prelude::*;
use bevy_pyxel_loader::{BevyPyxelPlugin, PyxelFile};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugin(BevyPyxelPlugin)
.add_startup_system(startup)
.add_system(dbg_json)
.run();
}
fn startup(asset_server: Res<AssetServer>, mut commands: Commands) {
let handle = asset_server.load::<PyxelFile, &str>("borders.pyxel");
commands.insert_resource(handle);
}
fn dbg_json(assets: Res<Assets<PyxelFile>>, handle: Res<Handle<PyxelFile>>) {
if assets.is_changed() {
if let Some(file) = assets.get(handle.id) {
dbg!(&file.data);
}
}
}
|
extern crate failure;
#[macro_use]
extern crate failure_derive;
use std::fmt;
use std::io;
use failure::{Backtrace, Fail};
#[derive(Fail, Debug)]
#[fail(display = "An error has occurred: {}", inner)]
struct WrapError {
#[fail(cause)]
inner: io::Error,
}
#[test]
fn wrap_error() {
let inner = io::Error::from_raw_os_error(98);
let err = WrapError { inner };
assert!(err
.cause()
.and_then(|err| err.downcast_ref::<io::Error>())
.is_some());
}
#[derive(Fail, Debug)]
#[fail(display = "An error has occurred: {}", _0)]
struct WrapTupleError(#[fail(cause)] io::Error);
#[test]
fn wrap_tuple_error() {
let io_error = io::Error::from_raw_os_error(98);
let err: WrapTupleError = WrapTupleError(io_error);
assert!(err
.cause()
.and_then(|err| err.downcast_ref::<io::Error>())
.is_some());
}
#[derive(Fail, Debug)]
#[fail(display = "An error has occurred: {}", inner)]
struct WrapBacktraceError {
#[fail(cause)]
inner: io::Error,
backtrace: Backtrace,
}
#[test]
fn wrap_backtrace_error() {
let inner = io::Error::from_raw_os_error(98);
let err: WrapBacktraceError = WrapBacktraceError {
inner,
backtrace: Backtrace::new(),
};
assert!(err
.cause()
.and_then(|err| err.downcast_ref::<io::Error>())
.is_some());
assert!(err.backtrace().is_some());
}
#[derive(Fail, Debug)]
enum WrapEnumError {
#[fail(display = "An error has occurred: {}", _0)]
Io(#[fail(cause)] io::Error),
#[fail(display = "An error has occurred: {}", inner)]
Fmt {
#[fail(cause)]
inner: fmt::Error,
backtrace: Backtrace,
},
}
#[test]
fn wrap_enum_error() {
let io_error = io::Error::from_raw_os_error(98);
let err: WrapEnumError = WrapEnumError::Io(io_error);
assert!(err
.cause()
.and_then(|err| err.downcast_ref::<io::Error>())
.is_some());
assert!(err.backtrace().is_none());
let fmt_error = fmt::Error::default();
let err: WrapEnumError = WrapEnumError::Fmt {
inner: fmt_error,
backtrace: Backtrace::new(),
};
assert!(err
.cause()
.and_then(|err| err.downcast_ref::<fmt::Error>())
.is_some());
assert!(err.backtrace().is_some());
}
|
// SPDX-License-Identifier: Apache-2.0
//! Array of `T` with dynamic allocations of `N` entries for slabs of size `M`
//!
//! The array will dynamically allocate slabs of size `M` to extend its internal
//! linked list, which will extend the capacity by `N`.
//!
//! Currently nightly until `#![feature(min_const_generics)]` hits stable with `1.51`.
#![deny(missing_docs)]
#![deny(clippy::all)]
#![cfg_attr(not(test), no_std)]
use core::alloc::GlobalAlloc;
use core::alloc::Layout;
use core::marker::PhantomData;
use core::mem::{align_of, size_of, MaybeUninit};
use core::ptr::NonNull;
#[inline]
const fn align_up<T>(addr: usize) -> usize {
let align_mask = align_of::<T>() - 1;
if addr & align_mask == 0 {
addr // already aligned
} else {
(addr | align_mask) + 1
}
}
/// Array of `T` with dynamic allocations of `N` entries for slabs of size `M`
pub struct SlabVec<T: Default + Copy + Sized, const N: usize, const M: usize> {
head: Option<NonNull<ListPage<T, N, M>>>,
tail: Option<NonNull<ListPage<T, N, M>>>,
len: usize,
alloc: &'static dyn GlobalAlloc,
}
impl<T: Default + Copy + Sized, const N: usize, const M: usize> SlabVec<T, N, M> {
/// Number of entries a [`SlabVec`] could hold
///
/// Trick used because of const_generics being still unstable.
pub const NUM_ENTRIES: usize =
(M - size_of::<ListPageHeader<T, N, 1>>()) / align_up::<T>(size_of::<T>());
/// Get a new List using `alloc` as the allocator for its slabs
pub fn new(alloc: &'static dyn GlobalAlloc) -> Self {
let mut sl = Self {
alloc,
len: 0,
head: None,
tail: None,
};
sl.add_page();
sl
}
/// Add one more page of size `M` with `N` entries
pub fn add_page(&mut self) {
let lp = NonNull::new({
let ele = unsafe {
&mut *(self
.alloc
.alloc(Layout::from_size_align(M, align_of::<ListPage<T, N, M>>()).unwrap())
as *mut MaybeUninit<ListPage<T, N, M>>)
};
unsafe {
ele.as_mut_ptr().write(ListPage::<T, N, M> {
header: ListPageHeader { next: None },
entry: [T::default(); N],
});
// As the yet unstable MaybeUninit::assume_init_mut()
&mut *ele.as_mut_ptr()
}
});
if self.head.is_none() {
self.head = lp;
}
if let Some(mut tail) = self.tail {
unsafe { tail.as_mut() }.header.next = lp;
}
self.tail = lp;
self.len += N;
}
/// Provides a forward iterator.
pub fn iter(&self) -> Iter<'_, T, N, M> {
Iter {
current: self.head,
index: 0,
len: self.len,
phantom: PhantomData,
}
}
/// Provides a forward iterator with mutable references.
pub fn iter_mut(&mut self) -> IterMut<'_, T, N, M> {
IterMut {
current: self.head,
index: 0,
len: self.len,
phantom: PhantomData,
}
}
}
impl<T: Default + Copy + Sized, const N: usize, const M: usize> Drop for SlabVec<T, N, M> {
fn drop(&mut self) {
unsafe {
let mut this = self.head.take();
while let Some(mut ele) = this {
this = ele.as_mut().header.next.take();
self.alloc.dealloc(
ele.as_ptr() as *mut u8,
Layout::from_size_align(size_of::<Self>(), align_of::<Self>()).unwrap(),
);
}
}
}
}
#[repr(C)]
struct ListPageHeader<T: Default + Copy + Sized, const N: usize, const M: usize> {
next: Option<NonNull<ListPage<T, N, M>>>,
}
#[repr(C)]
struct ListPage<T: Default + Copy + Sized, const N: usize, const M: usize> {
header: ListPageHeader<T, N, M>,
entry: [T; N],
}
/// An iterator over the elements of a `SlabVec`.
///
/// This `struct` is created by [`SlabVec::iter()`]. See its
/// documentation for more.
pub struct Iter<'a, T: Default + Copy + Sized, const N: usize, const M: usize> {
current: Option<NonNull<ListPage<T, N, M>>>,
index: usize,
len: usize,
phantom: PhantomData<&'a SlabVec<T, N, M>>,
}
impl<'a, T: Default + Copy + Sized, const N: usize, const M: usize> Iterator for Iter<'a, T, N, M> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let this: &ListPage<T, N, M> = unsafe { &*(self.current?.as_ptr()) };
let ret = this.entry.get(self.index)?;
self.len -= 1;
self.index += 1;
if self.index == N {
self.current = this.header.next;
self.index = 0;
}
Some(ret)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
/// A mutable iterator over the elements of a `SlabVec`.
///
/// This `struct` is created by [`SlabVec::iter_mut()`]. See its
/// documentation for more.
pub struct IterMut<'a, T: Default + Copy + Sized, const N: usize, const M: usize> {
current: Option<NonNull<ListPage<T, N, M>>>,
index: usize,
len: usize,
phantom: PhantomData<&'a mut SlabVec<T, N, M>>,
}
impl<'a, T: Default + Copy + Sized, const N: usize, const M: usize> Iterator
for IterMut<'a, T, N, M>
{
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
let this: &mut ListPage<T, N, M> = unsafe { &mut *(self.current?.as_ptr()) };
let ret = this.entry.get_mut(self.index)?;
self.len -= 1;
self.index += 1;
if self.index == N {
self.current = this.header.next;
self.index = 0;
}
Some(ret)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}
#[cfg(test)]
mod tests {
use crate::SlabVec;
const PAGE_SIZE: usize = 4096;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(align(16))]
struct Data {
a: i32,
b: i32,
c: u64,
}
impl Default for Data {
fn default() -> Self {
Self { a: -1, b: -1, c: 0 }
}
}
type DataPageList = SlabVec<Data, { SlabVec::<Data, 1, PAGE_SIZE>::NUM_ENTRIES }, PAGE_SIZE>;
#[test]
fn len() {
static mut SYSTEM: std::alloc::System = std::alloc::System;
let pl = DataPageList::new(unsafe { &mut SYSTEM });
assert_eq!(pl.iter().count(), 255);
}
#[test]
fn const_len() {
assert_eq!(DataPageList::NUM_ENTRIES, 255);
}
#[test]
fn zero_len() {
assert_eq!(
SlabVec::<Data, { SlabVec::<Data, 1, 16>::NUM_ENTRIES }, 16>::NUM_ENTRIES,
0
);
}
#[test]
fn iter() {
static mut SYSTEM: std::alloc::System = std::alloc::System;
let pl = DataPageList::new(unsafe { &mut SYSTEM });
for entry in pl.iter() {
assert_eq!(*entry, Data::default());
}
}
#[test]
fn iter_mut() {
static mut SYSTEM: std::alloc::System = std::alloc::System;
let mut pl = DataPageList::new(unsafe { &mut SYSTEM });
for (i, entry) in pl.iter_mut().enumerate() {
*entry = Data {
a: i as _,
b: i as _,
c: i as _,
};
}
for (i, entry) in pl.iter().enumerate() {
assert_eq!(entry.a, i as _);
assert_eq!(entry.b, i as _);
assert_eq!(entry.c, i as _);
}
}
}
|
/// ```rust,ignore
/// 41. 缺失的第一个正数
///
/// 给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
///
/// 示例 1:
///
/// 输入: [1,2,0]
/// 输出: 3
///
/// 示例 2:
///
/// 输入: [3,4,-1,1]
/// 输出: 2
///
/// 示例 3:
///
/// 输入: [7,8,9,11,12]
/// 输出: 1
///
/// 说明:
///
/// 你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。
///
/// 来源:力扣(LeetCode)
/// 链接:https://leetcode-cn.com/problems/first-missing-positive
/// 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/// ```
pub fn first_missing_positive(nums: Vec<i32>) -> i32 {
let mut i = 1;
loop {
if !nums.contains(&i) {
return i;
}
i += 1;
}
}
#[cfg(test)]
mod test
{
use super::first_missing_positive;
#[test]
fn test_first_missing_positive()
{
assert_eq!(first_missing_positive(vec![1,2,0]), 3);
}
}
|
use crate::shader::{SFragmentShaderPayload, SVertexShaderPayload};
use std::default::Default;
use std::boxed::Box;
use opencv::core::MatTrait;
use opencv::prelude::MatTraitManual;
use crate::shader_utility::{texture_sample, texture_sample2};
pub type VertexShaderProgram=Box<dyn Fn(&SVertexShaderPayload) -> glm::Vec3>;
pub type FrameShaderProgram=Box<dyn Fn(&SFragmentShaderPayload) -> glm::Vec3>;
// frame shader
pub fn empty_fs(fs_payload: &SFragmentShaderPayload) -> glm::Vec3 {
return glm::vec3(1.0f32, 1.0, 1.0);
}
pub fn normal_fs(fs_payload: &SFragmentShaderPayload) -> glm::Vec3{
let mut result_color = (fs_payload.normal.normalize() + glm::vec3(1., 1., 1.)).scale(0.5);
return result_color;
}
struct Light {
pub pos: glm::Vec3,
pub I: glm::Vec3,
}
pub fn phone_fs(fs_payload: &SFragmentShaderPayload) -> glm::Vec3 {
let tex_color;
if !fs_payload.texture.empty().unwrap() {
tex_color = texture_sample(&fs_payload.texture, &fs_payload.tex_coords).xyz();
// println!("tex_color: {:?}, {:?}", tex_color, fs_payload.tex_coords);
}
else {
tex_color = fs_payload.color;
}
let ka = glm::vec3(0.005f32, 0.005, 0.005);
let kd = fs_payload.color;
let ks = glm::vec3(0.7939, 0.7937, 0.7937);
let l1 = Light {
pos: glm::vec3(20., 20., 20.),
I: glm::vec3(1.0, 1.0, 1.0),
};
let l2 = Light {
pos: glm::vec3(-20., 20., 0.),
I: glm::vec3(1.0, 1.0, 1.0),
};
let lights = [l1, l2];
let amb_light_I = glm::vec3(0.04, 0.04, 0.04);
let eye_pos = fs_payload.eye_pos;
let view_pos = fs_payload.position;
let p = 150.0f32;
let color = tex_color;
let normal = fs_payload.normal.normalize();
let mut out_color = glm::zero();
for l in lights.iter() {
let ol = (l.pos - view_pos).normalize();
let oe = (eye_pos - view_pos).normalize();
let half_mid = (ol + oe).normalize();
let nl_ct = f32::max(glm::dot(&normal, &ol), 0.0f32);
let nh_ct = f32::max(glm::dot(&normal, &half_mid), 0.0f32);
let ambient_color = glm::matrix_comp_mult(&color, &amb_light_I);
let diffuse_color = glm::matrix_comp_mult(&color, &(nl_ct * l.I));
let specular_color = l.I * nh_ct.powf(p);
out_color += ambient_color;
out_color += diffuse_color;
out_color += specular_color;
}
return out_color;
}
pub fn texture_fs(fs_payload: &SFragmentShaderPayload) -> glm::Vec3 {
let tex_color;
if !fs_payload.texture.empty().unwrap() {
tex_color = texture_sample(&fs_payload.texture, &fs_payload.tex_coords).xyz();
// println!("tex_color: {:?}, {:?}", tex_color, fs_payload.tex_coords);
}
else {
tex_color = fs_payload.color;
}
return tex_color;
}
pub fn bump_fs(fs_payload: &SFragmentShaderPayload) -> glm::Vec3 {
let n = fs_payload.normal.normalize();
let _v = glm::vec1(n.x * n.x + n.z * n.z);
let _sqrt = glm::sqrt(&_v).x;
let t = glm::vec3(
1.0f32 * n.x * n.y / _sqrt,
_sqrt,
1.0f32 * n.z * n.y / _sqrt
);
let b = glm::cross(&n, &t);
let tbn = glm::Mat3x3::new(
t[0], b[0], n[0],
t[1], b[1], n[1],
t[2], b[2], n[2],
);
let kh = 0.2;
let kn = 0.1;
let kk = 255.0;
let w = fs_payload.texture.size().unwrap().width as f32;
let h = fs_payload.texture.size().unwrap().height as f32;
let uv = fs_payload.tex_coords;
let uv1 = glm::vec2(uv.x + 1f32/w, uv.y);
let uv2 = glm::vec2(uv.x, uv.y + 1f32/h);
let uv_c = texture_sample2(&fs_payload.texture, &uv).norm();
let dU = kh * kn * (texture_sample2(&fs_payload.texture, &uv1).norm() - uv_c);
let dV = kh * kn * (texture_sample2(&fs_payload.texture, &uv2).norm() - uv_c);
let ln = glm::vec3(-dU, -dV, 1f32);
// println!("{:?}", ln);
let w_normal = (tbn * ln).normalize();
// let c_normal = (w_normal + glm::vec3(1., 1., 1.)).scale(0.5);
return w_normal;
}
|
// xsd:
pub mod common;
#[allow(unused_imports)]
pub mod metadatastream;
pub mod onvif;
pub mod radiometry;
pub mod rules;
pub mod soap_envelope;
pub mod types;
pub mod validate;
pub mod xmlmime;
pub mod xop;
// wsdl:
#[allow(unused_imports)]
pub mod accesscontrol;
#[allow(unused_imports)]
pub mod accessrules;
#[allow(unused_imports)]
pub mod actionengine;
#[allow(unused_imports)]
pub mod advancedsecurity;
#[allow(unused_imports)]
pub mod analytics;
#[allow(unused_imports)]
pub mod authenticationbehavior;
#[allow(unused_imports)]
pub mod b_2;
#[allow(unused_imports)]
pub mod bf_2;
#[allow(unused_imports)]
pub mod credential;
#[allow(unused_imports)]
pub mod deviceio;
#[allow(unused_imports)]
pub mod devicemgmt;
#[allow(unused_imports)]
pub mod display;
#[allow(unused_imports)]
pub mod doorcontrol;
#[allow(unused_imports)]
pub mod event;
#[allow(unused_imports)]
pub mod imaging;
#[allow(unused_imports)]
pub mod media;
#[allow(unused_imports)]
pub mod media2;
#[allow(unused_imports)]
pub mod provisioning;
#[allow(unused_imports)]
pub mod ptz;
#[allow(unused_imports)]
pub mod receiver;
#[allow(unused_imports)]
pub mod recording;
#[allow(unused_imports)]
pub mod replay;
#[allow(unused_imports)]
pub mod schedule;
#[allow(unused_imports)]
pub mod search;
#[allow(unused_imports)]
pub mod t_1;
#[allow(unused_imports)]
pub mod thermal;
#[allow(unused_imports)]
pub mod uplink;
#[allow(unused_imports)]
pub mod ws_addr;
pub mod ws_discovery;
#[cfg(test)]
mod tests;
|
use std::convert::TryFrom;
use std::sync::Arc;
use thiserror::Error;
use crate::erts::process::alloc::TermAlloc;
use crate::erts::process::trace::Trace;
use crate::erts::term::prelude::*;
use super::{ArcError, ErlangException, Exception, SystemException, UnexpectedExceptionError};
#[derive(Error, Debug, Clone)]
pub enum RuntimeException {
#[error("{0}")]
Throw(#[from] super::Throw),
#[error("{0}")]
Error(#[from] super::Error),
#[error("{0}")]
Exit(#[from] super::Exit),
}
impl Eq for RuntimeException {}
impl PartialEq for RuntimeException {
fn eq(&self, other: &Self) -> bool {
use RuntimeException::*;
match (self, other) {
(Throw(ref lhs), Throw(ref rhs)) => lhs.eq(rhs),
(Error(ref lhs), Error(ref rhs)) => lhs.eq(rhs),
(Exit(ref lhs), Exit(ref rhs)) => lhs.eq(rhs),
_ => false,
}
}
}
impl RuntimeException {
pub fn class(&self) -> super::Class {
match self {
RuntimeException::Throw(e) => e.class(),
RuntimeException::Exit(e) => e.class(),
RuntimeException::Error(e) => e.class(),
}
}
pub fn reason(&self) -> Term {
match self {
RuntimeException::Throw(e) => e.reason(),
RuntimeException::Exit(e) => e.reason(),
RuntimeException::Error(e) => e.reason(),
}
}
pub fn stacktrace(&self) -> Arc<Trace> {
match self {
RuntimeException::Throw(e) => e.stacktrace(),
RuntimeException::Exit(e) => e.stacktrace(),
RuntimeException::Error(e) => e.stacktrace(),
}
}
#[inline]
pub fn layout(&self) -> std::alloc::Layout {
use crate::borrow::CloneToProcess;
use std::alloc::Layout;
// The class and trace are 1 word each and stored inline with the tuple,
// the reason is the only potentially dynamic sized term. Simply calculate
// the tuple + a block of memory capable of holding the size in words of
// the reason
let words = self.reason().size_in_words();
let layout = Layout::new::<ErlangException>();
let (layout, _) = layout
.extend(Layout::array::<Term>(words).unwrap())
.unwrap();
layout.pad_to_align()
}
#[inline]
pub fn as_error_tuple<A>(&self, heap: &mut A) -> super::AllocResult<Term>
where
A: TermAlloc,
{
match self {
RuntimeException::Throw(e) => e.as_error_tuple(heap),
RuntimeException::Exit(e) => e.as_error_tuple(heap),
RuntimeException::Error(e) => e.as_error_tuple(heap),
}
}
#[inline]
pub fn as_erlang_exception(&self) -> Box<ErlangException> {
match self {
RuntimeException::Throw(e) => e.as_erlang_exception(),
RuntimeException::Exit(e) => e.as_erlang_exception(),
RuntimeException::Error(e) => e.as_erlang_exception(),
}
}
pub fn source(&self) -> Option<ArcError> {
match self {
RuntimeException::Throw(e) => e.source(),
RuntimeException::Exit(e) => e.source(),
RuntimeException::Error(e) => e.source(),
}
}
}
impl From<anyhow::Error> for RuntimeException {
fn from(err: anyhow::Error) -> Self {
badarg!(Trace::capture(), ArcError::new(err))
}
}
impl TryFrom<Exception> for RuntimeException {
type Error = UnexpectedExceptionError<RuntimeException, SystemException>;
fn try_from(err: Exception) -> Result<Self, <Self as TryFrom<Exception>>::Error> {
match err {
Exception::Runtime(e) => Ok(e),
Exception::System(_) => Err(UnexpectedExceptionError::default()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atom;
use crate::erts::exception::Class;
mod error {
use super::*;
#[test]
fn without_arguments_stores_none() {
let reason = atom!("badarg");
let error = error!(reason, Trace::capture());
assert_eq!(error.reason(), reason);
assert_eq!(error.class(), Class::Error { arguments: None });
}
#[test]
fn with_arguments_stores_some() {
let reason = atom!("badarg");
let arguments = Term::NIL;
let error = error!(reason, arguments, Trace::capture());
assert_eq!(error.reason(), reason);
assert_eq!(
error.class(),
Class::Error {
arguments: Some(arguments)
}
);
}
}
}
|
pub mod benchmarks_pb;
pub mod proto3; |
use std::fs::File;
use cgmath::Vector3;
use image::{png, ColorType};
use log::debug;
use crate::render::Renderer;
pub struct PNG {
pub width: u32,
pub height: u32,
zindex: Vec<f64>,
image: Vec<Vec<[u8; 3]>>,
}
impl Renderer for PNG {
fn new(width: u32, height: u32) -> PNG {
PNG {
width,
height,
zindex: vec![std::f64::NEG_INFINITY; (width * height) as usize],
image: vec![vec![[0, 0, 0]; width as usize]; height as usize],
}
}
fn set_pixel(&mut self, pixel: Vector3<f64>, color: [u8; 3]) {
if pixel.x > f64::from(self.width - 1)
|| pixel.x < 0.
|| pixel.y > f64::from(self.height - 1)
|| pixel.y < 0.
{
return;
}
let zindex = (pixel.x + pixel.y * f64::from(self.width)) as usize;
if self.zindex.get(zindex).is_none() {
return;
}
if self.zindex[zindex] < pixel.z {
self.zindex[zindex] = pixel.z;
self.image[pixel.y as usize][pixel.x as usize] = color;
}
}
fn render(&mut self) {
debug!("Writing image.");
let flat_data = flatten(&mut self.image);
let buffer = File::create("foo.png").unwrap();
let encoder = png::PNGEncoder::new(buffer);
encoder
.encode(&flat_data, self.width, self.height, ColorType::RGB(8))
.expect("Error encoding PNG");
}
fn get_size(&self) -> (u32, u32) {
(self.width, self.height)
}
}
fn flatten(data: &mut Vec<Vec<[u8; 3]>>) -> Vec<u8> {
let mut flat_data: Vec<u8> = Vec::new();
data.reverse();
for row in data {
for column in row {
for item in column.iter_mut() {
flat_data.push(*item);
}
}
}
flat_data
}
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CONFIG {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = "Possible values of the field `UNIFY`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UNIFYR {
#[doc = "The SCT operates as two 16-bit counters named L and H."]
THE_SCT_OPERATES_AS_,
#[doc = "The SCT operates as a unified 32-bit counter."]
UNIFIED,
}
impl UNIFYR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
UNIFYR::THE_SCT_OPERATES_AS_ => false,
UNIFYR::UNIFIED => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> UNIFYR {
match value {
false => UNIFYR::THE_SCT_OPERATES_AS_,
true => UNIFYR::UNIFIED,
}
}
#[doc = "Checks if the value of the field is `THE_SCT_OPERATES_AS_`"]
#[inline]
pub fn is_the_sct_operates_as_(&self) -> bool {
*self == UNIFYR::THE_SCT_OPERATES_AS_
}
#[doc = "Checks if the value of the field is `UNIFIED`"]
#[inline]
pub fn is_unified(&self) -> bool {
*self == UNIFYR::UNIFIED
}
}
#[doc = "Possible values of the field `CLKMODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLKMODER {
#[doc = "The bus clock clocks the SCT and prescalers."]
THE_BUS_CLOCK_CLOCKS,
#[doc = "The SCT clock is the bus clock, but the prescalers are enabled to count only when sampling of the input selected by the CKSEL field finds the selected edge. The minimum pulse width on the clock input is 1 bus clock period. This mode is the high-performance sampled-clock mode."]
THE_SCT_CLOCK_IS_THE,
#[doc = "The input selected by CKSEL clocks the SCT and prescalers. The input is synchronized to the bus clock and possibly inverted. The minimum pulse width on the clock input is 1 bus clock period. This mode is the low-power sampled-clock mode."]
THE_INPUT_SELECTED_B,
#[doc = "Reserved."]
RESERVED_,
}
impl CLKMODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
CLKMODER::THE_BUS_CLOCK_CLOCKS => 0,
CLKMODER::THE_SCT_CLOCK_IS_THE => 1,
CLKMODER::THE_INPUT_SELECTED_B => 2,
CLKMODER::RESERVED_ => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> CLKMODER {
match value {
0 => CLKMODER::THE_BUS_CLOCK_CLOCKS,
1 => CLKMODER::THE_SCT_CLOCK_IS_THE,
2 => CLKMODER::THE_INPUT_SELECTED_B,
3 => CLKMODER::RESERVED_,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `THE_BUS_CLOCK_CLOCKS`"]
#[inline]
pub fn is_the_bus_clock_clocks(&self) -> bool {
*self == CLKMODER::THE_BUS_CLOCK_CLOCKS
}
#[doc = "Checks if the value of the field is `THE_SCT_CLOCK_IS_THE`"]
#[inline]
pub fn is_the_sct_clock_is_the(&self) -> bool {
*self == CLKMODER::THE_SCT_CLOCK_IS_THE
}
#[doc = "Checks if the value of the field is `THE_INPUT_SELECTED_B`"]
#[inline]
pub fn is_the_input_selected_b(&self) -> bool {
*self == CLKMODER::THE_INPUT_SELECTED_B
}
#[doc = "Checks if the value of the field is `RESERVED_`"]
#[inline]
pub fn is_reserved_(&self) -> bool {
*self == CLKMODER::RESERVED_
}
}
#[doc = "Possible values of the field `CLKSEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLKSELR {
#[doc = "Rising edges on input 0."]
RISING_EDGES_ON_INPUT_0,
#[doc = "Falling edges on input 0."]
FALLING_EDGES_ON_INPUT_0,
#[doc = "Rising edges on input 1."]
RISING_EDGES_ON_INPUT_1,
#[doc = "Falling edges on input 1."]
FALLING_EDGES_ON_INPUT_1,
#[doc = "Rising edges on input 2."]
RISING_EDGES_ON_INPUT_2,
#[doc = "Falling edges on input 2."]
FALLING_EDGES_ON_INPUT_2,
#[doc = "Rising edges on input 3."]
RISING_EDGES_ON_INPUT_3,
#[doc = "Falling edges on input 3."]
FALLING_EDGES_ON_INPUT_3,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl CLKSELR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
CLKSELR::RISING_EDGES_ON_INPUT_0 => 0,
CLKSELR::FALLING_EDGES_ON_INPUT_0 => 1,
CLKSELR::RISING_EDGES_ON_INPUT_1 => 2,
CLKSELR::FALLING_EDGES_ON_INPUT_1 => 3,
CLKSELR::RISING_EDGES_ON_INPUT_2 => 4,
CLKSELR::FALLING_EDGES_ON_INPUT_2 => 5,
CLKSELR::RISING_EDGES_ON_INPUT_3 => 6,
CLKSELR::FALLING_EDGES_ON_INPUT_3 => 7,
CLKSELR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> CLKSELR {
match value {
0 => CLKSELR::RISING_EDGES_ON_INPUT_0,
1 => CLKSELR::FALLING_EDGES_ON_INPUT_0,
2 => CLKSELR::RISING_EDGES_ON_INPUT_1,
3 => CLKSELR::FALLING_EDGES_ON_INPUT_1,
4 => CLKSELR::RISING_EDGES_ON_INPUT_2,
5 => CLKSELR::FALLING_EDGES_ON_INPUT_2,
6 => CLKSELR::RISING_EDGES_ON_INPUT_3,
7 => CLKSELR::FALLING_EDGES_ON_INPUT_3,
i => CLKSELR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `RISING_EDGES_ON_INPUT_0`"]
#[inline]
pub fn is_rising_edges_on_input_0(&self) -> bool {
*self == CLKSELR::RISING_EDGES_ON_INPUT_0
}
#[doc = "Checks if the value of the field is `FALLING_EDGES_ON_INPUT_0`"]
#[inline]
pub fn is_falling_edges_on_input_0(&self) -> bool {
*self == CLKSELR::FALLING_EDGES_ON_INPUT_0
}
#[doc = "Checks if the value of the field is `RISING_EDGES_ON_INPUT_1`"]
#[inline]
pub fn is_rising_edges_on_input_1(&self) -> bool {
*self == CLKSELR::RISING_EDGES_ON_INPUT_1
}
#[doc = "Checks if the value of the field is `FALLING_EDGES_ON_INPUT_1`"]
#[inline]
pub fn is_falling_edges_on_input_1(&self) -> bool {
*self == CLKSELR::FALLING_EDGES_ON_INPUT_1
}
#[doc = "Checks if the value of the field is `RISING_EDGES_ON_INPUT_2`"]
#[inline]
pub fn is_rising_edges_on_input_2(&self) -> bool {
*self == CLKSELR::RISING_EDGES_ON_INPUT_2
}
#[doc = "Checks if the value of the field is `FALLING_EDGES_ON_INPUT_2`"]
#[inline]
pub fn is_falling_edges_on_input_2(&self) -> bool {
*self == CLKSELR::FALLING_EDGES_ON_INPUT_2
}
#[doc = "Checks if the value of the field is `RISING_EDGES_ON_INPUT_3`"]
#[inline]
pub fn is_rising_edges_on_input_3(&self) -> bool {
*self == CLKSELR::RISING_EDGES_ON_INPUT_3
}
#[doc = "Checks if the value of the field is `FALLING_EDGES_ON_INPUT_3`"]
#[inline]
pub fn is_falling_edges_on_input_3(&self) -> bool {
*self == CLKSELR::FALLING_EDGES_ON_INPUT_3
}
}
#[doc = r" Value of the field"]
pub struct NORELAOD_LR {
bits: bool,
}
impl NORELAOD_LR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct NORELOAD_HR {
bits: bool,
}
impl NORELOAD_HR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct INSYNCR {
bits: u8,
}
impl INSYNCR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct AUTOLIMIT_LR {
bits: bool,
}
impl AUTOLIMIT_LR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct AUTOLIMIT_HR {
bits: bool,
}
impl AUTOLIMIT_HR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Values that can be written to the field `UNIFY`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum UNIFYW {
#[doc = "The SCT operates as two 16-bit counters named L and H."]
THE_SCT_OPERATES_AS_,
#[doc = "The SCT operates as a unified 32-bit counter."]
UNIFIED,
}
impl UNIFYW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
UNIFYW::THE_SCT_OPERATES_AS_ => false,
UNIFYW::UNIFIED => true,
}
}
}
#[doc = r" Proxy"]
pub struct _UNIFYW<'a> {
w: &'a mut W,
}
impl<'a> _UNIFYW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: UNIFYW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "The SCT operates as two 16-bit counters named L and H."]
#[inline]
pub fn the_sct_operates_as_(self) -> &'a mut W {
self.variant(UNIFYW::THE_SCT_OPERATES_AS_)
}
#[doc = "The SCT operates as a unified 32-bit counter."]
#[inline]
pub fn unified(self) -> &'a mut W {
self.variant(UNIFYW::UNIFIED)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `CLKMODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLKMODEW {
#[doc = "The bus clock clocks the SCT and prescalers."]
THE_BUS_CLOCK_CLOCKS,
#[doc = "The SCT clock is the bus clock, but the prescalers are enabled to count only when sampling of the input selected by the CKSEL field finds the selected edge. The minimum pulse width on the clock input is 1 bus clock period. This mode is the high-performance sampled-clock mode."]
THE_SCT_CLOCK_IS_THE,
#[doc = "The input selected by CKSEL clocks the SCT and prescalers. The input is synchronized to the bus clock and possibly inverted. The minimum pulse width on the clock input is 1 bus clock period. This mode is the low-power sampled-clock mode."]
THE_INPUT_SELECTED_B,
#[doc = "Reserved."]
RESERVED_,
}
impl CLKMODEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
CLKMODEW::THE_BUS_CLOCK_CLOCKS => 0,
CLKMODEW::THE_SCT_CLOCK_IS_THE => 1,
CLKMODEW::THE_INPUT_SELECTED_B => 2,
CLKMODEW::RESERVED_ => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _CLKMODEW<'a> {
w: &'a mut W,
}
impl<'a> _CLKMODEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CLKMODEW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "The bus clock clocks the SCT and prescalers."]
#[inline]
pub fn the_bus_clock_clocks(self) -> &'a mut W {
self.variant(CLKMODEW::THE_BUS_CLOCK_CLOCKS)
}
#[doc = "The SCT clock is the bus clock, but the prescalers are enabled to count only when sampling of the input selected by the CKSEL field finds the selected edge. The minimum pulse width on the clock input is 1 bus clock period. This mode is the high-performance sampled-clock mode."]
#[inline]
pub fn the_sct_clock_is_the(self) -> &'a mut W {
self.variant(CLKMODEW::THE_SCT_CLOCK_IS_THE)
}
#[doc = "The input selected by CKSEL clocks the SCT and prescalers. The input is synchronized to the bus clock and possibly inverted. The minimum pulse width on the clock input is 1 bus clock period. This mode is the low-power sampled-clock mode."]
#[inline]
pub fn the_input_selected_b(self) -> &'a mut W {
self.variant(CLKMODEW::THE_INPUT_SELECTED_B)
}
#[doc = "Reserved."]
#[inline]
pub fn reserved_(self) -> &'a mut W {
self.variant(CLKMODEW::RESERVED_)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `CLKSEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLKSELW {
#[doc = "Rising edges on input 0."]
RISING_EDGES_ON_INPUT_0,
#[doc = "Falling edges on input 0."]
FALLING_EDGES_ON_INPUT_0,
#[doc = "Rising edges on input 1."]
RISING_EDGES_ON_INPUT_1,
#[doc = "Falling edges on input 1."]
FALLING_EDGES_ON_INPUT_1,
#[doc = "Rising edges on input 2."]
RISING_EDGES_ON_INPUT_2,
#[doc = "Falling edges on input 2."]
FALLING_EDGES_ON_INPUT_2,
#[doc = "Rising edges on input 3."]
RISING_EDGES_ON_INPUT_3,
#[doc = "Falling edges on input 3."]
FALLING_EDGES_ON_INPUT_3,
}
impl CLKSELW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
CLKSELW::RISING_EDGES_ON_INPUT_0 => 0,
CLKSELW::FALLING_EDGES_ON_INPUT_0 => 1,
CLKSELW::RISING_EDGES_ON_INPUT_1 => 2,
CLKSELW::FALLING_EDGES_ON_INPUT_1 => 3,
CLKSELW::RISING_EDGES_ON_INPUT_2 => 4,
CLKSELW::FALLING_EDGES_ON_INPUT_2 => 5,
CLKSELW::RISING_EDGES_ON_INPUT_3 => 6,
CLKSELW::FALLING_EDGES_ON_INPUT_3 => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _CLKSELW<'a> {
w: &'a mut W,
}
impl<'a> _CLKSELW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CLKSELW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Rising edges on input 0."]
#[inline]
pub fn rising_edges_on_input_0(self) -> &'a mut W {
self.variant(CLKSELW::RISING_EDGES_ON_INPUT_0)
}
#[doc = "Falling edges on input 0."]
#[inline]
pub fn falling_edges_on_input_0(self) -> &'a mut W {
self.variant(CLKSELW::FALLING_EDGES_ON_INPUT_0)
}
#[doc = "Rising edges on input 1."]
#[inline]
pub fn rising_edges_on_input_1(self) -> &'a mut W {
self.variant(CLKSELW::RISING_EDGES_ON_INPUT_1)
}
#[doc = "Falling edges on input 1."]
#[inline]
pub fn falling_edges_on_input_1(self) -> &'a mut W {
self.variant(CLKSELW::FALLING_EDGES_ON_INPUT_1)
}
#[doc = "Rising edges on input 2."]
#[inline]
pub fn rising_edges_on_input_2(self) -> &'a mut W {
self.variant(CLKSELW::RISING_EDGES_ON_INPUT_2)
}
#[doc = "Falling edges on input 2."]
#[inline]
pub fn falling_edges_on_input_2(self) -> &'a mut W {
self.variant(CLKSELW::FALLING_EDGES_ON_INPUT_2)
}
#[doc = "Rising edges on input 3."]
#[inline]
pub fn rising_edges_on_input_3(self) -> &'a mut W {
self.variant(CLKSELW::RISING_EDGES_ON_INPUT_3)
}
#[doc = "Falling edges on input 3."]
#[inline]
pub fn falling_edges_on_input_3(self) -> &'a mut W {
self.variant(CLKSELW::FALLING_EDGES_ON_INPUT_3)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NORELAOD_LW<'a> {
w: &'a mut W,
}
impl<'a> _NORELAOD_LW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NORELOAD_HW<'a> {
w: &'a mut W,
}
impl<'a> _NORELOAD_HW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _INSYNCW<'a> {
w: &'a mut W,
}
impl<'a> _INSYNCW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 255;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AUTOLIMIT_LW<'a> {
w: &'a mut W,
}
impl<'a> _AUTOLIMIT_LW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 17;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AUTOLIMIT_HW<'a> {
w: &'a mut W,
}
impl<'a> _AUTOLIMIT_HW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 18;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - SCT operation"]
#[inline]
pub fn unify(&self) -> UNIFYR {
UNIFYR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 1:2 - SCT clock mode"]
#[inline]
pub fn clkmode(&self) -> CLKMODER {
CLKMODER::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 3:6 - SCT clock select"]
#[inline]
pub fn clksel(&self) -> CLKSELR {
CLKSELR::_from({
const MASK: u8 = 15;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 7 - A 1 in this bit prevents the lower match registers from being reloaded from their respective reload registers. Software can write to set or clear this bit at any time. This bit applies to both the higher and lower registers when the UNIFY bit is set."]
#[inline]
pub fn norelaod_l(&self) -> NORELAOD_LR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
};
NORELAOD_LR { bits }
}
#[doc = "Bit 8 - A 1 in this bit prevents the higher match registers from being reloaded from their respective reload registers. Software can write to set or clear this bit at any time. This bit is not used when the UNIFY bit is set."]
#[inline]
pub fn noreload_h(&self) -> NORELOAD_HR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
};
NORELOAD_HR { bits }
}
#[doc = "Bits 9:16 - Synchronization for input N (bit 9 = input 0, bit 10 = input 1,..., bit 16 = input 7). A 1 in one of these bits subjects the corresponding input to synchronization to the SCT clock, before it is used to create an event. If an input is synchronous to the SCT clock, keep its bit 0 for faster response. When the CKMODE field is 1x, the bit in this field, corresponding to the input selected by the CKSEL field, is not used."]
#[inline]
pub fn insync(&self) -> INSYNCR {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) as u8
};
INSYNCR { bits }
}
#[doc = "Bit 17 - A one in this bit causes a match on match register 0 to be treated as a de-facto LIMIT condition without the need to define an associated event. As with any LIMIT event, this automatic limit causes the counter to be cleared to zero in uni-directional mode or to change the direction of count in bi-directional mode. Software can write to set or clear this bit at any time. This bit applies to both the higher and lower registers when the UNIFY bit is set."]
#[inline]
pub fn autolimit_l(&self) -> AUTOLIMIT_LR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 17;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AUTOLIMIT_LR { bits }
}
#[doc = "Bit 18 - A one in this bit will cause a match on match register 0 to be treated as a de-facto LIMIT condition without the need to define an associated event. As with any LIMIT event, this automatic limit causes the counter to be cleared to zero in uni-directional mode or to change the direction of count in bi-directional mode. Software can write to set or clear this bit at any time. This bit is not used when the UNIFY bit is set."]
#[inline]
pub fn autolimit_h(&self) -> AUTOLIMIT_HR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 18;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AUTOLIMIT_HR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 32256 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - SCT operation"]
#[inline]
pub fn unify(&mut self) -> _UNIFYW {
_UNIFYW { w: self }
}
#[doc = "Bits 1:2 - SCT clock mode"]
#[inline]
pub fn clkmode(&mut self) -> _CLKMODEW {
_CLKMODEW { w: self }
}
#[doc = "Bits 3:6 - SCT clock select"]
#[inline]
pub fn clksel(&mut self) -> _CLKSELW {
_CLKSELW { w: self }
}
#[doc = "Bit 7 - A 1 in this bit prevents the lower match registers from being reloaded from their respective reload registers. Software can write to set or clear this bit at any time. This bit applies to both the higher and lower registers when the UNIFY bit is set."]
#[inline]
pub fn norelaod_l(&mut self) -> _NORELAOD_LW {
_NORELAOD_LW { w: self }
}
#[doc = "Bit 8 - A 1 in this bit prevents the higher match registers from being reloaded from their respective reload registers. Software can write to set or clear this bit at any time. This bit is not used when the UNIFY bit is set."]
#[inline]
pub fn noreload_h(&mut self) -> _NORELOAD_HW {
_NORELOAD_HW { w: self }
}
#[doc = "Bits 9:16 - Synchronization for input N (bit 9 = input 0, bit 10 = input 1,..., bit 16 = input 7). A 1 in one of these bits subjects the corresponding input to synchronization to the SCT clock, before it is used to create an event. If an input is synchronous to the SCT clock, keep its bit 0 for faster response. When the CKMODE field is 1x, the bit in this field, corresponding to the input selected by the CKSEL field, is not used."]
#[inline]
pub fn insync(&mut self) -> _INSYNCW {
_INSYNCW { w: self }
}
#[doc = "Bit 17 - A one in this bit causes a match on match register 0 to be treated as a de-facto LIMIT condition without the need to define an associated event. As with any LIMIT event, this automatic limit causes the counter to be cleared to zero in uni-directional mode or to change the direction of count in bi-directional mode. Software can write to set or clear this bit at any time. This bit applies to both the higher and lower registers when the UNIFY bit is set."]
#[inline]
pub fn autolimit_l(&mut self) -> _AUTOLIMIT_LW {
_AUTOLIMIT_LW { w: self }
}
#[doc = "Bit 18 - A one in this bit will cause a match on match register 0 to be treated as a de-facto LIMIT condition without the need to define an associated event. As with any LIMIT event, this automatic limit causes the counter to be cleared to zero in uni-directional mode or to change the direction of count in bi-directional mode. Software can write to set or clear this bit at any time. This bit is not used when the UNIFY bit is set."]
#[inline]
pub fn autolimit_h(&mut self) -> _AUTOLIMIT_HW {
_AUTOLIMIT_HW { w: self }
}
}
|
extern crate afl;
extern crate proc_macro2;
fn main() {
afl::read_stdio_string(|string| {
if let Ok(token_stream) = string.parse::<proc_macro2::TokenStream>() {
for _ in token_stream { }
}
});
}
|
pub enum SpliffError {
SolanaAPIError(String),
SolanaProgramError(String),
InputError(String),
}
|
//! Literals and variables.
use std::{fmt, ops};
/// The backing type used to represent literals and variables.
pub type LitIdx = u32;
/// A boolean variable.
///
/// A boolean value is represented by an index. Internally these are 0-based, i.e. the first
/// variable has the index 0. For user IO a 1-based index is used, to allow denoting negated
/// variables using negative integers. This convention is also used in the DIMACS CNF format.
///
/// Creating a variable with an index larger than `Var::max_var().index()` is unsupported. This
/// might panic or be interpreted as a different variable.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Var {
index: LitIdx,
}
impl Var {
/// Creates a variable from a 1-based index as used in the DIMCAS CNF encoding.
///
/// The parameter must be positive and may not represent a variable past `Var::max_var()`.
#[inline]
pub fn from_dimacs(number: isize) -> Var {
debug_assert!(number > 0);
Var::from_index((number - 1) as usize)
}
/// Creates a variable from a 0-based index.
///
/// The index may not represent a variable past `Var::max_var()`.
#[inline]
pub fn from_index(index: usize) -> Var {
debug_assert!(index <= Var::max_var().index());
Var {
index: index as LitIdx,
}
}
/// The 1-based index representing this variable in the DIMACS CNF encoding.
#[inline]
pub fn to_dimacs(self) -> isize {
(self.index + 1) as isize
}
/// The 0-based index representing this variable.
#[inline]
pub const fn index(self) -> usize {
self.index as usize
}
/// The variable with largest index that is supported.
///
/// This is less than the backing integer type supports. This enables storing a variable index
/// and additional bits (as in `Lit`) or sentinel values in a single word.
pub const fn max_var() -> Var {
// Allow for sign or tag bits
Var {
index: LitIdx::max_value() >> 4,
}
}
/// Largest number of variables supported.
///
/// This is exactly `Var::max_var().index() + 1`.
pub const fn max_count() -> usize {
Self::max_var().index() + 1
}
/// Creates a literal from this var and a `bool` that is `true` when the literal is positive.
///
/// Shortcut for `Lit::from_var(var, polarity)`.
#[inline]
pub fn lit(self, polarity: bool) -> Lit {
Lit::from_var(self, polarity)
}
/// Creates a positive literal from this var.
///
/// Shortcut for `Lit::positive(var)`.
#[inline]
pub fn positive(self) -> Lit {
Lit::positive(self)
}
/// Creates a negative literal from this var.
///
/// Shortcut for `Lit::negative(var)`.
#[inline]
pub fn negative(self) -> Lit {
Lit::negative(self)
}
}
/// Uses the 1-based DIMACS CNF encoding.
impl fmt::Debug for Var {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_dimacs())
}
}
/// Uses the 1-based DIMACS CNF encoding.
impl fmt::Display for Var {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
/// A boolean literal.
///
/// A literal is a variable or the negation of a variable.
///
/// Conceptually a literal consists of a `Var` and a `bool` indicating whether the literal
/// represents the variable (positive literal) or its negation (negative literal).
///
/// Internally a literal is represented as an integer that is two times the index of its variable
/// when it is positive or one more when it is negative. This integer is called the `code` of the
/// literal.
///
/// The restriction on the range of allowed indices for `Var` also applies to `Lit`.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Lit {
code: LitIdx,
}
impl Lit {
/// Creates a literal from a `Var` and a `bool` that is `true` when the literal is positive.
#[inline]
pub fn from_var(var: Var, polarity: bool) -> Lit {
Lit::from_litidx(var.index, polarity)
}
/// Create a positive literal from a `Var`.
#[inline]
pub fn positive(var: Var) -> Lit {
Lit::from_var(var, true)
}
/// Create a negative literal from a `Var`.
#[inline]
pub fn negative(var: Var) -> Lit {
Lit::from_var(var, false)
}
/// Create a literal from a variable index and a `bool` that is `true` when the literal is
/// positive.
#[inline]
pub fn from_index(index: usize, polarity: bool) -> Lit {
Lit::from_var(Var::from_index(index), polarity)
}
/// Create a literal with the given encoding.
#[inline]
pub fn from_code(code: usize) -> Lit {
debug_assert!(code <= Var::max_var().index() * 2 + 1);
Lit {
code: code as LitIdx,
}
}
#[inline]
fn from_litidx(index: LitIdx, polarity: bool) -> Lit {
debug_assert!(index <= Var::max_var().index);
Lit {
code: (index << 1) | (!polarity as LitIdx),
}
}
/// Creates a literal from an integer.
///
/// The absolute value is used as 1-based index, the sign of
/// the integer is used as sign of the literal.
#[inline]
pub fn from_dimacs(number: isize) -> Lit {
Lit::from_var(Var::from_dimacs(number.abs()), number > 0)
}
/// 1-based Integer representation of the literal, opposite of `from_dimacs`.
#[inline]
pub fn to_dimacs(self) -> isize {
let mut number = self.var().to_dimacs();
if self.is_negative() {
number = -number
}
number
}
/// 0-based index of the literal's _variable_.
#[inline]
pub fn index(self) -> usize {
(self.code >> 1) as usize
}
/// The literal's variable.
#[inline]
pub fn var(self) -> Var {
Var {
index: self.code >> 1,
}
}
/// Whether the literal is negative, i.e. a negated variable.
#[inline]
pub fn is_negative(self) -> bool {
(self.code & 1) != 0
}
/// Whether the literal is positive, i.e. a non-negated variable.
#[inline]
pub fn is_positive(self) -> bool {
!self.is_negative()
}
/// Two times the variable's index for positive literals and one more for negative literals.
///
/// This is also the internal encoding.
#[inline]
pub fn code(self) -> usize {
self.code as usize
}
/// Apply a function to the variable of the literal, without changing the polarity.
#[inline]
pub fn map_var(self, f: impl FnOnce(Var) -> Var) -> Lit {
f(self.var()).lit(self.is_positive())
}
}
impl ops::Not for Lit {
type Output = Lit;
#[inline]
fn not(self) -> Lit {
Lit {
code: self.code ^ 1,
}
}
}
impl ops::BitXor<bool> for Lit {
type Output = Lit;
#[inline]
fn bitxor(self, rhs: bool) -> Lit {
Lit {
code: self.code ^ (rhs as LitIdx),
}
}
}
impl From<Var> for Lit {
#[inline]
fn from(var: Var) -> Lit {
Lit::positive(var)
}
}
/// Uses the 1-based DIMACS CNF encoding.
impl fmt::Debug for Lit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.to_dimacs())
}
}
/// Uses the 1-based DIMACS CNF encoding.
impl fmt::Display for Lit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
#[cfg(any(test, feature = "proptest-strategies"))]
#[doc(hidden)]
pub mod strategy {
use super::*;
use proptest::{prelude::*, *};
pub fn var(index: impl Strategy<Value = usize>) -> impl Strategy<Value = Var> {
index.prop_map(Var::from_index)
}
pub fn lit(index: impl Strategy<Value = usize>) -> impl Strategy<Value = Lit> {
(var(index), bool::ANY).prop_map(|(var, polarity)| var.lit(polarity))
}
}
|
use log::info;
use std::{
array::TryFromSliceError, convert::TryInto, fs, io, path::Path, thread,
time::Duration,
};
pub type DeviceHandle = rusb::DeviceHandle<rusb::Context>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io error: {0}")]
IoError(io::Error),
/// "CY" prefix is missing
#[error("invalid prefix")]
MissingMagic,
#[error("image is not executable")]
NotExecutable,
#[error("abnormal image")]
AbnormalFirmware,
#[error("invalid checksum")]
InvalidChecksum,
#[error("truncated data: {0}")]
TruncatedData(TryFromSliceError),
#[error("usb error: {0}")]
UsbError(rusb::Error),
}
struct Checksum {
value: u32,
}
impl Checksum {
fn new() -> Checksum {
Checksum { value: 0 }
}
fn update(&mut self, data: &[u8]) -> Result<(), Error> {
let mut offset = 0;
while offset < data.len() {
let chunk = &data[offset..offset + 4];
let val = u32::from_le_bytes(
chunk.try_into().map_err(Error::TruncatedData)?,
);
self.value = self.value.overflowing_add(val).0;
offset += 4;
}
Ok(())
}
}
fn write_control(
device: &DeviceHandle,
address: u32,
data: &[u8],
) -> Result<usize, Error> {
let bytes_written = device
.write_control(
/*request_type=*/ 0x40,
/*request=*/ 0xa0,
/*value=*/ (address & 0x0000ffff) as u16,
/*index=*/ (address >> 16) as u16,
/*buf=*/ data,
/*timeout=*/ Duration::from_secs(1),
)
.map_err(Error::UsbError)?;
Ok(bytes_written)
}
fn control_transfer(
device: &DeviceHandle,
mut address: u32,
data: &[u8],
) -> Result<(), Error> {
let mut balance = data.len() as u32;
let mut offset = 0;
while balance > 0 {
let mut b = if balance > 4096 { 4096 } else { balance };
let bytes_written = write_control(
device,
address,
&data[offset as usize..(offset + b) as usize],
)?;
b = bytes_written as u32;
address += b;
balance -= b;
offset += b;
}
Ok(())
}
/// Download firmware to RAM on a Cypress FX3
pub fn program_fx3_ram(
device: &DeviceHandle,
path: &Path,
) -> Result<(), Error> {
// Firmware files should be quite small, so just load the whole
// thing in memory
let program = fs::read(path).map_err(Error::IoError)?;
// Program must start with "CY"
if program[0] != b'C' || program[1] != b'Y' {
return Err(Error::MissingMagic);
}
// Check that the image contains executable code
if (program[2] & 0x01) != 0 {
return Err(Error::NotExecutable);
}
// Check for a normal FW binary with checksum
if program[3] != 0xb0 {
return Err(Error::AbnormalFirmware);
}
let mut offset = 4;
let mut checksum = Checksum::new();
let entry_address;
let read_u32 = |offset: &mut usize| {
let chunk = &program[*offset..*offset + 4];
let val =
u32::from_le_bytes(chunk.try_into().map_err(Error::TruncatedData)?);
*offset += 4;
Ok(val)
};
// Transfer the program to the FX3
info!("transfering program to the device");
loop {
let length = read_u32(&mut offset)?;
let address = read_u32(&mut offset)?;
if length == 0 {
entry_address = address;
break;
} else {
let data = &program[offset..offset + (length as usize) * 4];
offset += (length as usize) * 4;
checksum.update(data)?;
control_transfer(device, address, data)?;
}
}
// Read checksum
info!("validating checksum");
let expected_checksum = read_u32(&mut offset)?;
if expected_checksum != checksum.value {
return Err(Error::InvalidChecksum);
}
thread::sleep(Duration::from_secs(1));
write_control(device, entry_address, &[])?;
Ok(())
}
|
use gateway::UnitGateway;
use std::sync::{Arc, Mutex};
#[derive(PartialEq, Eq, Debug)]
pub struct PresentableUnit {
pub health: u8
}
pub trait ViewUnitsPresenter {
fn present(&self, presentable_unit: PresentableUnit);
}
pub struct ViewUnits {
unit_gateway: Arc<Mutex<UnitGateway>>
}
impl ViewUnits {
pub fn new(unit_gateway: Arc<Mutex<UnitGateway>>) -> Self {
return ViewUnits { unit_gateway };
}
pub fn execute(self, presenter: &mut ViewUnitsPresenter) {
let result = self.unit_gateway.lock().unwrap().get_units_stream().recv();
if !result.is_err() {
presenter.present(PresentableUnit { health: u8::max_value() })
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::sync::mpsc::*;
use domain::Unit;
struct SpyPresenter {
last_presentable_unit: Cell<Option<PresentableUnit>>
}
impl SpyPresenter {
fn new() -> Self {
return SpyPresenter { last_presentable_unit: Cell::new(None) };
}
fn get_last_presentable_unit(&self) -> Option<PresentableUnit> {
return self.last_presentable_unit.take();
}
}
impl ViewUnitsPresenter for SpyPresenter {
fn present(&self, presentable_unit: PresentableUnit) {
self.last_presentable_unit.set(Some(presentable_unit))
}
}
struct EmptyUnitsGatewayStub {}
impl UnitGateway for EmptyUnitsGatewayStub {
fn get_units_stream(&self) -> Receiver<Unit> {
let (_, receiver) = channel();
return receiver;
}
}
struct OneUnitGatewayStub {}
impl UnitGateway for OneUnitGatewayStub {
fn get_units_stream(&self) -> Receiver<Unit> {
let (sender, receiver) = channel();
sender.send(Unit {});
return receiver;
}
}
#[test]
fn can_present_no_units() {
let gateway = EmptyUnitsGatewayStub {};
let use_case = ViewUnits::new(Arc::new(Mutex::new(gateway)));
let mut presenter = SpyPresenter::new();
use_case.execute(&mut presenter);
assert_eq!(
presenter.get_last_presentable_unit(),
None
);
}
#[test]
fn can_present_a_unit() {
let gateway = OneUnitGatewayStub {};
let use_case = ViewUnits::new(Arc::new(Mutex::new(gateway)));
let mut presenter = SpyPresenter::new();
use_case.execute(&mut presenter);
assert_eq!(
presenter.get_last_presentable_unit().unwrap(),
PresentableUnit { health: u8::max_value() }
);
}
} |
use super::{
mappingproxy::PyMappingProxy, object, union_, PyClassMethod, PyDictRef, PyList, PyStr,
PyStrInterned, PyStrRef, PyTuple, PyTupleRef, PyWeak,
};
use crate::{
builtins::{
descriptor::{
MemberGetter, MemberKind, MemberSetter, PyDescriptorOwned, PyMemberDef,
PyMemberDescriptor,
},
function::PyCellRef,
tuple::{IntoPyTuple, PyTupleTyped},
PyBaseExceptionRef,
},
class::{PyClassImpl, StaticType},
common::{
ascii,
borrow::BorrowedValue,
lock::{PyRwLock, PyRwLockReadGuard},
},
convert::ToPyResult,
function::{FuncArgs, KwArgs, OptionalArg, PyMethodDef, PySetterValue},
identifier,
object::{Traverse, TraverseFn},
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
types::{AsNumber, Callable, GetAttr, PyTypeFlags, PyTypeSlots, Representable, SetAttr},
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine,
};
use indexmap::{map::Entry, IndexMap};
use itertools::Itertools;
use std::{borrow::Borrow, collections::HashSet, fmt, ops::Deref, pin::Pin, ptr::NonNull};
#[pyclass(module = false, name = "type", traverse = "manual")]
pub struct PyType {
pub base: Option<PyTypeRef>,
pub bases: Vec<PyTypeRef>,
pub mro: Vec<PyTypeRef>,
pub subclasses: PyRwLock<Vec<PyRef<PyWeak>>>,
pub attributes: PyRwLock<PyAttributes>,
pub slots: PyTypeSlots,
pub heaptype_ext: Option<Pin<Box<HeapTypeExt>>>,
}
unsafe impl crate::object::Traverse for PyType {
fn traverse(&self, tracer_fn: &mut crate::object::TraverseFn) {
self.base.traverse(tracer_fn);
self.bases.traverse(tracer_fn);
self.mro.traverse(tracer_fn);
self.subclasses.traverse(tracer_fn);
self.attributes
.read_recursive()
.iter()
.map(|(_, v)| v.traverse(tracer_fn))
.count();
}
}
pub struct HeapTypeExt {
pub name: PyRwLock<PyStrRef>,
pub slots: Option<PyTupleTyped<PyStrRef>>,
pub sequence_methods: PySequenceMethods,
pub mapping_methods: PyMappingMethods,
}
pub struct PointerSlot<T>(NonNull<T>);
impl<T> PointerSlot<T> {
pub unsafe fn borrow_static(&self) -> &'static T {
self.0.as_ref()
}
}
impl<T> Clone for PointerSlot<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for PointerSlot<T> {}
impl<T> From<&'static T> for PointerSlot<T> {
fn from(x: &'static T) -> Self {
Self(NonNull::from(x))
}
}
impl<T> AsRef<T> for PointerSlot<T> {
fn as_ref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}
impl<T> PointerSlot<T> {
pub unsafe fn from_heaptype<F>(typ: &PyType, f: F) -> Option<Self>
where
F: FnOnce(&HeapTypeExt) -> &T,
{
typ.heaptype_ext
.as_ref()
.map(|ext| Self(NonNull::from(f(ext))))
}
}
pub type PyTypeRef = PyRef<PyType>;
cfg_if::cfg_if! {
if #[cfg(feature = "threading")] {
unsafe impl Send for PyType {}
unsafe impl Sync for PyType {}
}
}
/// For attributes we do not use a dict, but an IndexMap, which is an Hash Table
/// that maintains order and is compatible with the standard HashMap This is probably
/// faster and only supports strings as keys.
pub type PyAttributes = IndexMap<&'static PyStrInterned, PyObjectRef, ahash::RandomState>;
unsafe impl Traverse for PyAttributes {
fn traverse(&self, tracer_fn: &mut TraverseFn) {
self.values().for_each(|v| v.traverse(tracer_fn));
}
}
impl fmt::Display for PyType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.name(), f)
}
}
impl fmt::Debug for PyType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[PyType {}]", &self.name())
}
}
impl PyPayload for PyType {
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.type_type
}
}
impl PyType {
pub fn new_simple_heap(
name: &str,
base: &PyTypeRef,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
Self::new_heap(
name,
vec![base.clone()],
Default::default(),
Default::default(),
Self::static_type().to_owned(),
ctx,
)
}
pub fn new_heap(
name: &str,
bases: Vec<PyRef<Self>>,
attrs: PyAttributes,
slots: PyTypeSlots,
metaclass: PyRef<Self>,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
// TODO: ensure clean slot name
// assert_eq!(slots.name.borrow(), "");
let name = ctx.new_str(name);
let heaptype_ext = HeapTypeExt {
name: PyRwLock::new(name),
slots: None,
sequence_methods: PySequenceMethods::default(),
mapping_methods: PyMappingMethods::default(),
};
let base = bases[0].clone();
Self::new_heap_inner(base, bases, attrs, slots, heaptype_ext, metaclass, ctx)
}
#[allow(clippy::too_many_arguments)]
fn new_heap_inner(
base: PyRef<Self>,
bases: Vec<PyRef<Self>>,
attrs: PyAttributes,
mut slots: PyTypeSlots,
heaptype_ext: HeapTypeExt,
metaclass: PyRef<Self>,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
// Check for duplicates in bases.
let mut unique_bases = HashSet::new();
for base in &bases {
if !unique_bases.insert(base.get_id()) {
return Err(format!("duplicate base class {}", base.name()));
}
}
let mros = bases
.iter()
.map(|x| x.iter_mro().map(|x| x.to_owned()).collect())
.collect();
let mro = linearise_mro(mros)?;
if base.slots.flags.has_feature(PyTypeFlags::HAS_DICT) {
slots.flags |= PyTypeFlags::HAS_DICT
}
let new_type = PyRef::new_ref(
PyType {
base: Some(base),
bases,
mro,
subclasses: PyRwLock::default(),
attributes: PyRwLock::new(attrs),
slots,
heaptype_ext: Some(Pin::new(Box::new(heaptype_ext))),
},
metaclass,
None,
);
new_type.init_slots(ctx);
let weakref_type = super::PyWeak::static_type();
for base in &new_type.bases {
base.subclasses.write().push(
new_type
.as_object()
.downgrade_with_weakref_typ_opt(None, weakref_type.to_owned())
.unwrap(),
);
}
Ok(new_type)
}
pub fn new_static(
base: PyRef<Self>,
attrs: PyAttributes,
mut slots: PyTypeSlots,
metaclass: PyRef<Self>,
) -> Result<PyRef<Self>, String> {
if base.slots.flags.has_feature(PyTypeFlags::HAS_DICT) {
slots.flags |= PyTypeFlags::HAS_DICT
}
let bases = vec![base.clone()];
let mro = base.iter_mro().map(|x| x.to_owned()).collect();
let new_type = PyRef::new_ref(
PyType {
base: Some(base),
bases,
mro,
subclasses: PyRwLock::default(),
attributes: PyRwLock::new(attrs),
slots,
heaptype_ext: None,
},
metaclass,
None,
);
let weakref_type = super::PyWeak::static_type();
for base in &new_type.bases {
base.subclasses.write().push(
new_type
.as_object()
.downgrade_with_weakref_typ_opt(None, weakref_type.to_owned())
.unwrap(),
);
}
Ok(new_type)
}
pub(crate) fn init_slots(&self, ctx: &Context) {
#[allow(clippy::mutable_key_type)]
let mut slot_name_set = std::collections::HashSet::new();
for cls in self.mro.iter() {
for &name in cls.attributes.read().keys() {
if name == identifier!(ctx, __new__) {
continue;
}
if name.as_str().starts_with("__") && name.as_str().ends_with("__") {
slot_name_set.insert(name);
}
}
}
for &name in self.attributes.read().keys() {
if name.as_str().starts_with("__") && name.as_str().ends_with("__") {
slot_name_set.insert(name);
}
}
for attr_name in slot_name_set {
self.update_slot::<true>(attr_name, ctx);
}
}
pub fn iter_mro(&self) -> impl Iterator<Item = &PyType> + DoubleEndedIterator {
std::iter::once(self).chain(self.mro.iter().map(|cls| -> &PyType { cls }))
}
pub(crate) fn mro_find_map<F, R>(&self, f: F) -> Option<R>
where
F: Fn(&Self) -> Option<R>,
{
// the hot path will be primitive types which usually hit the result from itself.
// try std::intrinsics::likely once it is stablized
if let Some(r) = f(self) {
Some(r)
} else {
self.mro.iter().find_map(|cls| f(cls))
}
}
// This is used for class initialisation where the vm is not yet available.
pub fn set_str_attr<V: Into<PyObjectRef>>(
&self,
attr_name: &str,
value: V,
ctx: impl AsRef<Context>,
) {
let ctx = ctx.as_ref();
let attr_name = ctx.intern_str(attr_name);
self.set_attr(attr_name, value.into())
}
pub fn set_attr(&self, attr_name: &'static PyStrInterned, value: PyObjectRef) {
self.attributes.write().insert(attr_name, value);
}
/// This is the internal get_attr implementation for fast lookup on a class.
pub fn get_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> {
flame_guard!(format!("class_get_attr({:?})", attr_name));
self.get_direct_attr(attr_name)
.or_else(|| self.get_super_attr(attr_name))
}
pub fn get_direct_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> {
self.attributes.read().get(attr_name).cloned()
}
pub fn get_super_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> {
self.mro
.iter()
.find_map(|class| class.attributes.read().get(attr_name).cloned())
}
// This is the internal has_attr implementation for fast lookup on a class.
pub fn has_attr(&self, attr_name: &'static PyStrInterned) -> bool {
self.attributes.read().contains_key(attr_name)
|| self
.mro
.iter()
.any(|c| c.attributes.read().contains_key(attr_name))
}
pub fn get_attributes(&self) -> PyAttributes {
// Gather all members here:
let mut attributes = PyAttributes::default();
for bc in self.iter_mro().rev() {
for (name, value) in bc.attributes.read().iter() {
attributes.insert(name.to_owned(), value.clone());
}
}
attributes
}
// bound method for every type
pub(crate) fn __new__(zelf: PyRef<PyType>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let (subtype, args): (PyRef<Self>, FuncArgs) = args.bind(vm)?;
if !subtype.fast_issubclass(&zelf) {
return Err(vm.new_type_error(format!(
"{zelf}.__new__({subtype}): {subtype} is not a subtype of {zelf}",
zelf = zelf.name(),
subtype = subtype.name(),
)));
}
call_slot_new(zelf, subtype, args, vm)
}
fn name_inner<'a, R: 'a>(
&'a self,
static_f: impl FnOnce(&'static str) -> R,
heap_f: impl FnOnce(&'a HeapTypeExt) -> R,
) -> R {
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
static_f(self.slots.name)
} else {
heap_f(self.heaptype_ext.as_ref().unwrap())
}
}
pub fn slot_name(&self) -> BorrowedValue<str> {
self.name_inner(
|name| name.into(),
|ext| PyRwLockReadGuard::map(ext.name.read(), |name| name.as_str()).into(),
)
}
pub fn name(&self) -> BorrowedValue<str> {
self.name_inner(
|name| name.rsplit_once('.').map_or(name, |(_, name)| name).into(),
|ext| PyRwLockReadGuard::map(ext.name.read(), |name| name.as_str()).into(),
)
}
}
impl Py<PyType> {
/// Determines if `subclass` is actually a subclass of `cls`, this doesn't call __subclasscheck__,
/// so only use this if `cls` is known to have not overridden the base __subclasscheck__ magic
/// method.
pub fn fast_issubclass(&self, cls: &impl Borrow<crate::PyObject>) -> bool {
self.as_object().is(cls.borrow()) || self.mro.iter().any(|c| c.is(cls.borrow()))
}
pub fn iter_mro(&self) -> impl Iterator<Item = &Py<PyType>> + DoubleEndedIterator {
std::iter::once(self).chain(self.mro.iter().map(|x| x.deref()))
}
pub fn iter_base_chain(&self) -> impl Iterator<Item = &Py<PyType>> {
std::iter::successors(Some(self), |cls| cls.base.as_deref())
}
pub fn extend_methods(&'static self, method_defs: &'static [PyMethodDef], ctx: &Context) {
for method_def in method_defs {
let method = method_def.to_proper_method(self, ctx);
self.set_attr(ctx.intern_str(method_def.name), method);
}
}
}
#[pyclass(
with(Py, GetAttr, SetAttr, Callable, AsNumber, Representable),
flags(BASETYPE)
)]
impl PyType {
#[pygetset(magic)]
fn bases(&self, vm: &VirtualMachine) -> PyTupleRef {
vm.ctx.new_tuple(
self.bases
.iter()
.map(|x| x.as_object().to_owned())
.collect(),
)
}
#[pygetset(magic)]
fn base(&self) -> Option<PyTypeRef> {
self.base.clone()
}
#[pygetset(magic)]
fn flags(&self) -> u64 {
self.slots.flags.bits()
}
#[pygetset]
pub fn __name__(&self, vm: &VirtualMachine) -> PyStrRef {
self.name_inner(
|name| {
vm.ctx
.interned_str(name.rsplit_once('.').map_or(name, |(_, name)| name))
.unwrap_or_else(|| {
panic!(
"static type name must be already interned but {} is not",
self.slot_name()
)
})
.to_owned()
},
|ext| ext.name.read().clone(),
)
}
#[pygetset(magic)]
pub fn qualname(&self, vm: &VirtualMachine) -> PyObjectRef {
self.attributes
.read()
.get(identifier!(vm, __qualname__))
.cloned()
// We need to exclude this method from going into recursion:
.and_then(|found| {
if found.fast_isinstance(vm.ctx.types.getset_type) {
None
} else {
Some(found)
}
})
.unwrap_or_else(|| vm.ctx.new_str(self.name().deref()).into())
}
#[pygetset(magic, setter)]
fn set_qualname(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
// TODO: we should replace heaptype flag check to immutable flag check
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
return Err(vm.new_type_error(format!(
"cannot set '__qualname__' attribute of immutable type '{}'",
self.name()
)));
};
let value = value.ok_or_else(|| {
vm.new_type_error(format!(
"cannot delete '__qualname__' attribute of immutable type '{}'",
self.name()
))
})?;
if !value.class().fast_issubclass(vm.ctx.types.str_type) {
return Err(vm.new_type_error(format!(
"can only assign string to {}.__qualname__, not '{}'",
self.name(),
value.class().name()
)));
}
self.attributes
.write()
.insert(identifier!(vm, __qualname__), value);
Ok(())
}
#[pygetset(magic)]
fn annotations(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
return Err(vm.new_attribute_error(format!(
"type object '{}' has no attribute '__annotations__'",
self.name()
)));
}
let __annotations__ = identifier!(vm, __annotations__);
let annotations = self.attributes.read().get(__annotations__).cloned();
let annotations = if let Some(annotations) = annotations {
annotations
} else {
let annotations: PyObjectRef = vm.ctx.new_dict().into();
let removed = self
.attributes
.write()
.insert(__annotations__, annotations.clone());
debug_assert!(removed.is_none());
annotations
};
Ok(annotations)
}
#[pygetset(magic, setter)]
fn set_annotations(&self, value: Option<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> {
if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
return Err(vm.new_type_error(format!(
"cannot set '__annotations__' attribute of immutable type '{}'",
self.name()
)));
}
let __annotations__ = identifier!(vm, __annotations__);
if let Some(value) = value {
self.attributes.write().insert(__annotations__, value);
} else {
self.attributes
.read()
.get(__annotations__)
.cloned()
.ok_or_else(|| {
vm.new_attribute_error(format!(
"'{}' object has no attribute '__annotations__'",
self.name()
))
})?;
}
Ok(())
}
#[pygetset(magic)]
pub fn module(&self, vm: &VirtualMachine) -> PyObjectRef {
self.attributes
.read()
.get(identifier!(vm, __module__))
.cloned()
// We need to exclude this method from going into recursion:
.and_then(|found| {
if found.fast_isinstance(vm.ctx.types.getset_type) {
None
} else {
Some(found)
}
})
.unwrap_or_else(|| vm.ctx.new_str(ascii!("builtins")).into())
}
#[pygetset(magic, setter)]
fn set_module(&self, value: PyObjectRef, vm: &VirtualMachine) {
self.attributes
.write()
.insert(identifier!(vm, __module__), value);
}
#[pyclassmethod(magic)]
fn prepare(
_cls: PyTypeRef,
_name: OptionalArg<PyObjectRef>,
_bases: OptionalArg<PyObjectRef>,
_kwargs: KwArgs,
vm: &VirtualMachine,
) -> PyDictRef {
vm.ctx.new_dict()
}
#[pymethod(magic)]
fn subclasses(&self) -> PyList {
let mut subclasses = self.subclasses.write();
subclasses.retain(|x| x.upgrade().is_some());
PyList::from(
subclasses
.iter()
.map(|x| x.upgrade().unwrap())
.collect::<Vec<_>>(),
)
}
#[pymethod(magic)]
pub fn ror(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(other, zelf, vm)
}
#[pymethod(magic)]
pub fn or(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(zelf, other, vm)
}
#[pyslot]
fn slot_new(metatype: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
vm_trace!("type.__new__ {:?}", args);
let is_type_type = metatype.is(vm.ctx.types.type_type);
if is_type_type && args.args.len() == 1 && args.kwargs.is_empty() {
return Ok(args.args[0].class().to_owned().into());
}
if args.args.len() != 3 {
return Err(vm.new_type_error(if is_type_type {
"type() takes 1 or 3 arguments".to_owned()
} else {
format!(
"type.__new__() takes exactly 3 arguments ({} given)",
args.args.len()
)
}));
}
let (name, bases, dict, kwargs): (PyStrRef, PyTupleRef, PyDictRef, KwArgs) =
args.clone().bind(vm)?;
if name.as_str().as_bytes().contains(&0) {
return Err(vm.new_value_error("type name must not contain null characters".to_owned()));
}
let (metatype, base, bases) = if bases.is_empty() {
let base = vm.ctx.types.object_type.to_owned();
(metatype, base.clone(), vec![base])
} else {
let bases = bases
.iter()
.map(|obj| {
obj.clone().downcast::<PyType>().or_else(|obj| {
if vm
.get_attribute_opt(obj, identifier!(vm, __mro_entries__))?
.is_some()
{
Err(vm.new_type_error(
"type() doesn't support MRO entry resolution; \
use types.new_class()"
.to_owned(),
))
} else {
Err(vm.new_type_error("bases must be types".to_owned()))
}
})
})
.collect::<PyResult<Vec<_>>>()?;
// Search the bases for the proper metatype to deal with this:
let winner = calculate_meta_class(metatype.clone(), &bases, vm)?;
let metatype = if !winner.is(&metatype) {
if let Some(ref slot_new) = winner.slots.new.load() {
// Pass it to the winner
return slot_new(winner, args, vm);
}
winner
} else {
metatype
};
let base = best_base(&bases, vm)?;
(metatype, base, bases)
};
let mut attributes = dict.to_attributes(vm);
if let Some(f) = attributes.get_mut(identifier!(vm, __init_subclass__)) {
if f.class().is(vm.ctx.types.function_type) {
*f = PyClassMethod::from(f.clone()).into_pyobject(vm);
}
}
if let Some(f) = attributes.get_mut(identifier!(vm, __class_getitem__)) {
if f.class().is(vm.ctx.types.function_type) {
*f = PyClassMethod::from(f.clone()).into_pyobject(vm);
}
}
if let Some(current_frame) = vm.current_frame() {
let entry = attributes.entry(identifier!(vm, __module__));
if matches!(entry, Entry::Vacant(_)) {
let module_name = vm.unwrap_or_none(
current_frame
.globals
.get_item_opt(identifier!(vm, __name__), vm)?,
);
entry.or_insert(module_name);
}
}
attributes
.entry(identifier!(vm, __qualname__))
.or_insert_with(|| vm.ctx.new_str(name.as_str()).into());
// All *classes* should have a dict. Exceptions are *instances* of
// classes that define __slots__ and instances of built-in classes
// (with exceptions, e.g function)
let __dict__ = identifier!(vm, __dict__);
attributes.entry(__dict__).or_insert_with(|| {
vm.ctx
.new_getset(
"__dict__",
vm.ctx.types.object_type,
subtype_get_dict,
subtype_set_dict,
)
.into()
});
// TODO: Flags is currently initialized with HAS_DICT. Should be
// updated when __slots__ are supported (toggling the flag off if
// a class has __slots__ defined).
let heaptype_slots: Option<PyTupleTyped<PyStrRef>> =
if let Some(x) = attributes.get(identifier!(vm, __slots__)) {
Some(if x.to_owned().class().is(vm.ctx.types.str_type) {
PyTupleTyped::<PyStrRef>::try_from_object(
vm,
vec![x.to_owned()].into_pytuple(vm).into(),
)?
} else {
let iter = x.to_owned().get_iter(vm)?;
let elements = {
let mut elements = Vec::new();
while let PyIterReturn::Return(element) = iter.next(vm)? {
elements.push(element);
}
elements
};
PyTupleTyped::<PyStrRef>::try_from_object(vm, elements.into_pytuple(vm).into())?
})
} else {
None
};
let base_member_count = base.slots.member_count;
let member_count: usize =
base.slots.member_count + heaptype_slots.as_ref().map(|x| x.len()).unwrap_or(0);
let flags = PyTypeFlags::heap_type_flags() | PyTypeFlags::HAS_DICT;
let (slots, heaptype_ext) = {
let slots = PyTypeSlots {
member_count,
flags,
..PyTypeSlots::heap_default()
};
let heaptype_ext = HeapTypeExt {
name: PyRwLock::new(name),
slots: heaptype_slots.to_owned(),
sequence_methods: PySequenceMethods::default(),
mapping_methods: PyMappingMethods::default(),
};
(slots, heaptype_ext)
};
let typ = Self::new_heap_inner(
base,
bases,
attributes,
slots,
heaptype_ext,
metatype,
&vm.ctx,
)
.map_err(|e| vm.new_type_error(e))?;
if let Some(ref slots) = heaptype_slots {
let mut offset = base_member_count;
for member in slots.as_slice() {
let member_def = PyMemberDef {
name: member.to_string(),
kind: MemberKind::ObjectEx,
getter: MemberGetter::Offset(offset),
setter: MemberSetter::Offset(offset),
doc: None,
};
let member_descriptor: PyRef<PyMemberDescriptor> =
vm.ctx.new_pyref(PyMemberDescriptor {
common: PyDescriptorOwned {
typ: typ.clone(),
name: vm.ctx.intern_str(member.as_str()),
qualname: PyRwLock::new(None),
},
member: member_def,
});
let attr_name = vm.ctx.intern_str(member.to_string());
if !typ.has_attr(attr_name) {
typ.set_attr(attr_name, member_descriptor.into());
}
offset += 1;
}
}
if let Some(cell) = typ.attributes.write().get(identifier!(vm, __classcell__)) {
let cell = PyCellRef::try_from_object(vm, cell.clone()).map_err(|_| {
vm.new_type_error(format!(
"__classcell__ must be a nonlocal cell, not {}",
cell.class().name()
))
})?;
cell.set(Some(typ.clone().into()));
};
// avoid deadlock
let attributes = typ
.attributes
.read()
.iter()
.filter_map(|(name, obj)| {
vm.get_method(obj.clone(), identifier!(vm, __set_name__))
.map(|res| res.map(|meth| (obj.clone(), name.to_owned(), meth)))
})
.collect::<PyResult<Vec<_>>>()?;
for (obj, name, set_name) in attributes {
set_name.call((typ.clone(), name), vm).map_err(|e| {
let err = vm.new_runtime_error(format!(
"Error calling __set_name__ on '{}' instance {} in '{}'",
obj.class().name(),
name,
typ.name()
));
err.set_cause(Some(e));
err
})?;
}
if let Some(init_subclass) = typ.get_super_attr(identifier!(vm, __init_subclass__)) {
let init_subclass = vm
.call_get_descriptor_specific(&init_subclass, None, Some(typ.clone().into()))
.unwrap_or(Ok(init_subclass))?;
init_subclass.call(kwargs, vm)?;
};
Ok(typ.into())
}
#[pygetset(magic)]
fn dict(zelf: PyRef<Self>) -> PyMappingProxy {
PyMappingProxy::from(zelf)
}
#[pygetset(magic, setter)]
fn set_dict(&self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
Err(vm.new_not_implemented_error(
"Setting __dict__ attribute on a type isn't yet implemented".to_owned(),
))
}
fn check_set_special_type_attr(
&self,
_value: &PyObject,
name: &PyStrInterned,
vm: &VirtualMachine,
) -> PyResult<()> {
if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
return Err(vm.new_type_error(format!(
"cannot set '{}' attribute of immutable type '{}'",
name,
self.slot_name()
)));
}
Ok(())
}
#[pygetset(magic, setter)]
fn set_name(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.check_set_special_type_attr(&value, identifier!(vm, __name__), vm)?;
let name = value.downcast::<PyStr>().map_err(|value| {
vm.new_type_error(format!(
"can only assign string to {}.__name__, not '{}'",
self.slot_name(),
value.class().slot_name(),
))
})?;
if name.as_str().as_bytes().contains(&0) {
return Err(vm.new_value_error("type name must not contain null characters".to_owned()));
}
*self.heaptype_ext.as_ref().unwrap().name.write() = name;
Ok(())
}
#[pygetset(magic)]
fn text_signature(&self) -> Option<String> {
self.slots
.doc
.and_then(|doc| get_text_signature_from_internal_doc(&self.name(), doc))
.map(|signature| signature.to_string())
}
}
#[pyclass]
impl Py<PyType> {
#[pygetset(name = "__mro__")]
fn get_mro(&self) -> PyTuple {
let elements: Vec<PyObjectRef> =
self.iter_mro().map(|x| x.as_object().to_owned()).collect();
PyTuple::new_unchecked(elements.into_boxed_slice())
}
#[pymethod(magic)]
fn dir(&self) -> PyList {
let attributes: Vec<PyObjectRef> = self
.get_attributes()
.into_iter()
.map(|(k, _)| k.to_object())
.collect();
PyList::from(attributes)
}
#[pymethod(magic)]
fn instancecheck(&self, obj: PyObjectRef) -> bool {
obj.fast_isinstance(self)
}
#[pymethod(magic)]
fn subclasscheck(&self, subclass: PyTypeRef) -> bool {
subclass.fast_issubclass(self)
}
#[pyclassmethod(magic)]
fn subclasshook(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pymethod]
fn mro(&self) -> Vec<PyObjectRef> {
self.iter_mro().map(|cls| cls.to_owned().into()).collect()
}
}
const SIGNATURE_END_MARKER: &str = ")\n--\n\n";
fn get_signature(doc: &str) -> Option<&str> {
doc.find(SIGNATURE_END_MARKER).map(|index| &doc[..=index])
}
fn find_signature<'a>(name: &str, doc: &'a str) -> Option<&'a str> {
let name = name.rsplit('.').next().unwrap();
let doc = doc.strip_prefix(name)?;
doc.starts_with('(').then_some(doc)
}
pub(crate) fn get_text_signature_from_internal_doc<'a>(
name: &str,
internal_doc: &'a str,
) -> Option<&'a str> {
find_signature(name, internal_doc).and_then(get_signature)
}
impl GetAttr for PyType {
fn getattro(zelf: &Py<Self>, name_str: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
#[cold]
fn attribute_error(
zelf: &Py<PyType>,
name: &str,
vm: &VirtualMachine,
) -> PyBaseExceptionRef {
vm.new_attribute_error(format!(
"type object '{}' has no attribute '{}'",
zelf.slot_name(),
name,
))
}
let Some(name) = vm.ctx.interned_str(name_str) else {
return Err(attribute_error(zelf, name_str.as_str(), vm));
};
vm_trace!("type.__getattribute__({:?}, {:?})", zelf, name);
let mcl = zelf.class();
let mcl_attr = mcl.get_attr(name);
if let Some(ref attr) = mcl_attr {
let attr_class = attr.class();
let has_descr_set = attr_class
.mro_find_map(|cls| cls.slots.descr_set.load())
.is_some();
if has_descr_set {
let descr_get = attr_class.mro_find_map(|cls| cls.slots.descr_get.load());
if let Some(descr_get) = descr_get {
let mcl = mcl.to_owned().into();
return descr_get(attr.clone(), Some(zelf.to_owned().into()), Some(mcl), vm);
}
}
}
let zelf_attr = zelf.get_attr(name);
if let Some(attr) = zelf_attr {
let descr_get = attr.class().mro_find_map(|cls| cls.slots.descr_get.load());
if let Some(descr_get) = descr_get {
descr_get(attr, None, Some(zelf.to_owned().into()), vm)
} else {
Ok(attr)
}
} else if let Some(attr) = mcl_attr {
vm.call_if_get_descriptor(&attr, zelf.to_owned().into())
} else {
Err(attribute_error(zelf, name_str.as_str(), vm))
}
}
}
impl SetAttr for PyType {
fn setattro(
zelf: &Py<Self>,
attr_name: &Py<PyStr>,
value: PySetterValue,
vm: &VirtualMachine,
) -> PyResult<()> {
// TODO: pass PyRefExact instead of &str
let attr_name = vm.ctx.intern_str(attr_name.as_str());
if let Some(attr) = zelf.get_class_attr(attr_name) {
let descr_set = attr.class().mro_find_map(|cls| cls.slots.descr_set.load());
if let Some(descriptor) = descr_set {
return descriptor(&attr, zelf.to_owned().into(), value, vm);
}
}
let assign = value.is_assign();
if let PySetterValue::Assign(value) = value {
zelf.attributes.write().insert(attr_name, value);
} else {
let prev_value = zelf.attributes.write().remove(attr_name);
if prev_value.is_none() {
return Err(vm.new_exception(
vm.ctx.exceptions.attribute_error.to_owned(),
vec![attr_name.to_object()],
));
}
}
if attr_name.as_str().starts_with("__") && attr_name.as_str().ends_with("__") {
if assign {
zelf.update_slot::<true>(attr_name, &vm.ctx);
} else {
zelf.update_slot::<false>(attr_name, &vm.ctx);
}
}
Ok(())
}
}
impl Callable for PyType {
type Args = FuncArgs;
fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
vm_trace!("type_call: {:?}", zelf);
let obj = call_slot_new(zelf.to_owned(), zelf.to_owned(), args.clone(), vm)?;
if (zelf.is(vm.ctx.types.type_type) && args.kwargs.is_empty()) || !obj.fast_isinstance(zelf)
{
return Ok(obj);
}
let init = obj.class().mro_find_map(|cls| cls.slots.init.load());
if let Some(init_method) = init {
init_method(obj.clone(), args, vm)?;
}
Ok(obj)
}
}
impl AsNumber for PyType {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
or: Some(|a, b, vm| or_(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}
impl Representable for PyType {
#[inline]
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let module = zelf.module(vm);
let module = module.downcast_ref::<PyStr>().map(|m| m.as_str());
let repr = match module {
Some(module) if module != "builtins" => {
let name = zelf.name();
format!(
"<class '{}.{}'>",
module,
zelf.qualname(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str())
.unwrap_or_else(|| &name)
)
}
_ => format!("<class '{}'>", zelf.slot_name()),
};
Ok(repr)
}
}
fn find_base_dict_descr(cls: &Py<PyType>, vm: &VirtualMachine) -> Option<PyObjectRef> {
cls.iter_base_chain().skip(1).find_map(|cls| {
// TODO: should actually be some translation of:
// cls.slot_dictoffset != 0 && !cls.flags.contains(HEAPTYPE)
if cls.is(vm.ctx.types.type_type) {
cls.get_attr(identifier!(vm, __dict__))
} else {
None
}
})
}
fn subtype_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
// TODO: obj.class().as_pyref() need to be supported
let ret = match find_base_dict_descr(obj.class(), vm) {
Some(descr) => vm.call_get_descriptor(&descr, obj).unwrap_or_else(|| {
Err(vm.new_type_error(format!(
"this __dict__ descriptor does not support '{}' objects",
descr.class()
)))
})?,
None => object::object_get_dict(obj, vm)?.into(),
};
Ok(ret)
}
fn subtype_set_dict(obj: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let cls = obj.class();
match find_base_dict_descr(cls, vm) {
Some(descr) => {
let descr_set = descr
.class()
.mro_find_map(|cls| cls.slots.descr_set.load())
.ok_or_else(|| {
vm.new_type_error(format!(
"this __dict__ descriptor does not support '{}' objects",
cls.name()
))
})?;
descr_set(&descr, obj, PySetterValue::Assign(value), vm)
}
None => {
object::object_set_dict(obj, value.try_into_value(vm)?, vm)?;
Ok(())
}
}
}
/*
* The magical type type
*/
pub(crate) fn init(ctx: &Context) {
PyType::extend_class(ctx, ctx.types.type_type);
}
pub(crate) fn call_slot_new(
typ: PyTypeRef,
subtype: PyTypeRef,
args: FuncArgs,
vm: &VirtualMachine,
) -> PyResult {
for cls in typ.deref().iter_mro() {
if let Some(slot_new) = cls.slots.new.load() {
return slot_new(subtype, args, vm);
}
}
unreachable!("Should be able to find a new slot somewhere in the mro")
}
pub(super) fn or_(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if !union_::is_unionable(zelf.clone(), vm) || !union_::is_unionable(other.clone(), vm) {
return vm.ctx.not_implemented();
}
let tuple = PyTuple::new_ref(vec![zelf, other], &vm.ctx);
union_::make_union(&tuple, vm)
}
fn take_next_base(bases: &mut [Vec<PyTypeRef>]) -> Option<PyTypeRef> {
for base in bases.iter() {
let head = base[0].clone();
if !bases.iter().any(|x| x[1..].iter().any(|x| x.is(&head))) {
// Remove from other heads.
for item in bases.iter_mut() {
if item[0].is(&head) {
item.remove(0);
}
}
return Some(head);
}
}
None
}
fn linearise_mro(mut bases: Vec<Vec<PyTypeRef>>) -> Result<Vec<PyTypeRef>, String> {
vm_trace!("Linearise MRO: {:?}", bases);
// Python requires that the class direct bases are kept in the same order.
// This is called local precedence ordering.
// This means we must verify that for classes A(), B(A) we must reject C(A, B) even though this
// algorithm will allow the mro ordering of [C, B, A, object].
// To verify this, we make sure non of the direct bases are in the mro of bases after them.
for (i, base_mro) in bases.iter().enumerate() {
let base = &base_mro[0]; // MROs cannot be empty.
for later_mro in &bases[i + 1..] {
// We start at index 1 to skip direct bases.
// This will not catch duplicate bases, but such a thing is already tested for.
if later_mro[1..].iter().any(|cls| cls.is(base)) {
return Err(
"Unable to find mro order which keeps local precedence ordering".to_owned(),
);
}
}
}
let mut result = vec![];
while !bases.is_empty() {
let head = take_next_base(&mut bases).ok_or_else(|| {
// Take the head class of each class here. Now that we have reached the problematic bases.
// Because this failed, we assume the lists cannot be empty.
format!(
"Cannot create a consistent method resolution order (MRO) for bases {}",
bases.iter().map(|x| x.first().unwrap()).format(", ")
)
})?;
result.push(head);
bases.retain(|x| !x.is_empty());
}
Ok(result)
}
fn calculate_meta_class(
metatype: PyTypeRef,
bases: &[PyTypeRef],
vm: &VirtualMachine,
) -> PyResult<PyTypeRef> {
// = _PyType_CalculateMetaclass
let mut winner = metatype;
for base in bases {
let base_type = base.class();
if winner.fast_issubclass(base_type) {
continue;
} else if base_type.fast_issubclass(&winner) {
winner = base_type.to_owned();
continue;
}
return Err(vm.new_type_error(
"metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass \
of the metaclasses of all its bases"
.to_owned(),
));
}
Ok(winner)
}
fn best_base(bases: &[PyTypeRef], vm: &VirtualMachine) -> PyResult<PyTypeRef> {
// let mut base = None;
// let mut winner = None;
for base_i in bases {
// base_proto = PyTuple_GET_ITEM(bases, i);
// if (!PyType_Check(base_proto)) {
// PyErr_SetString(
// PyExc_TypeError,
// "bases must be types");
// return NULL;
// }
// base_i = (PyTypeObject *)base_proto;
// if (base_i->slot_dict == NULL) {
// if (PyType_Ready(base_i) < 0)
// return NULL;
// }
if !base_i.slots.flags.has_feature(PyTypeFlags::BASETYPE) {
return Err(vm.new_type_error(format!(
"type '{}' is not an acceptable base type",
base_i.name()
)));
}
// candidate = solid_base(base_i);
// if (winner == NULL) {
// winner = candidate;
// base = base_i;
// }
// else if (PyType_IsSubtype(winner, candidate))
// ;
// else if (PyType_IsSubtype(candidate, winner)) {
// winner = candidate;
// base = base_i;
// }
// else {
// PyErr_SetString(
// PyExc_TypeError,
// "multiple bases have "
// "instance lay-out conflict");
// return NULL;
// }
}
// FIXME: Ok(base.unwrap()) is expected
Ok(bases[0].clone())
}
#[cfg(test)]
mod tests {
use super::*;
fn map_ids(obj: Result<Vec<PyTypeRef>, String>) -> Result<Vec<usize>, String> {
Ok(obj?.into_iter().map(|x| x.get_id()).collect())
}
#[test]
fn test_linearise() {
let context = Context::genesis();
let object = context.types.object_type.to_owned();
let type_type = context.types.type_type.to_owned();
let a = PyType::new_heap(
"A",
vec![object.clone()],
PyAttributes::default(),
Default::default(),
type_type.clone(),
context,
)
.unwrap();
let b = PyType::new_heap(
"B",
vec![object.clone()],
PyAttributes::default(),
Default::default(),
type_type,
context,
)
.unwrap();
assert_eq!(
map_ids(linearise_mro(vec![
vec![object.clone()],
vec![object.clone()]
])),
map_ids(Ok(vec![object.clone()]))
);
assert_eq!(
map_ids(linearise_mro(vec![
vec![a.clone(), object.clone()],
vec![b.clone(), object.clone()],
])),
map_ids(Ok(vec![a, b, object]))
);
}
}
|
use crate::poseidon::PoseidonParams;
use crate::rescue::RescueParams;
use crate::sponge::GenericSponge;
use crate::traits::Sponge;
use franklin_crypto::bellman::pairing::bn256::{Bn256, Fr, FrRepr};
use franklin_crypto::bellman::{Field, PrimeField};
use franklin_crypto::rescue::{bn256::Bn256RescueParams, RescueHashParams, StatefulRescue};
use franklin_crypto::{
bellman::plonk::better_better_cs::cs::{TrivialAssembly, Width4MainGateWithDNext},
bellman::Engine,
plonk::circuit::Width4WithCustomGates,
};
use poseidon_hash::StatefulSponge as PoseidonSponge;
use poseidon_hash::{bn256::Bn256PoseidonParams, PoseidonHashParams};
use rand::{Rand, SeedableRng, XorShiftRng};
use std::convert::TryInto;
pub(crate) fn init_rng() -> XorShiftRng {
XorShiftRng::from_seed(crate::common::TEST_SEED)
}
pub(crate) fn init_cs<E: Engine>(
) -> TrivialAssembly<E, Width4WithCustomGates, Width4MainGateWithDNext> {
TrivialAssembly::<E, Width4WithCustomGates, Width4MainGateWithDNext>::new()
}
#[test]
fn test_rescue_bn256_fixed_length() {
const INPUT_LENGTH: usize = 2;
let rng = &mut init_rng();
let input = (0..INPUT_LENGTH).map(|_| Fr::rand(rng)).collect::<Vec<Fr>>();
let old_params = Bn256RescueParams::new_checked_2_into_1();
let expected = franklin_crypto::rescue::rescue_hash::<Bn256>(&old_params, &input);
let actual =
crate::rescue::rescue_hash::<Bn256, INPUT_LENGTH>(&input.try_into().expect("static vector"));
assert_eq!(expected[0], actual[0]);
}
#[test]
fn test_poseidon_bn256_fixed_length() {
const WIDTH: usize = 3;
const RATE: usize = 2;
let rng = &mut init_rng();
let input = (0..2).map(|_| Fr::rand(rng)).collect::<Vec<Fr>>();
let old_params = Bn256PoseidonParams::new_checked_2_into_1();
let expected = poseidon_hash::poseidon_hash::<Bn256>(&old_params, &input);
let actual =
crate::poseidon::generic_poseidon_hash_var_length::<Bn256, RATE, WIDTH>(&input);
assert_eq!(expected[0], actual[0]);
}
#[test]
fn test_rescue_params() {
const WIDTH: usize = 3;
const RATE: usize = 2;
let old_params = Bn256RescueParams::new_checked_2_into_1();
let (new_params, _, _) = crate::rescue::params::rescue_params::<Bn256, RATE, WIDTH>();
let number_of_rounds = new_params.full_rounds;
for round in 0..number_of_rounds {
assert_eq!(
old_params.round_constants(round as u32),
new_params.constants_of_round(round)
)
}
for row in 0..WIDTH {
assert_eq!(
old_params.mds_matrix_row(row as u32),
new_params.mds_matrix[row]
);
}
}
#[test]
fn test_poseidon_params() {
const WIDTH: usize = 3;
const RATE: usize = 2;
let old_params = Bn256PoseidonParams::new_checked_2_into_1();
let (new_params, _) = crate::poseidon::params::poseidon_params::<Bn256, RATE, WIDTH>();
let number_of_rounds = new_params.full_rounds;
for round in 0..number_of_rounds {
assert_eq!(
old_params.round_constants(round as u32),
new_params.constants_of_round(round)
)
}
for row in 0..WIDTH {
assert_eq!(
old_params.mds_matrix_row(row as u32),
new_params.mds_matrix[row]
);
}
}
#[test]
fn test_poseidon_comparisons_with_original_one() {
const WIDTH: usize = 3;
const RATE: usize = 2;
let mut el = Fr::one();
el.double();
let input = vec![el; 2];
let original_params = Bn256PoseidonParams::new_checked_2_into_1();
let mut original_poseidon = PoseidonSponge::<Bn256>::new(&original_params);
original_poseidon.absorb(&input);
let mut expected = [Fr::zero(); 2];
expected[0] = original_poseidon.squeeze_out_single();
expected[1] = original_poseidon.squeeze_out_single();
let new_params = PoseidonParams::<Bn256, RATE, WIDTH>::default();
let mut hasher = GenericSponge::from_params(&new_params);
hasher.absorb(&input);
let actual = hasher.squeeze(None);
assert_eq!(actual, expected);
}
#[test]
fn test_rescue_comparisons_with_original_one() {
const WIDTH: usize = 3;
const RATE: usize = 2;
let mut el = Fr::one();
el.double();
let input = vec![el; 2];
let original_params = Bn256RescueParams::new_checked_2_into_1();
let mut original_rescue = StatefulRescue::<Bn256>::new(&original_params);
original_rescue.absorb(&input);
let mut expected = [Fr::zero(); 2];
expected[0] = original_rescue.squeeze_out_single();
expected[1] = original_rescue.squeeze_out_single();
let new_params = RescueParams::<Bn256, RATE, WIDTH>::default();
let mut hasher = GenericSponge::from_params(&new_params);
hasher.absorb(&input);
let actual = hasher.squeeze(None);
assert_eq!(actual, expected);
}
#[test]
#[should_panic]
fn test_sponge_phase_absorb() {
const WIDTH: usize = 3;
const RATE: usize = 2;
let params = RescueParams::default();
let mut sponge = GenericSponge::<Bn256, _, RATE, WIDTH>::from_params(¶ms);
sponge.absorb(&[Fr::one(); 2]);
sponge.absorb(&[Fr::one(); 2]);
}
#[test]
#[should_panic]
fn test_sponge_phase_squeeze() {
const WIDTH: usize = 3;
const RATE: usize = 2;
let params = RescueParams::default();
let mut sponge = GenericSponge::<Bn256, _, RATE, WIDTH>::from_params(¶ms);
sponge.squeeze(None);
}
#[test]
fn test_generic_rescue_bn256_fixed_length() {
use crate::rescue::RescueParams;
use crate::sponge::GenericSponge;
use crate::traits::Sponge;
const WIDTH: usize = 3;
const RATE: usize = 2;
let rng = &mut init_rng();
let input = (0..2).map(|_| Fr::rand(rng)).collect::<Vec<Fr>>();
let old_params = Bn256RescueParams::new_checked_2_into_1();
let expected = franklin_crypto::rescue::rescue_hash::<Bn256>(&old_params, &input);
let new_params = RescueParams::<Bn256, RATE, WIDTH>::default();
let mut rescue_hasher = GenericSponge::from_params(&new_params);
rescue_hasher.specialize(Some(Fr::from_repr(FrRepr::from(2u64)).expect("")));
rescue_hasher.absorb(&input);
let actual = rescue_hasher.squeeze(None);
assert_eq!(expected[0], actual[0]);
}
#[test]
#[should_panic]
fn test_generic_rescue_bn256_var_length() {
use crate::rescue::RescueParams;
use crate::sponge::GenericSponge;
use crate::traits::Sponge;
const WIDTH: usize = 3;
const RATE: usize = 2;
let rng = &mut init_rng();
// input is not multiple of RATE so it should panic
let input = (0..RATE + 1).map(|_| Fr::rand(rng)).collect::<Vec<Fr>>();
let old_params = Bn256RescueParams::new_checked_2_into_1();
let expected = franklin_crypto::rescue::rescue_hash::<Bn256>(&old_params, &input);
let new_params = RescueParams::<Bn256, RATE, WIDTH>::default();
let mut rescue_hasher = GenericSponge::from_params(&new_params);
rescue_hasher.specialize(Some(Fr::from_repr(FrRepr::from(2u64)).expect("")));
rescue_hasher.absorb(&input);
let actual = rescue_hasher.squeeze(None);
assert_eq!(expected[0], actual[0]);
}
|
//! This module implements formatting functions for writing into lock files.
use crate::sys;
use core::{
fmt::{self, Write},
mem,
};
/// I/O buffer size, chosen targeting possible PID's digits (I belive 11 would
/// be enough tho).
const BUF_SIZE: usize = 16;
/// A fmt Writer that writes data into the given open file.
#[derive(Debug, Clone, Copy)]
pub struct Writer(
/// The open file to which data will be written.
pub sys::FileDesc,
);
impl Writer {
/// Writes formatting arguments into the file.
pub fn write_fmt(
&self,
arguments: fmt::Arguments,
) -> Result<(), sys::Error> {
let mut adapter = Adapter::new(self.0);
let _ = adapter.write_fmt(arguments);
adapter.finish()
}
}
/// Fmt <-> IO adapter.
///
/// Buffer is flushed on drop.
#[derive(Debug)]
struct Adapter {
/// File being written to.
desc: sys::FileDesc,
/// Temporary buffer of bytes being written.
buffer: [u8; BUF_SIZE],
/// Cursor tracking where new bytes should be written at the buffer.
cursor: usize,
/// Partial result for writes.
result: Result<(), sys::Error>,
}
impl Adapter {
/// Creates a zeroed adapter from an open file.
fn new(desc: sys::FileDesc) -> Self {
Self { desc, buffer: [0; BUF_SIZE], cursor: 0, result: Ok(()) }
}
/// Flushes the buffer into the open file.
fn flush(&mut self) -> Result<(), sys::Error> {
sys::write(self.desc, &self.buffer[.. self.cursor])?;
self.buffer = [0; BUF_SIZE];
self.cursor = 0;
Ok(())
}
/// Finishes the adapter, returning the I/O Result
fn finish(mut self) -> Result<(), sys::Error> {
mem::replace(&mut self.result, Ok(()))
}
}
impl Write for Adapter {
fn write_str(&mut self, data: &str) -> fmt::Result {
let mut bytes = data.as_bytes();
while bytes.len() > 0 && self.result.is_ok() {
let start = self.cursor;
let size = (BUF_SIZE - self.cursor).min(bytes.len());
let end = start + size;
self.buffer[start .. end].copy_from_slice(&bytes[.. size]);
self.cursor = end;
bytes = &bytes[size ..];
if bytes.len() > 0 {
self.result = self.flush();
}
}
match self.result {
Ok(_) => Ok(()),
Err(_) => Err(fmt::Error),
}
}
}
impl Drop for Adapter {
fn drop(&mut self) {
let _ = self.flush();
let _ = sys::fsync(self.desc);
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtGui/qopengltimerquery.h
// dst-file: /src/gui/qopengltimerquery.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::core::qobject::*; // 771
use std::ops::Deref;
use super::super::core::qobjectdefs::*; // 771
// use super::qvector::*; // 775
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QOpenGLTimerQuery_Class_Size() -> c_int;
// proto: bool QOpenGLTimerQuery::create();
fn C_ZN17QOpenGLTimerQuery6createEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QOpenGLTimerQuery::isCreated();
fn C_ZNK17QOpenGLTimerQuery9isCreatedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QOpenGLTimerQuery::end();
fn C_ZN17QOpenGLTimerQuery3endEv(qthis: u64 /* *mut c_void*/);
// proto: void QOpenGLTimerQuery::~QOpenGLTimerQuery();
fn C_ZN17QOpenGLTimerQueryD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QOpenGLTimerQuery::begin();
fn C_ZN17QOpenGLTimerQuery5beginEv(qthis: u64 /* *mut c_void*/);
// proto: void QOpenGLTimerQuery::QOpenGLTimerQuery(QObject * parent);
fn C_ZN17QOpenGLTimerQueryC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: void QOpenGLTimerQuery::destroy();
fn C_ZN17QOpenGLTimerQuery7destroyEv(qthis: u64 /* *mut c_void*/);
// proto: GLuint64 QOpenGLTimerQuery::waitForResult();
fn C_ZNK17QOpenGLTimerQuery13waitForResultEv(qthis: u64 /* *mut c_void*/) -> c_ulong;
// proto: GLuint QOpenGLTimerQuery::objectId();
fn C_ZNK17QOpenGLTimerQuery8objectIdEv(qthis: u64 /* *mut c_void*/) -> c_uint;
// proto: GLuint64 QOpenGLTimerQuery::waitForTimestamp();
fn C_ZNK17QOpenGLTimerQuery16waitForTimestampEv(qthis: u64 /* *mut c_void*/) -> c_ulong;
// proto: const QMetaObject * QOpenGLTimerQuery::metaObject();
fn C_ZNK17QOpenGLTimerQuery10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QOpenGLTimerQuery::recordTimestamp();
fn C_ZN17QOpenGLTimerQuery15recordTimestampEv(qthis: u64 /* *mut c_void*/);
// proto: bool QOpenGLTimerQuery::isResultAvailable();
fn C_ZNK17QOpenGLTimerQuery17isResultAvailableEv(qthis: u64 /* *mut c_void*/) -> c_char;
fn QOpenGLTimeMonitor_Class_Size() -> c_int;
// proto: void QOpenGLTimeMonitor::setSampleCount(int sampleCount);
fn C_ZN18QOpenGLTimeMonitor14setSampleCountEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QOpenGLTimeMonitor::sampleCount();
fn C_ZNK18QOpenGLTimeMonitor11sampleCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QOpenGLTimeMonitor::destroy();
fn C_ZN18QOpenGLTimeMonitor7destroyEv(qthis: u64 /* *mut c_void*/);
// proto: bool QOpenGLTimeMonitor::create();
fn C_ZN18QOpenGLTimeMonitor6createEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QOpenGLTimeMonitor::~QOpenGLTimeMonitor();
fn C_ZN18QOpenGLTimeMonitorD2Ev(qthis: u64 /* *mut c_void*/);
// proto: bool QOpenGLTimeMonitor::isResultAvailable();
fn C_ZNK18QOpenGLTimeMonitor17isResultAvailableEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QVector<GLuint64> QOpenGLTimeMonitor::waitForIntervals();
fn C_ZNK18QOpenGLTimeMonitor16waitForIntervalsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QVector<GLuint> QOpenGLTimeMonitor::objectIds();
fn C_ZNK18QOpenGLTimeMonitor9objectIdsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QOpenGLTimeMonitor::recordSample();
fn C_ZN18QOpenGLTimeMonitor12recordSampleEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QOpenGLTimeMonitor::reset();
fn C_ZN18QOpenGLTimeMonitor5resetEv(qthis: u64 /* *mut c_void*/);
// proto: void QOpenGLTimeMonitor::QOpenGLTimeMonitor(QObject * parent);
fn C_ZN18QOpenGLTimeMonitorC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: QVector<GLuint64> QOpenGLTimeMonitor::waitForSamples();
fn C_ZNK18QOpenGLTimeMonitor14waitForSamplesEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QOpenGLTimeMonitor::isCreated();
fn C_ZNK18QOpenGLTimeMonitor9isCreatedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: const QMetaObject * QOpenGLTimeMonitor::metaObject();
fn C_ZNK18QOpenGLTimeMonitor10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
} // <= ext block end
// body block begin =>
// class sizeof(QOpenGLTimerQuery)=1
#[derive(Default)]
pub struct QOpenGLTimerQuery {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
// class sizeof(QOpenGLTimeMonitor)=1
#[derive(Default)]
pub struct QOpenGLTimeMonitor {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QOpenGLTimerQuery {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QOpenGLTimerQuery {
return QOpenGLTimerQuery{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QOpenGLTimerQuery {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QOpenGLTimerQuery {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: bool QOpenGLTimerQuery::create();
impl /*struct*/ QOpenGLTimerQuery {
pub fn create<RetType, T: QOpenGLTimerQuery_create<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.create(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_create<RetType> {
fn create(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: bool QOpenGLTimerQuery::create();
impl<'a> /*trait*/ QOpenGLTimerQuery_create<i8> for () {
fn create(self , rsthis: & QOpenGLTimerQuery) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QOpenGLTimerQuery6createEv()};
let mut ret = unsafe {C_ZN17QOpenGLTimerQuery6createEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QOpenGLTimerQuery::isCreated();
impl /*struct*/ QOpenGLTimerQuery {
pub fn isCreated<RetType, T: QOpenGLTimerQuery_isCreated<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isCreated(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_isCreated<RetType> {
fn isCreated(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: bool QOpenGLTimerQuery::isCreated();
impl<'a> /*trait*/ QOpenGLTimerQuery_isCreated<i8> for () {
fn isCreated(self , rsthis: & QOpenGLTimerQuery) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QOpenGLTimerQuery9isCreatedEv()};
let mut ret = unsafe {C_ZNK17QOpenGLTimerQuery9isCreatedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QOpenGLTimerQuery::end();
impl /*struct*/ QOpenGLTimerQuery {
pub fn end<RetType, T: QOpenGLTimerQuery_end<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.end(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_end<RetType> {
fn end(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: void QOpenGLTimerQuery::end();
impl<'a> /*trait*/ QOpenGLTimerQuery_end<()> for () {
fn end(self , rsthis: & QOpenGLTimerQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QOpenGLTimerQuery3endEv()};
unsafe {C_ZN17QOpenGLTimerQuery3endEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QOpenGLTimerQuery::~QOpenGLTimerQuery();
impl /*struct*/ QOpenGLTimerQuery {
pub fn free<RetType, T: QOpenGLTimerQuery_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_free<RetType> {
fn free(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: void QOpenGLTimerQuery::~QOpenGLTimerQuery();
impl<'a> /*trait*/ QOpenGLTimerQuery_free<()> for () {
fn free(self , rsthis: & QOpenGLTimerQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QOpenGLTimerQueryD2Ev()};
unsafe {C_ZN17QOpenGLTimerQueryD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QOpenGLTimerQuery::begin();
impl /*struct*/ QOpenGLTimerQuery {
pub fn begin<RetType, T: QOpenGLTimerQuery_begin<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.begin(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_begin<RetType> {
fn begin(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: void QOpenGLTimerQuery::begin();
impl<'a> /*trait*/ QOpenGLTimerQuery_begin<()> for () {
fn begin(self , rsthis: & QOpenGLTimerQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QOpenGLTimerQuery5beginEv()};
unsafe {C_ZN17QOpenGLTimerQuery5beginEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QOpenGLTimerQuery::QOpenGLTimerQuery(QObject * parent);
impl /*struct*/ QOpenGLTimerQuery {
pub fn new<T: QOpenGLTimerQuery_new>(value: T) -> QOpenGLTimerQuery {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QOpenGLTimerQuery_new {
fn new(self) -> QOpenGLTimerQuery;
}
// proto: void QOpenGLTimerQuery::QOpenGLTimerQuery(QObject * parent);
impl<'a> /*trait*/ QOpenGLTimerQuery_new for (Option<&'a QObject>) {
fn new(self) -> QOpenGLTimerQuery {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QOpenGLTimerQueryC2EP7QObject()};
let ctysz: c_int = unsafe{QOpenGLTimerQuery_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN17QOpenGLTimerQueryC2EP7QObject(arg0)};
let rsthis = QOpenGLTimerQuery{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QOpenGLTimerQuery::destroy();
impl /*struct*/ QOpenGLTimerQuery {
pub fn destroy<RetType, T: QOpenGLTimerQuery_destroy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.destroy(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_destroy<RetType> {
fn destroy(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: void QOpenGLTimerQuery::destroy();
impl<'a> /*trait*/ QOpenGLTimerQuery_destroy<()> for () {
fn destroy(self , rsthis: & QOpenGLTimerQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QOpenGLTimerQuery7destroyEv()};
unsafe {C_ZN17QOpenGLTimerQuery7destroyEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: GLuint64 QOpenGLTimerQuery::waitForResult();
impl /*struct*/ QOpenGLTimerQuery {
pub fn waitForResult<RetType, T: QOpenGLTimerQuery_waitForResult<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.waitForResult(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_waitForResult<RetType> {
fn waitForResult(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: GLuint64 QOpenGLTimerQuery::waitForResult();
impl<'a> /*trait*/ QOpenGLTimerQuery_waitForResult<u64> for () {
fn waitForResult(self , rsthis: & QOpenGLTimerQuery) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QOpenGLTimerQuery13waitForResultEv()};
let mut ret = unsafe {C_ZNK17QOpenGLTimerQuery13waitForResultEv(rsthis.qclsinst)};
return ret as u64; // 1
// return 1;
}
}
// proto: GLuint QOpenGLTimerQuery::objectId();
impl /*struct*/ QOpenGLTimerQuery {
pub fn objectId<RetType, T: QOpenGLTimerQuery_objectId<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.objectId(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_objectId<RetType> {
fn objectId(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: GLuint QOpenGLTimerQuery::objectId();
impl<'a> /*trait*/ QOpenGLTimerQuery_objectId<u32> for () {
fn objectId(self , rsthis: & QOpenGLTimerQuery) -> u32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QOpenGLTimerQuery8objectIdEv()};
let mut ret = unsafe {C_ZNK17QOpenGLTimerQuery8objectIdEv(rsthis.qclsinst)};
return ret as u32; // 1
// return 1;
}
}
// proto: GLuint64 QOpenGLTimerQuery::waitForTimestamp();
impl /*struct*/ QOpenGLTimerQuery {
pub fn waitForTimestamp<RetType, T: QOpenGLTimerQuery_waitForTimestamp<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.waitForTimestamp(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_waitForTimestamp<RetType> {
fn waitForTimestamp(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: GLuint64 QOpenGLTimerQuery::waitForTimestamp();
impl<'a> /*trait*/ QOpenGLTimerQuery_waitForTimestamp<u64> for () {
fn waitForTimestamp(self , rsthis: & QOpenGLTimerQuery) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QOpenGLTimerQuery16waitForTimestampEv()};
let mut ret = unsafe {C_ZNK17QOpenGLTimerQuery16waitForTimestampEv(rsthis.qclsinst)};
return ret as u64; // 1
// return 1;
}
}
// proto: const QMetaObject * QOpenGLTimerQuery::metaObject();
impl /*struct*/ QOpenGLTimerQuery {
pub fn metaObject<RetType, T: QOpenGLTimerQuery_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_metaObject<RetType> {
fn metaObject(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: const QMetaObject * QOpenGLTimerQuery::metaObject();
impl<'a> /*trait*/ QOpenGLTimerQuery_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QOpenGLTimerQuery) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QOpenGLTimerQuery10metaObjectEv()};
let mut ret = unsafe {C_ZNK17QOpenGLTimerQuery10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QOpenGLTimerQuery::recordTimestamp();
impl /*struct*/ QOpenGLTimerQuery {
pub fn recordTimestamp<RetType, T: QOpenGLTimerQuery_recordTimestamp<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.recordTimestamp(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_recordTimestamp<RetType> {
fn recordTimestamp(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: void QOpenGLTimerQuery::recordTimestamp();
impl<'a> /*trait*/ QOpenGLTimerQuery_recordTimestamp<()> for () {
fn recordTimestamp(self , rsthis: & QOpenGLTimerQuery) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN17QOpenGLTimerQuery15recordTimestampEv()};
unsafe {C_ZN17QOpenGLTimerQuery15recordTimestampEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QOpenGLTimerQuery::isResultAvailable();
impl /*struct*/ QOpenGLTimerQuery {
pub fn isResultAvailable<RetType, T: QOpenGLTimerQuery_isResultAvailable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isResultAvailable(self);
// return 1;
}
}
pub trait QOpenGLTimerQuery_isResultAvailable<RetType> {
fn isResultAvailable(self , rsthis: & QOpenGLTimerQuery) -> RetType;
}
// proto: bool QOpenGLTimerQuery::isResultAvailable();
impl<'a> /*trait*/ QOpenGLTimerQuery_isResultAvailable<i8> for () {
fn isResultAvailable(self , rsthis: & QOpenGLTimerQuery) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK17QOpenGLTimerQuery17isResultAvailableEv()};
let mut ret = unsafe {C_ZNK17QOpenGLTimerQuery17isResultAvailableEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
impl /*struct*/ QOpenGLTimeMonitor {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QOpenGLTimeMonitor {
return QOpenGLTimeMonitor{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QOpenGLTimeMonitor {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QOpenGLTimeMonitor {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QOpenGLTimeMonitor::setSampleCount(int sampleCount);
impl /*struct*/ QOpenGLTimeMonitor {
pub fn setSampleCount<RetType, T: QOpenGLTimeMonitor_setSampleCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSampleCount(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_setSampleCount<RetType> {
fn setSampleCount(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: void QOpenGLTimeMonitor::setSampleCount(int sampleCount);
impl<'a> /*trait*/ QOpenGLTimeMonitor_setSampleCount<()> for (i32) {
fn setSampleCount(self , rsthis: & QOpenGLTimeMonitor) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QOpenGLTimeMonitor14setSampleCountEi()};
let arg0 = self as c_int;
unsafe {C_ZN18QOpenGLTimeMonitor14setSampleCountEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QOpenGLTimeMonitor::sampleCount();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn sampleCount<RetType, T: QOpenGLTimeMonitor_sampleCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sampleCount(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_sampleCount<RetType> {
fn sampleCount(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: int QOpenGLTimeMonitor::sampleCount();
impl<'a> /*trait*/ QOpenGLTimeMonitor_sampleCount<i32> for () {
fn sampleCount(self , rsthis: & QOpenGLTimeMonitor) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QOpenGLTimeMonitor11sampleCountEv()};
let mut ret = unsafe {C_ZNK18QOpenGLTimeMonitor11sampleCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QOpenGLTimeMonitor::destroy();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn destroy<RetType, T: QOpenGLTimeMonitor_destroy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.destroy(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_destroy<RetType> {
fn destroy(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: void QOpenGLTimeMonitor::destroy();
impl<'a> /*trait*/ QOpenGLTimeMonitor_destroy<()> for () {
fn destroy(self , rsthis: & QOpenGLTimeMonitor) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QOpenGLTimeMonitor7destroyEv()};
unsafe {C_ZN18QOpenGLTimeMonitor7destroyEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QOpenGLTimeMonitor::create();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn create<RetType, T: QOpenGLTimeMonitor_create<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.create(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_create<RetType> {
fn create(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: bool QOpenGLTimeMonitor::create();
impl<'a> /*trait*/ QOpenGLTimeMonitor_create<i8> for () {
fn create(self , rsthis: & QOpenGLTimeMonitor) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QOpenGLTimeMonitor6createEv()};
let mut ret = unsafe {C_ZN18QOpenGLTimeMonitor6createEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QOpenGLTimeMonitor::~QOpenGLTimeMonitor();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn free<RetType, T: QOpenGLTimeMonitor_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_free<RetType> {
fn free(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: void QOpenGLTimeMonitor::~QOpenGLTimeMonitor();
impl<'a> /*trait*/ QOpenGLTimeMonitor_free<()> for () {
fn free(self , rsthis: & QOpenGLTimeMonitor) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QOpenGLTimeMonitorD2Ev()};
unsafe {C_ZN18QOpenGLTimeMonitorD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QOpenGLTimeMonitor::isResultAvailable();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn isResultAvailable<RetType, T: QOpenGLTimeMonitor_isResultAvailable<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isResultAvailable(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_isResultAvailable<RetType> {
fn isResultAvailable(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: bool QOpenGLTimeMonitor::isResultAvailable();
impl<'a> /*trait*/ QOpenGLTimeMonitor_isResultAvailable<i8> for () {
fn isResultAvailable(self , rsthis: & QOpenGLTimeMonitor) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QOpenGLTimeMonitor17isResultAvailableEv()};
let mut ret = unsafe {C_ZNK18QOpenGLTimeMonitor17isResultAvailableEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QVector<GLuint64> QOpenGLTimeMonitor::waitForIntervals();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn waitForIntervals<RetType, T: QOpenGLTimeMonitor_waitForIntervals<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.waitForIntervals(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_waitForIntervals<RetType> {
fn waitForIntervals(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: QVector<GLuint64> QOpenGLTimeMonitor::waitForIntervals();
impl<'a> /*trait*/ QOpenGLTimeMonitor_waitForIntervals<u64> for () {
fn waitForIntervals(self , rsthis: & QOpenGLTimeMonitor) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QOpenGLTimeMonitor16waitForIntervalsEv()};
let mut ret = unsafe {C_ZNK18QOpenGLTimeMonitor16waitForIntervalsEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: QVector<GLuint> QOpenGLTimeMonitor::objectIds();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn objectIds<RetType, T: QOpenGLTimeMonitor_objectIds<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.objectIds(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_objectIds<RetType> {
fn objectIds(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: QVector<GLuint> QOpenGLTimeMonitor::objectIds();
impl<'a> /*trait*/ QOpenGLTimeMonitor_objectIds<u64> for () {
fn objectIds(self , rsthis: & QOpenGLTimeMonitor) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QOpenGLTimeMonitor9objectIdsEv()};
let mut ret = unsafe {C_ZNK18QOpenGLTimeMonitor9objectIdsEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: int QOpenGLTimeMonitor::recordSample();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn recordSample<RetType, T: QOpenGLTimeMonitor_recordSample<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.recordSample(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_recordSample<RetType> {
fn recordSample(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: int QOpenGLTimeMonitor::recordSample();
impl<'a> /*trait*/ QOpenGLTimeMonitor_recordSample<i32> for () {
fn recordSample(self , rsthis: & QOpenGLTimeMonitor) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QOpenGLTimeMonitor12recordSampleEv()};
let mut ret = unsafe {C_ZN18QOpenGLTimeMonitor12recordSampleEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QOpenGLTimeMonitor::reset();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn reset<RetType, T: QOpenGLTimeMonitor_reset<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.reset(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_reset<RetType> {
fn reset(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: void QOpenGLTimeMonitor::reset();
impl<'a> /*trait*/ QOpenGLTimeMonitor_reset<()> for () {
fn reset(self , rsthis: & QOpenGLTimeMonitor) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QOpenGLTimeMonitor5resetEv()};
unsafe {C_ZN18QOpenGLTimeMonitor5resetEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QOpenGLTimeMonitor::QOpenGLTimeMonitor(QObject * parent);
impl /*struct*/ QOpenGLTimeMonitor {
pub fn new<T: QOpenGLTimeMonitor_new>(value: T) -> QOpenGLTimeMonitor {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QOpenGLTimeMonitor_new {
fn new(self) -> QOpenGLTimeMonitor;
}
// proto: void QOpenGLTimeMonitor::QOpenGLTimeMonitor(QObject * parent);
impl<'a> /*trait*/ QOpenGLTimeMonitor_new for (Option<&'a QObject>) {
fn new(self) -> QOpenGLTimeMonitor {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN18QOpenGLTimeMonitorC2EP7QObject()};
let ctysz: c_int = unsafe{QOpenGLTimeMonitor_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN18QOpenGLTimeMonitorC2EP7QObject(arg0)};
let rsthis = QOpenGLTimeMonitor{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QVector<GLuint64> QOpenGLTimeMonitor::waitForSamples();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn waitForSamples<RetType, T: QOpenGLTimeMonitor_waitForSamples<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.waitForSamples(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_waitForSamples<RetType> {
fn waitForSamples(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: QVector<GLuint64> QOpenGLTimeMonitor::waitForSamples();
impl<'a> /*trait*/ QOpenGLTimeMonitor_waitForSamples<u64> for () {
fn waitForSamples(self , rsthis: & QOpenGLTimeMonitor) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QOpenGLTimeMonitor14waitForSamplesEv()};
let mut ret = unsafe {C_ZNK18QOpenGLTimeMonitor14waitForSamplesEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: bool QOpenGLTimeMonitor::isCreated();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn isCreated<RetType, T: QOpenGLTimeMonitor_isCreated<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isCreated(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_isCreated<RetType> {
fn isCreated(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: bool QOpenGLTimeMonitor::isCreated();
impl<'a> /*trait*/ QOpenGLTimeMonitor_isCreated<i8> for () {
fn isCreated(self , rsthis: & QOpenGLTimeMonitor) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QOpenGLTimeMonitor9isCreatedEv()};
let mut ret = unsafe {C_ZNK18QOpenGLTimeMonitor9isCreatedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: const QMetaObject * QOpenGLTimeMonitor::metaObject();
impl /*struct*/ QOpenGLTimeMonitor {
pub fn metaObject<RetType, T: QOpenGLTimeMonitor_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QOpenGLTimeMonitor_metaObject<RetType> {
fn metaObject(self , rsthis: & QOpenGLTimeMonitor) -> RetType;
}
// proto: const QMetaObject * QOpenGLTimeMonitor::metaObject();
impl<'a> /*trait*/ QOpenGLTimeMonitor_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QOpenGLTimeMonitor) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK18QOpenGLTimeMonitor10metaObjectEv()};
let mut ret = unsafe {C_ZNK18QOpenGLTimeMonitor10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// <= body block end
|
#![cfg(feature = "rusoto_core")]
use crate::{dns::Resolver, sinks::util, tls::MaybeTlsSettings};
use async_trait::async_trait;
use bytes05::Bytes;
use futures::{Stream, StreamExt};
use http::{
header::{HeaderMap, HeaderName, HeaderValue},
Method, Request, Response, StatusCode,
};
use hyper::body::{Body, HttpBody};
use rusoto_core::{
request::{
DispatchSignedRequest, DispatchSignedRequestFuture, HttpDispatchError, HttpResponse,
},
ByteStream, Region,
};
use rusoto_credential::{
AutoRefreshingProvider, AwsCredentials, ChainProvider, CredentialsError, ProvideAwsCredentials,
StaticProvider,
};
use rusoto_signature::{SignedRequest, SignedRequestPayload};
use rusoto_sts::{StsAssumeRoleSessionCredentialsProvider, StsClient};
use snafu::{ResultExt, Snafu};
use std::{
fmt, io,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use tower03::{Service, ServiceExt};
pub type Client = HttpClient<util::http::HttpClient<RusotoBody>>;
pub fn client(resolver: Resolver) -> crate::Result<Client> {
let settings = MaybeTlsSettings::enable_client()?;
let client = util::http::HttpClient::new(resolver, settings)?;
Ok(HttpClient { client })
}
#[derive(Debug, Snafu)]
enum RusotoError {
#[snafu(display("Invalid AWS credentials: {}", source))]
InvalidAWSCredentials { source: CredentialsError },
}
// A place-holder for the types of AWS credentials we support
pub enum AwsCredentialsProvider {
Default(AutoRefreshingProvider<ChainProvider>),
Role(AutoRefreshingProvider<StsAssumeRoleSessionCredentialsProvider>),
Static(StaticProvider),
}
impl fmt::Debug for AwsCredentialsProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Default(_) => "default",
Self::Role(_) => "role",
Self::Static(_) => "static",
};
f.debug_tuple("AwsCredentialsProvider")
.field(&name)
.finish()
}
}
impl AwsCredentialsProvider {
pub fn new(region: &Region, assume_role: Option<String>) -> crate::Result<Self> {
if let Some(role) = assume_role {
debug!("using sts assume role credentials for AWS.");
let sts = StsClient::new(region.clone());
let provider = StsAssumeRoleSessionCredentialsProvider::new(
sts,
role,
"default".to_owned(),
None,
None,
None,
None,
);
let creds = AutoRefreshingProvider::new(provider).context(InvalidAWSCredentials)?;
Ok(Self::Role(creds))
} else {
debug!("using default credentials provider for AWS.");
let mut chain = ChainProvider::new();
// 8 seconds because our default healthcheck timeout
// is 10 seconds.
chain.set_timeout(Duration::from_secs(8));
let creds = AutoRefreshingProvider::new(chain).context(InvalidAWSCredentials)?;
Ok(Self::Default(creds))
}
}
pub fn new_minimal<A: Into<String>, S: Into<String>>(access_key: A, secret_key: S) -> Self {
Self::Static(StaticProvider::new_minimal(
access_key.into(),
secret_key.into(),
))
}
}
#[async_trait]
impl ProvideAwsCredentials for AwsCredentialsProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
let fut = match self {
Self::Default(p) => p.credentials(),
Self::Role(p) => p.credentials(),
Self::Static(p) => p.credentials(),
};
fut.await
}
}
#[derive(Debug, Clone)]
pub struct HttpClient<T> {
client: T,
}
#[derive(Debug)]
pub struct RusotoBody {
inner: Option<SignedRequestPayload>,
}
impl<T> HttpClient<T> {
pub fn new(client: T) -> Self {
HttpClient { client }
}
}
impl<T> DispatchSignedRequest for HttpClient<T>
where
T: Service<Request<RusotoBody>, Response = Response<Body>, Error = hyper::Error>
+ Clone
+ Send
+ 'static,
T::Future: Send + 'static,
{
// Adaptation of https://docs.rs/rusoto_core/0.44.0/src/rusoto_core/request.rs.html#314-416
fn dispatch(
&self,
request: SignedRequest,
timeout: Option<Duration>,
) -> DispatchSignedRequestFuture {
assert!(timeout.is_none(), "timeout is not supported at this level");
let client = self.client.clone();
Box::pin(async move {
let method = match request.method().as_ref() {
"POST" => Method::POST,
"PUT" => Method::PUT,
"DELETE" => Method::DELETE,
"GET" => Method::GET,
"HEAD" => Method::HEAD,
v => {
return Err(HttpDispatchError::new(format!(
"Unsupported HTTP verb {}",
v
)));
}
};
let mut headers = HeaderMap::new();
for h in request.headers().iter() {
let header_name = match h.0.parse::<HeaderName>() {
Ok(name) => name,
Err(err) => {
return Err(HttpDispatchError::new(format!(
"error parsing header name: {}",
err
)))
}
};
for v in h.1.iter() {
let header_value = match HeaderValue::from_bytes(v) {
Ok(value) => value,
Err(err) => {
return Err(HttpDispatchError::new(format!(
"error parsing header value: {}",
err
)))
}
};
headers.append(&header_name, header_value);
}
}
let mut uri = format!(
"{}://{}{}",
request.scheme(),
request.hostname(),
request.canonical_path()
);
if !request.canonical_query_string().is_empty() {
uri += &format!("?{}", request.canonical_query_string());
}
let mut request = Request::builder()
.method(method)
.uri(uri)
.body(RusotoBody::from(request.payload))
.map_err(|e| format!("error building request: {}", e))
.map_err(HttpDispatchError::new)?;
*request.headers_mut() = headers;
let response = client
.oneshot(request)
.await
.map_err(|e| HttpDispatchError::new(format!("Error during dispatch: {}", e)))?;
let status = StatusCode::from_u16(response.status().as_u16()).unwrap();
let headers = response
.headers()
.iter()
.map(|(h, v)| {
let value_string = v.to_str().unwrap().to_owned();
// This should always be valid since we are coming from http.
let name = HeaderName::from_bytes(h.as_ref())
.expect("Should always be a valid header");
(name, value_string)
})
.collect();
let body = response.into_body().map(|try_chunk| {
try_chunk
.map(|c| c)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
});
Ok(HttpResponse {
status,
headers,
body: ByteStream::new(body),
})
})
}
}
impl HttpBody for RusotoBody {
type Data = Bytes;
type Error = io::Error;
fn poll_data(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
match self.inner.as_mut() {
Some(SignedRequestPayload::Buffer(buf)) => {
if !buf.is_empty() {
let buf = buf.split_off(0);
Poll::Ready(Some(Ok(buf)))
} else {
Poll::Ready(None)
}
}
Some(SignedRequestPayload::Stream(stream)) => {
let stream = Pin::new(stream);
match stream.poll_next(cx) {
Poll::Ready(Some(result)) => match result {
Ok(buf) => Poll::Ready(Some(Ok(buf))),
Err(error) => Poll::Ready(Some(Err(error))),
},
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
None => Poll::Ready(None),
}
}
fn poll_trailers(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
Poll::Ready(Ok(None))
}
}
impl From<Option<SignedRequestPayload>> for RusotoBody {
fn from(inner: Option<SignedRequestPayload>) -> Self {
RusotoBody { inner }
}
}
|
extern crate handlebars;
extern crate html_minifier;
use handlebars::Handlebars;
use html_minifier::HTMLMinifier;
use std::str;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn render(template: &str, ctx: &JsValue, minify: Option<bool>) -> String {
let hbs = Handlebars::new();
let json_value: handlebars::JsonValue = ctx.into_serde().unwrap();
let mut rendered = hbs.render_template(template, &json_value).unwrap();
if minify.unwrap_or(true) {
let mut html_minifier = HTMLMinifier::new();
html_minifier.digest(rendered).unwrap();
rendered = str::from_utf8(html_minifier.get_html())
.unwrap()
.to_string();
}
return rendered;
}
|
#[cfg(test)]
mod tests{
use crate::neurone::{self, FullNet};
#[test]
fn activation_test(){
let i1 = neurone::Neuron::new(1);
let i2 = neurone::Neuron::new(1);
let i3 = neurone::Neuron::new(1);
let mut o0 = neurone::Neuron::new(1);
assert_eq!(o0.activtion([i1,i2,i3].to_vec(), 0).activation,0.8909032)
}
#[test]
fn run_frd(){
let mut net = FullNet::new(1, 2, 1);
let out = net.run_data([1].to_vec());
assert_eq!(out,[0.71818227,0.71818227].to_vec())
}
} |
use crate::InputChannel;
use crate::error::DashPipeError;
use super::RUNTIME;
use log::{error, info};
use futures::{
prelude::*,
Stream,
};
use nitox::{commands::*, NatsClient};
use std::io;
use prometheus::{Counter};
pub struct NatsInput {
subject: String,
queue_group:Option<String>,
nats_client: NatsClient,
}
impl NatsInput {
pub fn new(cluster_uri: &str, a_subject: String, queue_group: Option<String>) -> Result<NatsInput, DashPipeError> {
let nats_client_builder = super::connect_to_nats(cluster_uri);
match RUNTIME.lock().unwrap().block_on(nats_client_builder) {
Ok(client) => {
let ret = NatsInput {
nats_client: client,
queue_group: queue_group,
subject: a_subject,
};
info!("Consuming client successfully created");
Ok(ret)
},
Err(e) => {
let disp = format!("Unable to create nats input: {}", e);
error!("Unable to connect to NATS: {}", e);
Err(DashPipeError::InitializeError(disp))
}
}
}
}
impl InputChannel for NatsInput {
fn start(&self) -> Result<Box<Stream<Item=String, Error = io::Error>>, DashPipeError> {
let group_tag = match self.queue_group.clone(){
Some(s) => s.to_owned(),
None => "None".to_owned(),
};
let msg_recv_counter = register_int_counter!(opts!(
"dashpipe_received_messages",
"Total number of messages received",
labels! {"channel" => "nats", "subject" => &self.subject, "queue_group" => &group_tag, }))
.unwrap();
let receive_err_counter = register_int_counter!(opts!(
"dashpipe_received_messages_error",
"Total number of errors while receiving messages",
labels! {"channel" => "nats", "subject" => &self.subject, "queue_group" => &group_tag, }))
.unwrap();
let parse_err_counter = register_int_counter!(opts!(
"dashpipe_received_messages_parse_error",
"Total number of errors while parsing received messages",
labels! {"channel" => "nats", "subject" => &self.subject, "queue_group" => &group_tag, }))
.unwrap();
let sub_cmd: SubCommand = SubCommand::builder()
.subject(self.subject.to_owned())
.queue_group(match &self.queue_group{
Some(s) => Some(s.clone()),
None => None,
})
.build()
.unwrap();
let receiver = match self.nats_client.subscribe(sub_cmd).wait(){
Ok(r) => r,
Err(e) => {
let disp = format!("Unable to initialize NATS subscription {}", e);
error!("Unable to initialize NATS subscription {}", e);
return Err(DashPipeError::InitializeError(disp))
},
};
let ret = receiver.map_err(move |_| {
receive_err_counter.inc();
io::Error::from(io::ErrorKind::Other)})
.map(
move |msg: Message| {
msg_recv_counter.inc();
let slice = msg.payload.slice_from(0);
String::from_utf8(slice.to_vec())
})
.filter_map(move |res| {
match res{
Ok(s) => Some(s),
Err(_) => {
parse_err_counter.inc();
error!("Unable to parse incoming message as a string, skipping");
None
}
}
});
Ok(Box::new(ret))
}
} |
#[doc = "Reader of register MTLISR"]
pub type R = crate::R<u32, super::MTLISR>;
#[doc = "Reader of field `Q0IS`"]
pub type Q0IS_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Queue interrupt status"]
#[inline(always)]
pub fn q0is(&self) -> Q0IS_R {
Q0IS_R::new((self.bits & 0x01) != 0)
}
}
|
use std::cell::UnsafeCell;
use std::path::PathBuf;
use super::ir::NodeIR;
use crate::cache::NodeCache;
use crate::error::Result;
use crate::execs::{ExecIR, GlobalVars};
use crate::externs::PythonScript;
use crate::n3_std;
use crate::seed::Seed;
use crate::tensor::TensorNode;
pub struct NodeRoot {
pub(crate) seed: Seed,
sources: NodeCache<TensorNode>,
externs: NodeCache<PythonScript>,
pub(crate) parser: crate::Parser,
_thread_unsafe: UnsafeCell<()>,
}
impl NodeRoot {
pub fn new(n3_source_root: Option<&str>) -> Self {
let n3_source_root = n3_source_root
.map(PathBuf::from)
.unwrap_or_else(GlobalVars::get_n3_source_root);
Self {
seed: Seed::default(),
sources: NodeCache::new(n3_std::get_sources(&n3_source_root)),
externs: NodeCache::new(n3_std::get_externs(&n3_source_root)),
parser: crate::Parser::default(),
_thread_unsafe: UnsafeCell::new(()),
}
}
}
impl NodeRoot {
pub fn add_source(&self, name: String, source: String) {
self.sources.add_source(name, source);
}
pub fn add_source_path(&self, name: String, path: String) {
self.sources.add_path(name, path);
}
pub fn add_extern_path(&self, name: String, path: String) {
self.externs.add_path(name, path);
}
pub(crate) fn get(&self, name: &str) -> Result<NodeIR> {
self.sources.get(name, self)?.unwrap_node()
}
pub(crate) fn get_exec(&self, name: &str) -> Result<ExecIR> {
self.sources.get(name, self)?.unwrap_exec()
}
pub(crate) fn get_extern(&self, name: &str) -> Result<PythonScript> {
self.externs.get(name, self)
}
}
|
/// Buka file jika file tidak ada buat baru
/// jika file sudah ada tambah isinya ke pointer terakhir
///
use std::fs::OpenOptions;
use std::io::prelude::*;
fn main() {
let file = OpenOptions::new()
.create(true)
.read(true)
.append(true)
.open("hello.txt");
match file {
Err(e) => eprintln!("{}", e),
Ok(mut f) => {
let _ = f.write_all("Hello world lagu!.".to_owned().as_bytes());
}
}
} |
use num_traits::Pow;
use crate::ast;
pub trait BuildValue {
fn build(&self) -> ast::Value;
}
impl BuildValue for ast::RefVariable {
fn build(&self) -> ast::Value {
match &self.borrow().value {
Some(value) => value.build(),
None => ast::Value::Variable(self.clone()),
}
}
}
impl BuildValue for ast::Value {
fn build(&self) -> Self {
match self {
Self::Bool(_)
| Self::UInt(_)
| Self::Int(_)
| Self::Real(_)
| Self::Dim(_)
| Self::String(_) => self.clone(),
Self::Node(_) => node_variable_should_be_pruned(),
Self::Variable(value) => value.build(),
Self::Expr(value) => value.build(),
Self::List(value) => Self::List(value.iter().map(|x| x.build()).collect()),
Self::Map(value) => Self::Map(
value
.iter()
.map(|(k, v)| (k.clone(), v.as_ref().map(|x| x.build())))
.collect(),
),
}
}
}
impl BuildValue for ast::Expr {
fn build(&self) -> ast::Value {
let lhs = self.lhs.build();
if let Some(rhs) = &self.rhs {
let rhs = rhs.build();
match self.op {
ast::Operator::Add => lhs + rhs,
ast::Operator::Sub => lhs - rhs,
ast::Operator::Mul => lhs * rhs,
ast::Operator::MulInt => {
if lhs.is_atomic() && rhs.is_atomic() {
(lhs.unwrap_uint().unwrap() * rhs.unwrap_uint().unwrap()).into()
} else {
ast::Expr {
op: self.op,
lhs,
rhs: Some(rhs),
}
.into()
}
}
ast::Operator::Div => lhs / rhs,
ast::Operator::Mod => lhs % rhs,
ast::Operator::Pow => lhs.pow(rhs),
ast::Operator::And => lhs & rhs,
ast::Operator::Or => lhs | rhs,
ast::Operator::Xor => lhs ^ rhs,
_ => unreachable!("expected binary operators"),
}
} else {
match self.op {
ast::Operator::Pos => lhs,
ast::Operator::Neg => -lhs,
_ => unreachable!("expected unary operators"),
}
}
}
}
impl<T> BuildValue for Box<T>
where
T: BuildValue,
{
fn build(&self) -> ast::Value {
(**self).build()
}
}
pub(crate) fn node_variable_should_be_pruned() -> ! {
unreachable!("node variable should be pruned.")
}
|
use P59::*;
pub fn main() {
let trees = hbal_trees(3, 'x');
for tree in trees {
println!("{}", tree);
}
}
|
#[doc = "Reader of register CHSELR_1"]
pub type R = crate::R<u32, super::CHSELR_1>;
#[doc = "Writer for register CHSELR_1"]
pub type W = crate::W<u32, super::CHSELR_1>;
#[doc = "Register CHSELR_1 `reset()`'s with value 0"]
impl crate::ResetValue for super::CHSELR_1 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SQ1`"]
pub type SQ1_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ1`"]
pub struct SQ1_W<'a> {
w: &'a mut W,
}
impl<'a> SQ1_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `SQ2`"]
pub type SQ2_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ2`"]
pub struct SQ2_W<'a> {
w: &'a mut W,
}
impl<'a> SQ2_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4);
self.w
}
}
#[doc = "Reader of field `SQ3`"]
pub type SQ3_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ3`"]
pub struct SQ3_W<'a> {
w: &'a mut W,
}
impl<'a> SQ3_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8);
self.w
}
}
#[doc = "Reader of field `SQ4`"]
pub type SQ4_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ4`"]
pub struct SQ4_W<'a> {
w: &'a mut W,
}
impl<'a> SQ4_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 12)) | (((value as u32) & 0x0f) << 12);
self.w
}
}
#[doc = "Reader of field `SQ5`"]
pub type SQ5_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ5`"]
pub struct SQ5_W<'a> {
w: &'a mut W,
}
impl<'a> SQ5_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16);
self.w
}
}
#[doc = "Reader of field `SQ6`"]
pub type SQ6_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ6`"]
pub struct SQ6_W<'a> {
w: &'a mut W,
}
impl<'a> SQ6_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 20)) | (((value as u32) & 0x0f) << 20);
self.w
}
}
#[doc = "Reader of field `SQ7`"]
pub type SQ7_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ7`"]
pub struct SQ7_W<'a> {
w: &'a mut W,
}
impl<'a> SQ7_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24);
self.w
}
}
#[doc = "Reader of field `SQ8`"]
pub type SQ8_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SQ8`"]
pub struct SQ8_W<'a> {
w: &'a mut W,
}
impl<'a> SQ8_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 28)) | (((value as u32) & 0x0f) << 28);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - conversion of the sequence"]
#[inline(always)]
pub fn sq1(&self) -> SQ1_R {
SQ1_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 4:7 - conversion of the sequence"]
#[inline(always)]
pub fn sq2(&self) -> SQ2_R {
SQ2_R::new(((self.bits >> 4) & 0x0f) as u8)
}
#[doc = "Bits 8:11 - conversion of the sequence"]
#[inline(always)]
pub fn sq3(&self) -> SQ3_R {
SQ3_R::new(((self.bits >> 8) & 0x0f) as u8)
}
#[doc = "Bits 12:15 - conversion of the sequence"]
#[inline(always)]
pub fn sq4(&self) -> SQ4_R {
SQ4_R::new(((self.bits >> 12) & 0x0f) as u8)
}
#[doc = "Bits 16:19 - conversion of the sequence"]
#[inline(always)]
pub fn sq5(&self) -> SQ5_R {
SQ5_R::new(((self.bits >> 16) & 0x0f) as u8)
}
#[doc = "Bits 20:23 - conversion of the sequence"]
#[inline(always)]
pub fn sq6(&self) -> SQ6_R {
SQ6_R::new(((self.bits >> 20) & 0x0f) as u8)
}
#[doc = "Bits 24:27 - conversion of the sequence"]
#[inline(always)]
pub fn sq7(&self) -> SQ7_R {
SQ7_R::new(((self.bits >> 24) & 0x0f) as u8)
}
#[doc = "Bits 28:31 - conversion of the sequence"]
#[inline(always)]
pub fn sq8(&self) -> SQ8_R {
SQ8_R::new(((self.bits >> 28) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - conversion of the sequence"]
#[inline(always)]
pub fn sq1(&mut self) -> SQ1_W {
SQ1_W { w: self }
}
#[doc = "Bits 4:7 - conversion of the sequence"]
#[inline(always)]
pub fn sq2(&mut self) -> SQ2_W {
SQ2_W { w: self }
}
#[doc = "Bits 8:11 - conversion of the sequence"]
#[inline(always)]
pub fn sq3(&mut self) -> SQ3_W {
SQ3_W { w: self }
}
#[doc = "Bits 12:15 - conversion of the sequence"]
#[inline(always)]
pub fn sq4(&mut self) -> SQ4_W {
SQ4_W { w: self }
}
#[doc = "Bits 16:19 - conversion of the sequence"]
#[inline(always)]
pub fn sq5(&mut self) -> SQ5_W {
SQ5_W { w: self }
}
#[doc = "Bits 20:23 - conversion of the sequence"]
#[inline(always)]
pub fn sq6(&mut self) -> SQ6_W {
SQ6_W { w: self }
}
#[doc = "Bits 24:27 - conversion of the sequence"]
#[inline(always)]
pub fn sq7(&mut self) -> SQ7_W {
SQ7_W { w: self }
}
#[doc = "Bits 28:31 - conversion of the sequence"]
#[inline(always)]
pub fn sq8(&mut self) -> SQ8_W {
SQ8_W { w: self }
}
}
|
// Copyright 2016 The Cartographer Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use cgmath::{Decomposed, Deg, InnerSpace, Matrix4, One, PerspectiveFov, Quaternion, Rad, Rotation,
Rotation3, Transform, Vector3, Zero};
use opengl;
use std::f32;
#[derive(Debug)]
pub struct Camera {
pub moving_backward: bool,
pub moving_forward: bool,
pub moving_left: bool,
pub moving_right: bool,
pub moving_down: bool,
pub moving_up: bool,
pub width: i32,
pub height: i32,
movement_speed: f32,
theta: Rad<f32>,
phi: Rad<f32>,
moved: bool,
transform: Decomposed<Vector3<f32>, Quaternion<f32>>,
projection_matrix: Matrix4<f32>,
}
impl Camera {
pub fn new(gl: &opengl::Gl, width: i32, height: i32) -> Self {
let mut camera = Camera {
movement_speed: 1.5,
moving_backward: false,
moving_forward: false,
moving_left: false,
moving_right: false,
moving_down: false,
moving_up: false,
moved: true,
theta: Rad(0.),
phi: Rad(0.),
transform: Decomposed {
scale: 1.,
rot: Quaternion::one(),
disp: Vector3::new(0., 0., 150.),
},
// These will be set by set_size().
projection_matrix: One::one(),
width: 0,
height: 0,
};
camera.set_size(gl, width, height);
camera
}
pub fn set_size(&mut self, gl: &opengl::Gl, width: i32, height: i32) {
self.width = width;
self.height = height;
self.projection_matrix = Matrix4::from(PerspectiveFov {
fovy: Rad::from(Deg(45.)),
aspect: width as f32 / height as f32,
near: 0.1,
far: 10000.0,
});
unsafe {
gl.Viewport(0, 0, width, height);
}
}
pub fn get_world_to_gl(&self) -> Matrix4<f32> {
let world_to_camera: Matrix4<f32> = self.transform.inverse_transform().unwrap().into();
self.projection_matrix * world_to_camera
}
/// Update the camera position for the current frame. Returns true if the camera moved in this
/// step.
pub fn update(&mut self) -> bool {
let mut moved = self.moved;
self.moved = false;
let mut pan = Vector3::zero();
if self.moving_right {
pan.x += 1.;
}
if self.moving_left {
pan.x -= 1.;
}
if self.moving_backward {
pan.z += 1.;
}
if self.moving_forward {
pan.z -= 1.;
}
if self.moving_up {
pan.y += 1.;
}
if self.moving_down {
pan.y -= 1.;
}
if pan.magnitude2() > 0. {
moved = true;
let translation = self.transform
.rot
.rotate_vector(pan.normalize() * self.movement_speed);
self.transform.disp += translation;
}
let rotation_z = Quaternion::from_angle_z(self.theta);
let rotation_x = Quaternion::from_angle_x(self.phi);
self.transform.rot = rotation_z * rotation_x;
moved
}
pub fn mouse_drag(&mut self, delta_x: i32, delta_y: i32) {
self.moved = true;
self.theta -= Rad(2. * f32::consts::PI * delta_x as f32 / self.width as f32);
self.phi -= Rad(2. * f32::consts::PI * delta_y as f32 / self.height as f32);
}
pub fn mouse_wheel(&mut self, delta: i32) {
let sign = delta.signum() as f32;
self.movement_speed += sign * 0.1 * self.movement_speed;
self.movement_speed = self.movement_speed.max(0.01);
}
}
|
#![feature(globs)]
extern crate native;
extern crate rocketsauce;
use rocketsauce::*;
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, main)
}
struct BasicGame;
impl BasicGame {
pub fn new() -> BasicGame {
BasicGame
}
}
impl Game for BasicGame {
fn init(&mut self, context: &mut Context) {
let texture: &Texture = &*(context.asset_mgr.get(&Path::new("data/textures/logo.png")).unwrap());
println!("{}", texture.width());
}
fn update(&mut self, context: &mut Context, _: f32) {
if context.keyboard.check_press(keyboard::Escape) {
context.terminate();
}
}
}
fn main() {
let mut context = Context::new(800, 600, "Basic Game");
BasicGame::new().run(&mut context);
} |
test_stdout!(
with_small_integer_divisor_with_underflow_returns_small_integer,
"true\n17592186044416\n"
);
test_stdout!(
with_big_integer_divisor_with_underflow_returns_small_integer,
"true\n1\n"
);
test_stdout!(
with_big_integer_divisor_without_underflow_returns_big_integer,
"true\n70368744177664\n"
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.